[英]Aggregate sum of multiple columns by date in pandas
My df looks like this我的 df 看起来像这样
Date![]() |
Col![]() |
Col1![]() |
---|---|---|
01/01/2022 ![]() |
A![]() |
500 ![]() |
01/01/2022 ![]() |
B![]() |
100 ![]() |
01/01/2022 ![]() |
C ![]() |
400 ![]() |
02/01/2022 ![]() |
A![]() |
400 ![]() |
02/01/2022 ![]() |
B![]() |
150 ![]() |
02/01/2022 ![]() |
C ![]() |
450 ![]() |
My desired output looks like我想要的 output 看起来像
Date![]() |
Total![]() |
---|---|
01/01/2022 ![]() |
1000 ![]() |
02/01/2022 ![]() |
1000 ![]() |
Please help.请帮忙。 I wanna do it automatically (not manually-hardcoded)
我想自动执行(不是手动硬编码)
I am trying this我正在尝试这个
df.groupby('Date')['Col1'].sum()
If you need totals and the separate column values for a given date, follow this general format.如果您需要给定日期的总计和单独的列值,请遵循此通用格式。
needed_columnms = ['List','Of','Needed','Columns']
df_sums = df.groupby('Date')[needed_columns].sum()
df_sums['Total'] = df_sums[needed_columns].sum(1)
df_sums will provide you with a column total and grand total for each of the dates within 'Date'. df_sums 将为您提供“日期”中每个日期的列总计和总计。
Try just summing the entire group, rather than a specific column:尝试只对整个组求和,而不是对特定列求和:
df.groupby('Date').sum()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.