Reputation: 135
I am just wondering how can I aggregate all the results in grouped by pandas data frame.
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
I have tired like this it save only last group.
result = pd.DataFrame(x)
result
Age
5 72
6 54
7 64
how to save all these result in pandas dataframe ?
Expected results
Age
0 54
1 48
2 44
3 64
4 66
5 72
6 54
7 64
Upvotes: 3
Views: 101
Reputation: 8033
Is this what you want?
pd.DataFrame(df['Age']*2)
Output
Age
0 54
1 48
2 44
3 64
4 66
5 72
6 54
7 64
Upvotes: 0
Reputation: 3619
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
Upvotes: 2
Reputation: 1545
You can use transform
:
df['answer'] = df.groupby('id')['Age'].transform(lambda x: x * 2)
output 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
Upvotes: 0