gpt4 book ai didi

python - 使用Python Pandas的数据透视表,单价求和

转载 作者:行者123 更新时间:2023-11-28 22:52:30 25 4
gpt4 key购买 nike

我想使用 py-pandas 从这种数据生成一个数据透视表

id      product  credit
1 book -5
1 ipad -15
1 server -25
2 book -5
15 server -25
2 glass -2
2 glass -2
1 book -5
15 glass -2
1 car -150

到那种电子表格

id        1          2        15
---------------------------------
book -5 (2) -5(1) NA
ipad -15(1) NA NA
server -25(1) NA -25(1)
glass NA -2(2) -2(1)
car -150(1) NA NA

这会将 ID 显示为列,将产品显示为行,单位积分和购买的产品数量。

谢谢你的帮助

-H

最佳答案

主要思想是使用pandas...pivot_table() .

如果您只想求和您的数据,那么np.sum 将执行:

>>> df.pivot_table(cols='id', values='credit', rows='product', aggfunc=np.sum)
id 1 2 15
product
book -10 -5 NaN
car -150 NaN NaN
glass NaN -4 -2
ipad -15 NaN NaN
server -25 NaN -25

或者您可以使用 collections.Counter以接近您需要的格式获取数据(Counter 的性能不是很好,所以要小心这个):

>>> from collections import Counter
>>> df.pivot_table(cols='id', values='credit', rows='product', aggfunc=Counter)
id 1 2 15
product
book {-5: 2} {-5: 1} NaN
car {-150: 1} NaN NaN
glass NaN {-2: 2} {-2: 1}
ipad {-15: 1} NaN NaN
server {-25: 1} NaN {-25: 1}

或者定义自定义函数以获得您所需要的:

>>> from collections import defaultdict
>>> def hlp_count(x):
... d = defaultdict(int)
... for v in x:
... d[v] += 1
... # join in case you have more than one distinct price
... return ', '.join(['{0} ({1})'.format(k, v) for k, v in d.iteritems()])

>>> df.pivot_table(cols='id', values='credit', rows='product', aggfunc=hlp_count)
id 1 2 15
product
book -5 (2) -5 (1) NaN
car -150 (1) NaN NaN
glass NaN -2 (2) -2 (1)
ipad -15 (1) NaN NaN
server -25 (1) NaN -25 (1)

关于python - 使用Python Pandas的数据透视表,单价求和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20399281/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com