python - 如何根据 Pandas 中具有特定值的列将多行合并为一行

标签 python pandas dataframe pandas-groupby

我有一个这样的数据框:

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/

相关文章:

python - 如何在 virtualenv 中 : Install python2. x?

python - 有没有一种简单的方法来交换矩阵中的行以在左侧形成单位矩阵

python - 如何返回与字典中最小值对应的键列表

python - 如何从多个数据帧创建分层多索引数据帧?

python - 将整列追加到字典中

r - 从 xml 中提取信息

python - 尝试使用 Celery 编写时出现 RedisClusterException

pandas - 将多索引数据帧转换为 Xarray 数据集会丢失年度序列或给出错误

r - 在 R 中的嵌套数据框中多次调用 ifelse

r - 在 R 中反转数据帧