Python 数据帧分组查找列上的计数和
我有一个像Python 数据帧分组查找列上的计数和,python,pandas,dataframe,grouping,Python,Pandas,Dataframe,Grouping,我有一个像 customer fruit price 0 cust1 mango 30 1 cust2 apple 45 2 cust1 banana 55 3 cust3 mango 22 4 cust4 banana 54 5 cust3 app
customer fruit price
0 cust1 mango 30
1 cust2 apple 45
2 cust1 banana 55
3 cust3 mango 22
4 cust4 banana 54
5 cust3 apple 55
6 cust2 apple 90
7 cust1 mango 45
8 cust3 banana 45
9 cust2 mango 23
10 cust4 mango 44
我需要=每位顾客在购买芒果和其他水果(即不是芒果本身作为一个类别)上的花费。cust1 mango=75,cust1 other=55,就像每个客户的wise一样
customer price spent_on_mango spent_on_others
0 cust1 75 55
1 cust2 23 135
2 cust3 22 100
3 cust4 44 54
请建议。我们可以将“水果”中不是“芒果”的元素替换为“其他”,然后
groupby
变量('customer'、'fruit'),获得总和和取消堆叠
import pandas as pd
df1.loc[df1.fruit !='mango', 'fruit'] = 'others'
print(df1.groupby(['customer', 'fruit']).sum().unstack())
# price
#fruit mango others
#customer
#cust1 75 55
#cust2 23 135
#cust3 22 100
#cust4 44 54
尝试对某些列进行分组,然后像这样应用sum():
print dframe.groupby(["customer","fruit"]).sum()
正如命令本身所说,它对列进行分组并将值相加
它返回一个包含所需信息的数据框。为什么不创建一列来指示水果是否是芒果,然后将其包含在您的groupby中
df['mango'] = df.fruit == 'mango'
df2 = df.groupby(['customer', 'mango']).sum().unstack()
df2.columns = ['not mango', 'mango']
>>> df2
not mango mango
customer
cust1 55 75
cust2 135 23
cust3 100 22
cust4 54 44
作为替代方案,您可以通过以下方式执行此操作:
这可能很好,但您可以创建所需的“非芒果”:
通常,如果您看到堆栈/取消堆栈,您应该改为尝试“pivot”:。另一种pandas
方法:
df.fruit[df.fruit != 'mango'] = 'other_fruit'
pd.pivot_table(df, 'price', 'customer', 'fruit', np.sum)
fruit mango other_fruit
customer
cust1 75 55
cust2 23 135
cust3 22 100
cust4 44 54
请展示如何从csv中准确初始化DataFrame,我通过将panda导入为pd来阅读。df=pd.read_csv('path')我以前试过这个方法。通过这个方法,我得到了所有水果的总和。但我想另外两列显示两组的花费,一个是在芒果上,另一个不是在芒果上。谢谢。但是有没有任何方法将这些假真重命名为在芒果上花费的钱和在其他人身上花费的钱。或者我如何在两个不同的列中获得这些。,这是一个很大的帮助和一种新的方式
In [13]: mango = res.pop("mango")
In [14]: res.sum(axis=1).to_frame(name="not mango").join(mango)
Out[14]:
not mango mango
customer
cust1 55.0 37.5
cust2 67.5 23.0
cust3 100.0 22.0
cust4 54.0 44.0
df.fruit[df.fruit != 'mango'] = 'other_fruit'
pd.pivot_table(df, 'price', 'customer', 'fruit', np.sum)
fruit mango other_fruit
customer
cust1 75 55
cust2 23 135
cust3 22 100
cust4 44 54