gpt4 book ai didi

python - 存储在新数据框中的 Pandas groupby

转载 作者:行者123 更新时间:2023-11-28 20:36:12 27 4
gpt4 key购买 nike

我有以下代码:

import pandas as pd
df1 = pd.DataFrame({'Counterparty':['Bank','Bank','GSE','PSE'],
'Sub Cat':['Tier1','Small','Small', 'Small'],
'Location':['US','US','UK','UK'],
'Amount':[50, 55, 65, 55],
'Amount1':[1,2,3,4]})

df2=df1.groupby(['Counterparty','Location'])[['Amount']].sum()
df2.dtypes
df1.dtypes

df2 数据框没有我要聚合的列(交易对手和位置)。任何想法为什么会这样? Amount 和 Amount1 都是数字字段。我只想对 Amount 求和并汇总 Amount1

最佳答案

对于来自索引的列,添加 as_index=False 参数或 reset_index :

df2=df1.groupby(['Counterparty','Location'])[['Amount']].sum().reset_index()
print (df2)
Counterparty Location Amount
0 Bank US 105
1 GSE UK 65
2 PSE UK 55

df2=df1.groupby(['Counterparty','Location'], as_index=False)[['Amount']].sum()
print (df2)
Counterparty Location Amount
0 Bank US 105
1 GSE UK 65
2 PSE UK 55

如果此处所有列的聚合发生automatic exclusion of nuisance columns - 列 Sub Cat 被省略:

df2=df1.groupby(['Counterparty','Location']).sum().reset_index()
print (df2)
Counterparty Location Amount Amount1
0 Bank US 105 3
1 GSE UK 65 3
2 PSE UK 55 4


df2=df1.groupby(['Counterparty','Location'], as_index=False).sum()

关于python - 存储在新数据框中的 Pandas groupby,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45619471/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com