如何在Python中同时使用filter、groupby和agg函数



我有一个数据帧如下:

A         B       C
0 asia      1000    ab
1 africa    2000    ab
2 asia      4000    bc
3 asia      6000    cd
4 USA       200     ab

我想筛选A列=亚洲,并按C列对B列组求和。我正在尝试使用:

agg = df[df['A'] = 'asia'].groupby('C')[['B']].sum()

但它只返回一行B列和C列的总和。我想返回整个数据帧。我怎样才能做到这一点?

试试这个:

df1 = df[df['A'] == 'asia'].groupby(['A', 'C'], as_index=False).sum()
print(df1)
A   C     B
0  asia  ab  1000
1  asia  bc  4000
2  asia  cd  6000

我将分两步完成,如下所示。

group = [('asia', data['B'].sum(), c) for c, data in df[df['A'] = 'asia'].groupby('C')]
df_new = pd.DataFrame(group, columns=['A', 'B', 'C'])

最新更新