Skip to content Skip to sidebar Skip to footer

Add Column From One Data Frame To Group-by Data Frame In Python

I have two data frames in python. The first is raw rainfall data for a single day of year and the second is the sum of daily rainfall using group.by. One data frame looks like thi

Solution 1:

Maybe this will work? groupby day month and year as well.

df.groupby(['device_id', 'day', 'month', 'year']).sum()
                                                     rain
device_id                            daymonthyear1d28dz3a-c923-4967-a7bb-5881d232c9a7 311220160.09z849362-b05d-4317-96f5-f267c1adf8d6 311220160.0
a044ag4f-fd7c-4ae4-bff3-9158cebad3b1 311220160.0
ceez972b-135f-45b3-be4w-7c23102676bq 311220160.2
e7z581f0-2693-42ad-9896-0048550ccda7 311220160.0

Or you could add reset_index to return these columns to the DataFrame like

df.groupby(['device_id', 'day', 'month', 'year']).sum().reset_index()

0  1d28dz3a-c923-4967-a7bb-5881d232c9a7   31     12  2016   0.0
1  9z849362-b05d-4317-96f5-f267c1adf8d6   31     12  2016   0.0
2  a044ag4f-fd7c-4ae4-bff3-9158cebad3b1   31     12  2016   0.0
3  ceez972b-135f-45b3-be4w-7c23102676bq   31     12  2016   0.2
4  e7z581f0-2693-42ad-9896-0048550ccda7   31     12  2016   0.0

Or the following should match your index / column structure exactly.

df.groupby(['device_id', 'day', 'month', 'year']).sum().reset_index([1, 2, 3])

Post a Comment for "Add Column From One Data Frame To Group-by Data Frame In Python"