如何根据类别添加总收入
How to add a total income based on category
我有这样的数据框
我想根据类别对客户的收入进行分组汇总
第一:我想把客户的收入按照月份分组
其二:客户的收入按月份分组后,我想按进出口分组
第三:我想根据以下条件对客户的收入进行分组:"charge, interest, and cost"
第四:我想根据"charge, interest, and cost"
添加一个客户的总收入
我的预期
这是我的最后一个代码
df = df.groupby ("[information", "Name"] ). Agg("sum)
我很困惑 python 中的“合并和单元格”以及基于类别求和
您可以使用具有很大灵活性的 pivot_table
:
In [11]: df
Out[11]:
Month Name Info Ex/Im Income
0 Jan Alice charge export 100
1 Jan Alice interest import 10
2 Jan Bob cost export 200
3 Feb Alice charge export 100
4 Jan Bob cost export 200
In [12]: df.pivot_table(index="Name", columns=["Month", "Ex/Im", "Info"], values="Income", aggfunc='sum')
Out[12]:
Month Feb Jan
Ex/Im export export import
Info charge charge cost interest
Name
Alice 100.0 100.0 NaN 10.0
Bob NaN NaN 400.0 NaN
In [13]: df.pivot_table(index="Name", columns=["Month", "Ex/Im", "Info"], values="Income", aggfunc='sum', fill_value=0)
Out[13]:
Month Feb Jan
Ex/Im export export import
Info charge charge cost interest
Name
Alice 100 100 0 10
Bob 0 0 400 0
我有这样的数据框
我想根据类别对客户的收入进行分组汇总
第一:我想把客户的收入按照月份分组
其二:客户的收入按月份分组后,我想按进出口分组
第三:我想根据以下条件对客户的收入进行分组:"charge, interest, and cost"
第四:我想根据"charge, interest, and cost"
添加一个客户的总收入我的预期
这是我的最后一个代码
df = df.groupby ("[information", "Name"] ). Agg("sum)
我很困惑 python 中的“合并和单元格”以及基于类别求和
您可以使用具有很大灵活性的 pivot_table
:
In [11]: df
Out[11]:
Month Name Info Ex/Im Income
0 Jan Alice charge export 100
1 Jan Alice interest import 10
2 Jan Bob cost export 200
3 Feb Alice charge export 100
4 Jan Bob cost export 200
In [12]: df.pivot_table(index="Name", columns=["Month", "Ex/Im", "Info"], values="Income", aggfunc='sum')
Out[12]:
Month Feb Jan
Ex/Im export export import
Info charge charge cost interest
Name
Alice 100.0 100.0 NaN 10.0
Bob NaN NaN 400.0 NaN
In [13]: df.pivot_table(index="Name", columns=["Month", "Ex/Im", "Info"], values="Income", aggfunc='sum', fill_value=0)
Out[13]:
Month Feb Jan
Ex/Im export export import
Info charge charge cost interest
Name
Alice 100 100 0 10
Bob 0 0 400 0