How can I resample dataframe columns?

2.6k views Asked by At

I have a dataframe with 200 columns whose headers are formatted as datetime

2001-01-01 | 2001-02-01 | 2001-03-01 | and so on

I would like to resample the columns so I get columns of quarterly means

2001q01 | 2001q02 | and so on

Here is my resample line:

df.resample('Q', axis=1)

Unfortunately I am getting an error because my dataframe as an integer index column and, as I understand it, resample is trying to execute on the index too.

TypeError: Only valid with DatetimeIndex, TimedeltaIndex or PeriodIndex, but got an instance of 'Index'

Can I have a dataframe with no index? If so, how do I create a dataframe with no index? If not, is there a way to call resample on just my columns of data?

2

There are 2 answers

5
Psidom On

As the error says, your column index are not DatetimeIndex, you need to convert them to DatetimeIndex firstly:

df.columns = pd.to_datetime(df.columns)

To expand the comments, if your data frame has columns from 7 to 206 related to datetime:

datetime_df = df.iloc[:, 7:207]
datetime_df.columns = pd.to_datetime(datetime_df.columns)
pd.concat([df.iloc[:,:7], datetime_df.resample("Q", axis=1).mean(), df.iloc[:,208:]], axis = 1)
0
Ted Petrou On

Your columns are not datetime type. You need to convert them to datetime and then resample.

df.columns = pd.to_datetime(df.columns)