Reputation: 582
It might not be clear from the title but I want to do something like this using a sorted pandas dataframe:
suppose the dataframe is something like this:
name amount
abc 25
abc 45
xyz 20
xyz 50
xyz 55
Now what I want to do is do a groupby on this dataframe by names.
And then loop over the groups one by one,and do some processing on them.
That is on first loop I would want to store the group abc into another intermediate dataframe process it and so on:
so while looping:
that is first iteration:
intermediate dataframe should have
name amount
abc 25
abc 45
then next iteration:
intermediate dataframe should have
name amount
xyz 20
xyz 50
xyz 55
So, I want to do this. I am not sure how to do this.
Upvotes: 2
Views: 706
Reputation: 862691
If need loop DataFrameGroupBy
object:
for idx, df in df.groupby('name'):
print (df)
name amount
0 abc 25
1 abc 45
name amount
2 xyz 20
3 xyz 50
4 xyz 55
If need some processing use groupby
with apply
:
def f(x):
print (x)
df = df.groupby('name').apply(f)
print (df)
Also check flexible apply in docs.
Upvotes: 3