【问题标题】:Convert Pandas tseries object to a DataFrame将 Pandas tseries 对象转换为 DataFrame
【发布时间】:2017-01-13 01:05:57
【问题描述】:

我希望将以下<'pandas.tseries.resample.DatetimeIndexResampler'> 类型对象转换为pandas DataFrame 对象(<'pandas.core.frame.DataFrame'>)。但是我在 pandas 文档中找不到相关功能来允许我这样做。

数据采用以下形式:

                  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
...

谁能提供替代解决方案?

【问题讨论】:

  • 它们的功能基本相同。数据框是数据列和索引。系列对象基本上是一列数据和一个索引。你需要数据框做什么?

标签: python pandas dataframe time-series resampling


【解决方案1】:

您需要一些聚合函数,例如 summean

以您的数据为例:

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

【讨论】:

    猜你喜欢
    • 2015-09-15
    • 1970-01-01
    • 2019-01-14
    • 1970-01-01
    • 2014-10-05
    • 2022-07-28
    • 2019-02-04
    • 2017-03-17
    • 2017-03-23
    相关资源
    最近更新 更多