(我认为)我有一个数据集,其中的列代表 datetime
间隔
列在日期时间中转换为:
for col in df.columns:
df.rename({col: pd.to_datetime(col, infer_datetime_format=True)}, inplace=True)
然后,我需要使用 mean
重新采样
到季度中
我试过了
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
函数还是错误的采样?
最佳答案
(我认为)您正在重命名每个列标题,而不是将整个列对象设为 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
关于python - 重新采样 Pandas 列日期时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41353623/