Convert Pandas tseries object to a DataFrame

2019-07-11 14:24发布

问题:

I wish to convert the following <'pandas.tseries.resample.DatetimeIndexResampler'> type object into a pandas DataFrame object (<'pandas.core.frame.DataFrame'>). However I cannot find the relevant function in the pandas documentation to allow me to do this.

The data takes the following form:

                  M30
Date                 
2016-02-29  -61.187699
2016-03-31  -60.869565
2016-04-30  -61.717922
2016-05-31  -61.823966
2016-06-30  -62.142100
...

Can anyone provide an alternative solution?

回答1:

You need some aggregate function like sum or mean.

Sample with your data:

print (df)
                  M30
Date                 
2016-02-29 -61.187699
2016-03-31 -60.869565
2016-04-30 -61.717922
2016-05-31 -61.823966
2016-06-30 -62.142100

#resample by 2 months
r = df.resample('2M')
print (r)
DatetimeIndexResampler [freq=<2 * MonthEnds>, 
                        axis=0, 
                        closed=right, 
                        label=right, 
                        convention=start, 
                        base=0]
#aggregate sum
print (r.sum())
                   M30
Date                  
2016-02-29  -61.187699
2016-04-30 -122.587487
2016-06-30 -123.966066

#aggregate mean
print (r.mean())
                  M30
Date                 
2016-02-29 -61.187699
2016-04-30 -61.293743
2016-06-30 -61.983033

#aggregate first
print (r.first())
                  M30
Date                 
2016-02-29 -61.187699
2016-04-30 -60.869565
2016-06-30 -61.823966