聚合组导致熊猫数据框

时间:2019-09-07 05:02:09

标签: python python-3.x pandas aggregate

我只是想知道如何将所有结果汇总到按熊猫数据框分组的地方。

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

3 个答案:

答案 0 :(得分:2)

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

答案 1 :(得分:0)

您可以使用transform

df['answer'] = df.groupby('id')['Age'].transform(lambda x: x * 2)

输出df:

    id  Age Qualification   answer
0   1   27  Msc             54
1   1   24  MA              48
2   2   22  MCA             44
3   2   32  Phd             64
4   2   33  B.Tech          66
5   3   36  B.com           72
6   3   27  Msc             54
7   3   32  MA              64

答案 2 :(得分:0)

这是您想要的吗?

inspect element

输出

pd.DataFrame(df['Age']*2)