我有一个这样的数据框:
item_id revenue month year
1 10.0 01 2014
1 5.0 02 2013
1 6.0 04 2013
1 7.0 03 2013
2 2.0 01 2013
2 3.0 03 2013
3 5.0 04 2013
我尝试获取 2013 年 1 月到 3 月每个项目的收入,如下 DataFrame:
item_it revenue year
1 12.0 2013
2 5.0 2013
3 0 2013
但是,我对如何在 Pandas 中实现它感到困惑。任何帮助将不胜感激。
最佳答案
您可以先进行切片,然后groupby
和重新索引
以包含0
值。
month_start, month_end = 1, 3
year = 2013
res = df.loc[df['month'].between(month_start, month_end) & df['year'].eq(year)]\
.groupby('item_id')['revenue'].sum()\
.reindex(df['item_id'].unique()).fillna(0)\
.reset_index('revenue').assign(year=year)
print(res)
item_id revenue year
0 1 12.0 2013
1 2 5.0 2013
2 3 0.0 2013
关于python - 如何根据 Pandas 中具有特定值的列将多行合并为一行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53335691/