Pandas 的 Reindex 方法不遵守设置的频率

Reindex method of Pandas does not respect the set frequency

我有一个 Pandas DataFrame,其中包含每日 DatetimeIndex。我正在尝试应用 Resample 方法将值汇总到这样的月度系列中:

>>> aggVols.resample('M',axis=1).sum()

但是当我尝试这个时,我得到了错误

TypeError: Only valid with DatetimeIndex or PeriodIndex

我注意到未设置对象索引的频率 (None)。

>>>aggVols.index
<class 'pandas.tseries.index.DatetimeIndex'>
[2016-01-04, ..., 2016-07-01]
Length: 130, Freq: None, Timezone: None

所以我首先将频率设置为每天(工作日)并重置索引以便我可以应用重采样:

>>> aggVols    = aggVols.reindex(aggVols.asfreq('B').index)
>>> aggVols.index
<class 'pandas.tseries.index.DatetimeIndex'>
[2016-01-04, ..., 2016-07-01]
Length: 130, Freq: B, Timezone: None

但我仍然遇到与重采样函数相同的错误:

TypeError: Only valid with DatetimeIndex or PeriodIndex

索引有什么问题?为什么无效? 如果我将频率设置为 D,我会得到同样的错误。

谢谢!

改变

aggVols.resample('M',axis=1).sum()

aggVols.resample('M',axis=0).sum()

您的 DatetimeIndex 在行上(不是列上)。

一般来说,轴 0 是行,轴 1 是列,轴 2 是高度,轴 3-N ......好吧,它们被认为更抽象。

参见 the NumPy docs 的 "along an axis" 部分。

终于搞定了。方法用错了最后的操作,就好像是一个系列。正确的代码是:

aggVols.resample('M',axis=0,how=sum)