我是熊猫的新手,我正在尝试使用 group by 并在新列中创建一个列表。我的数据框中有 3 列,我创建了第 4 列(New_List)来从另一列创建一个列表,如下所示:使用以下代码:
new_df = df.join(pd.Series(df.groupby(by='NO_ACCOUNTS').apply(lambda x: list(x.Bucket)), name="list_of_b"), on='NO_ACCOUNTS')
Account_Number Bucket Number_Transactions New_List
ABA APP 155 [APP]
ABC APP 1352 [APP]
AAA APP 90 [API,APP]
AAA API 5 [API,APP]
我希望获得 3 列所需的输出:
Account_Number Number_Transactions New_List
ABA 155 [APP]
ABC 1352 [APP]
AAA 95 [API,APP]
您可以agg
重新排列两列:
out = (df.groupby("Account_Number", sort=False, as_index=False)
.agg(Number_Transactions=("Number_Transactions", "sum"),
New_List=("Bucket", list)))
它首先分组,Account_Number
同时保持其顺序,sort=False
而不是索引as_index=False
,然后Number_Transactions
用求和聚合列并将其指定为相同名称的列,类似地,聚合Bucket
列list
并将其分配给New_List
输出中的列,
要得到
>>> out
Account_Number Number_Transactions New_List
0 ABA 155 [APP]
1 ABC 1352 [APP]
2 AAA 95 [APP, API]
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句