Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/341.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 返回groupby之后的所有行(即不减少作为组键唯一值的行数)_Python_Pandas_Pandas Groupby - Fatal编程技术网

Python 返回groupby之后的所有行(即不减少作为组键唯一值的行数)

Python 返回groupby之后的所有行(即不减少作为组键唯一值的行数),python,pandas,pandas-groupby,Python,Pandas,Pandas Groupby,教程中的以下代码产生以下结果: 代码: 结果: 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.02383

教程中的以下代码产生以下结果:

代码:

结果:

     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快速高效地完成这项工作

提前感谢

与指定列一起使用:

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

您也可以使用
apply
。对每个组执行该操作,但返回该组的所有行

def my_func(x):
    x["D"] = x.C.mean()
    return x
grouped = df.groupby('A', as_index=False).apply(my_func)
print(grouped)

哇!魔术谢谢你。也很好
def my_func(x):
    x["D"] = x.C.mean()
    return x
grouped = df.groupby('A', as_index=False).apply(my_func)
print(grouped)