I have a dataframe
with dates as columns. I'd like to average the values from daily to a monthly level. I've tried with Time Grouper and Resample, but it doesn't like the columns names are strings and I can seem to figure out how to make columns into something like a DatetimeIndex
.
My starting dataframe:
import pandas as pd
df = pd.DataFrame(data=[[1,2,3,4],[5,6,7,8]],
columns=['2013-01-01', '2013-01-02', '2013-02-03', '2013-02-04'],
index=['A', 'B'])
Desired Output:
2013-01-01 2013-02-01
A 1.5 3.5
B 5.6 7.5
You can using resample
df.columns = pd.to_datetime(df.columns)
df.T.resample('M').mean().T
Out[409]:
2013-01-31 2013-02-28
A 1.5 3.5
B 5.5 7.5
Or groupby
one
axis=1
df.groupby(pd.to_datetime(df.columns).to_period('M'),1).mean()
Out[412]:
2013-01 2013-02
A 1.5 3.5
B 5.5 7.5
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With