gpt4 book ai didi

python - 返回 groupby pandas 之后的所有行(即不是减少的行数,这是组键的唯一值)

转载 作者:太空宇宙 更新时间:2023-11-04 02:21:31 25 4
gpt4 key购买 nike

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

代码:

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 快速高效地执行此操作

提前致谢

最佳答案

使用GroupBy.transform指定列:

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

关于python - 返回 groupby pandas 之后的所有行(即不是减少的行数,这是组键的唯一值),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51495782/

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