Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pandas Resample on Date Columns

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
like image 705
user2242044 Avatar asked Dec 01 '22 11:12

user2242044


1 Answers

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
like image 117
BENY Avatar answered Dec 28 '22 13:12

BENY