python - Groupby 多索引 pandas 系列使用 agg 求和并应用列表

标签 python pandas

我有两个多索引系列

系列1

Company Name     Product     Price        TransactionID
Company A        Apple       10           T0001
Company B        Grapes      20           T0002
                 Orange      30           T0003

系列2

Company Name     Product     Price        TransactionID
Company A        Orange      10           T0004
                 Apple       20           T0005
Company B        Orange      20           T0006

我想组成如下系列

Company Name     Product     Sum_price    TransactionID
Company A        Orange      10           [T0004]
                 Apple       30           [T0001,T0005]
Company B        Orange      50           [T0003,T0006]
                 Grapes      20           [T0002]

来自Group dataframe and get sum AND count?表明我可以使用 .agg 同时进行求和和计数,但是如何将 .apply(list) 和求和一起应用?现在,我已经应用了代码Pandas: adding multiindex Series/Dataframes containing lists形成两个系列,一个是 sum,另一个是带有 transactionID 的系列。我想我可以将两个系列连接在一起,但我只是想看看是否有更好的方法。

最佳答案

使用concat聚合 aggregate使用 sum 并转换为 list:

df = (pd.concat([df1, df2])
        .groupby(['Company Name', 'Product'], as_index=False)
        .agg({'Price':'sum', 'TransactionID': lambda x: x.tolist()})
     )
print (df)
  Company Name Product  Price   TransactionID
0    Company A   Apple     30  [T0001, T0005]
1    Company A  Orange     10         [T0004]
2    Company B  Grapes     20         [T0002]
3    Company B  Orange     50  [T0003, T0006]

关于python - Groupby 多索引 pandas 系列使用 agg 求和并应用列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52946348/

相关文章:

python - 如何发送带有特定变量的用户名和密码的后请求身份验证?

android - 如何使用 pidcat?

python-3.x - 如何在 python 模块 pandas 中读取 "\n\n"?

python-3.x - 如何使用 PIL 保存具有自定义名称的图像?

python - 值错误: ('The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().' , 'occurred at index 0')

python - 如何有效地映射 pandas DataFrame 上的转换

python - libcurl 在curl 和curl-config 中不匹配

javascript - Node.JS-R,Python 繁重计算识别回调何时返回并存储该结果

python - 在Python中使用Selenium选择子元素

python - Pandas 四舍五入,这是一个错误吗?