Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a data frame for each group in the pandas.groupby function?

Tags:

python

pandas

I have a data frame which has been grouped by 'hour'. I want to use a for loop which loops through each group and creates a data frame for each group. The code I'm using at the moment only creates a data frame for the last group that it iterates through. Any suggestions on how I can get it to work properly?

for name, group in data.groupby('hour'):
    d = {'group_' + str(name) : group}
like image 324
daniel3412 Avatar asked Dec 03 '25 17:12

daniel3412


1 Answers

You're overwriting your object each time you want this:

d = {}
for name, group in data.groupby('hour'):
    d['group_' + str(name)] = group
like image 61
EdChum Avatar answered Dec 09 '25 17:12

EdChum



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!