Pandas数据帧按两列分组并汇总一列

2024-05-23 21:47:00 发布

您现在位置:Python中文网/ 问答频道 /正文

我有以下格式的熊猫数据帧:

d = {'buyer_code': ['A', 'B', 'C', 'A', 'A', 'B', 'B', 'A', 'C'], 'dollar_amount': ['2240.000', '160.000', '300.000', '10920.000', '10920.000', '235.749', '275.000', '10920.000', '300.000']}
df = pd.DataFrame(data=d)
df

我的数据帧是这样的:

^{pr2}$

我用groupby列出了每个买家和相应的美元金额。在

df.groupby(['buyer_code', 'dollar_amount']).size()

结果是:

buyer_code  dollar_amount
A           10920.000        3
            2240.000         1
B           160.000          1
            235.749          1
            275.000          1
C           300.000          2
dtype: int64

现在我要dollamount乘以它的计数,然后将每个买家的所有金额相加。在

Lets say for example buyer_code "A" should have (10920.000 * 3) + (2240.000 * 1)

结果应该是这样的:

buyer_code  dollar_amount
A           35000
B           670.749
C           600.000

我怎样才能得到这个输出?在


Tags: 数据dataframedfdatasize格式codebuyer
2条回答

unstack您的结果,然后使用dot-

i = df.groupby(['buyer_code', 'dollar_amount']).size().unstack()
i.fillna(0).dot(i.columns.astype(float))

buyer_code
A    35000.000
B      670.749
C      600.000
dtype: float64

或者

^{pr2}$

如果您要对中间结果groupby执行其他操作,则这是可以的,因为需要对其进行计算。如果不是,那么groupby+sum在这里更有意义。在

使用groupby+聚合sum

df['dollar_amount'] = df['dollar_amount'].astype(float)
a = df.groupby('buyer_code', as_index=False).sum()
print (a)
  buyer_code  dollar_amount
0          A      35000.000
1          B        670.749
2          C        600.000

相关问题 更多 >