使用 pandas 写入 csv,我想要每个唯一来源的月收入总和。月份采用日期时间格式。
我尝试过重采样和groupby方法,但是groupby忽略了月份并且重采样忽略了源。我目前有一个以 Month 和 Source 作为索引的多级索引。
Month Source Income
2019-03-01 A 100
2019-03-05 B 50
2019-03-06 A 4
2019-03-22 C 60
2019-04-23 A 40
2019-04-24 A 100
2019-04-24 C 30
2019-06-1 C 100
2019-06-1 B 90
2019-06-8 B 20
2019-06-12 A 50
2019-06-27 C 50
我可以按忽略日期的源进行分组,或者我可以对忽略源的日期进行重新采样。我想要每个独特来源的每月总金额。
最佳答案
月份列中的内容是时间戳。因此,您可以分离此 Timestamp 的月份属性,然后应用 groupby 方法,如下所示:
df.columns = ['Timestamp', 'Source', 'Income']
month_list = []
for i in range(len(df)):
month_list.append(df.loc[i,'Timestamp'].month)
df['Month'] = month_list
df1 = df.groupby(['Month', 'Source']).sum()
输出应该是这样的:
Income
Month Source
3 A 104
B 50
C 60
4 A 140
C 30
6 A 50
B 110
C 150
关于python - 使用 pandas 转 csv,如何在多级索引中组织时间和数值数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56485558/