python - Pandas 日期时间索引类型错误

标签 python pandas dataframe datetime

我试图做这里所做的事情:Pandas resampling with custom volume weighted aggregation但是我的索引遇到了类型错误。
我有这样的数据:

                         Dates       P   Q
0   2020-09-07 01:20:24.738686  7175.0  21
1   2020-09-07 01:45:27.540590  7150.0   7
2   2020-09-07 03:48:49.120607  7125.0   4
3   2020-09-07 04:45:50.972042  7125.0   6
4   2020-09-07 05:36:23.139612  7125.0   2
我使用 print(df.dtypes) 检查类型返回:
Dates    datetime64[ns]
P               float64
Q                 int64
dtype: object
然后我将索引设置为日期使用df = df.set_index(pd.DatetimeIndex(df['Dates']))然后我删除日期列以便使用 df = df.drop(['Dates'], axis=1) 更容易阅读
这给了我
                                 P   Q
Dates                                 
2020-09-07 01:20:24.738686  7175.0  21
2020-09-07 01:45:27.540590  7150.0   7
2020-09-07 03:48:49.120607  7125.0   4
2020-09-07 04:45:50.972042  7125.0   6
2020-09-07 05:36:23.139612  7125.0   2
然后我尝试重新采样:
def vwap(data):
    price = data.P
    quantity = data.Q

    top = sum(price * quantity)
    bottom = sum(quantity)

    return top / bottom

df2 = df.resample("5h",axis=1).apply(vwap)
这会导致错误 TypeError: Only valid with DatetimeIndex, TimedeltaIndex or PeriodIndex, but got an instance of 'Index'查看具有相似名称的其他堆栈溢出条目,它们的问题主要是日期时间仅看起来像日期时间,但实际上并未格式化为日期时间。这不是这里的情况,因为我们之前可以看到 Dates 列的类型为 datetime64[ns]此外,如果我这样做 print(df.index.dtype) ,我得到:
datetime64[ns]
有什么建议?如果有帮助,很高兴澄清任何事情或提供更多代码。

最佳答案

删除 axis=1参数和使用 pd.Grouper作品:

df.groupby(pd.Grouper(freq="5h")).apply(vwap)
Dates
2020-09-07 00:00:00    7157.236842
2020-09-07 05:00:00    7125.000000
dtype: float64
如果您想要具有信息性列名称的数据框,请使用 reset_index :
df.groupby(pd.Grouper(freq="5h")).apply(vwap).reset_index(name="vwap")
                Dates         vwap
0 2020-09-07 00:00:00  7157.236842
1 2020-09-07 05:00:00  7125.000000

关于python - Pandas 日期时间索引类型错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63967719/

相关文章:

python - Dask 2.1.0, key 错误 : 'Column not found: 0'

python - 为什么 key = model_instance.key 没有!!!在 db 到 ndb 文档的旁边?

python - 线程模块在 uwsgi 后面时非常慢

python - 如何在Python中注入(inject)URL查询字符串参数?

python - 为什么这段代码可以在不导入 sklearn 的情况下使用 sklearn 函数?

python - Python-无法读取大文件

python - 遍历字符串列并对 Pandas 中的单元格值进行排序

python - 如何将嵌套字典转换为 pandas DataFrame?

r - 当所有列都大于一个值时过滤行

r - 用行均值查找和替换缺失值