gpt4 book ai didi

python - 聚合组产生 Pandas 数据框

转载 作者:行者123 更新时间:2023-11-28 17:56:50 24 4
gpt4 key购买 nike

我只是想知道如何汇总按 pandas 数据框分组的所有结果。

data1 = {'id':['1', '1', '2', '2', '2', '3', '3', '3'],  
'Age':[27, 24, 22, 32, 33, 36, 27, 32],
'Qualification':['Msc', 'MA', 'MCA', 'Phd','B.Tech', 'B.com', 'Msc', 'MA']
}
df = pd.DataFrame(data1)


grp = df.groupby('id')
for name, group in grp:
x = group.Age * 2
print (x)

0 54
1 48
Name: Age, dtype: int64
2 44
3 64
4 66
Name: Age, dtype: int64
5 72
6 54
7 64
Name: Age, dtype: int64

我已经厌倦了这样它只保存最后一组。

result = pd.DataFrame(x) 
result

Age
5 72
6 54
7 64

如何将所有这些结果保存在 pandas dataframe 中?

预期结果

Age 
0 54
1 48
2 44
3 64
4 66
5 72
6 54
7 64

最佳答案

data1 = {'id':['1', '1', '2', '2', '2', '3', '3', '3'],  
'Age':[27, 24, 22, 32, 33, 36, 27, 32],
'Qualification':['Msc', 'MA', 'MCA', 'Phd','B.Tech', 'B.com', 'Msc', 'MA']
}
df = pd.DataFrame(data1)

grp = df.groupby('id')
x = [] # Create an empty list

for name, group in grp:
b = group.Age * 2 # Do your group vise operations
x.extend(b) # Extend your list with with your restuls

result = pd.DataFrame(x, columns=['Age'])
print(result)


Age
0 54
1 48
2 44
3 64
4 66
5 72
6 54
7 64

关于python - 聚合组产生 Pandas 数据框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57830819/

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