教程中的以下代码产生以下结果:
代码:
import pandas as pd
import numpy as np
df = pd.DataFrame({'A' : ['foo', 'bar', 'foo', 'bar',
'foo', 'bar', 'foo', 'foo'],
'B' : ['one', 'one', 'two', 'three',
'two', 'two', 'one', 'three'],
'C' : np.random.randn(8),
'D' : np.random.randn(8)})
print(df)
grouped = df.groupby('A').mean()
print(grouped)
结果:
A B C D
0 foo one -0.787410 -0.857863
1 bar one 0.140572 1.330183
2 foo two -0.770166 2.123528
3 bar three -0.965523 0.771663
4 foo two 0.215037 -0.597935
5 bar two -1.023839 -0.248445
6 foo one -1.377515 2.041921
7 foo three -0.314333 1.379423
C D
A
bar -0.616263 0.617800
foo -0.606877 0.817815
但是我希望看到所有的行,如下所示:
0 foo one -0.606877 0.817815
1 bar one -0.616263 0.617800
2 foo two -0.606877 0.817815
3 bar three -0.616263 0.617800
4 foo two -0.606877 0.817815
5 bar two -0.616263 0.617800
6 foo one -0.606877 0.817815
7 foo three -0.606877 0.817815
我也开放使用任何其他库。我只需要使用python3快速高效地完成此任务
预先感谢
答案 0 :(得分:2)
Use GroupBy.transform
with specifying columns:
cols = ['C','D']
df[cols] = df.groupby('A')[cols].transform('mean')
print(df)
A B C D
0 foo one 0.444616 -0.232363
1 bar one 0.173897 -0.603437
2 foo two 0.444616 -0.232363
3 bar three 0.173897 -0.603437
4 foo two 0.444616 -0.232363
5 bar two 0.173897 -0.603437
6 foo one 0.444616 -0.232363
7 foo three 0.444616 -0.232363
答案 1 :(得分:0)
您也可以使用apply
。在每个组上执行该操作,但返回该组的所有行。
def my_func(x):
x["D"] = x.C.mean()
return x
grouped = df.groupby('A', as_index=False).apply(my_func)
print(grouped)