【问题标题】:Resampling pandas columns datetime重新采样熊猫列日期时间
【发布时间】:2016-12-27 23:50:30
【问题描述】:

(我认为)我有一个数据集,其中的列代表 datetime 间隔

列在日期时间中转换为:

    for col in df.columns:
        df.rename({col: pd.to_datetime(col, infer_datetime_format=True)}, inplace=True)

然后,我需要使用mean 将列(年和月'2001-01')分成季度

我试过了

df = df.resample('1q', how='mean', axis=1)

DataFrame 也有一个多索引集 ['RegionName', 'County']

但我得到了错误:

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

问题出在to_datetime函数还是错误采样?

【问题讨论】:

  • 您可以发布数据框的前几行吗?根据您提供的信息,df.rename 语句应该会失败。

标签: python datetime pandas


【解决方案1】:

(我认为)您正在重命名每个列标题,而不是使整个列对象成为 DatetimeIndex

试试这个:

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

然后运行你的resample


注意:
在转换为DatetimeIndex 后,我会使用period。这样,您会在列标题中获得期间,而不是季度的结束日期。

df.groupby(df.columns.to_period('Q'), axis=1).mean()

演示

df = pd.DataFrame(np.arange(12).reshape(2, -1),
                  columns=['2011-01-31', '2011-02-28', '2011-03-31',
                           '2011-04-30', '2011-05-31', '2011-06-30'])

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

print(df.groupby(df.columns.to_period('Q'), axis=1).mean())

   2011Q1  2011Q2
0       1       4
1       7      10

【讨论】:

  • 但是列的值是另一个信息(价格 - 我想要三个月的平均值(三列)。我实际上希望将头部作为 DateTime 以便我可以将月份汇总为季度.
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-02-20
  • 2021-03-11
  • 1970-01-01
  • 2013-01-09
  • 2020-06-08
  • 1970-01-01
  • 2019-07-04
相关资源
最近更新 更多