'Keep columns while groupby(periodindex) df in pandas

I would like to keep other columns that the df has

df=df.groupby(pd.PeriodIndex(df['date'], freq='M'))['Close/Last'].mean().reset_index()

How can I keep other columns in df?



Solution 1:[1]

I think .agg() will fit here perfectly:

Just remember to import numpy as np

instead of:

df=df.groupby(pd.PeriodIndex(df['date'], freq='M'))['Close/Last'].mean().reset_index()

try this:

df=df.groupby(pd.PeriodIndex(df['date'], freq='M')).agg({'Close/Last': (np.mean),'Volume':'first','Name':'first'})

.agg() allows you to choose what to do with the columns (apply functions), but if you just want to keep them, use .agg({'col1': 'first', 'col2': 'first', ...} etc.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 guardian