python - 如何按日期时间索引熊猫数据框?
问题描述
我正在使用 django_pandas 包从存储的 Django 模型中获取 Pandas 数据帧。
df = qs.to_dataframe(['time', 'price_open', 'price_high', 'price_low', 'price_close'], index='time')
现在我想通过日期时间访问数据框,但是,这不起作用。打印 df 看起来像这样,其中时间列的位置很奇怪:
如果我这样做,print(df.keys())
我会得到以下结果: Index(['price_open', 'price_high', 'price_low', 'price_close', ], dtype='object') 但我更期待时间。此外, df.columns 不包含时间,而只包含其他列。
如何在给定的日期时间访问 df?为什么时间不是df的关键?谢谢!
解决方案
正如@ThePorcius 所指出的,reset_index
应该给你时间栏。
df = df.reset_index()
根据文档,您可以使用on
参数 inresample
来使用列而不是索引。您需要确保该time
列是datetime
.
dailyFrame=(
df.resample('D', on='time')
.agg({'price_open': 'first', 'price_high': 'max', 'price_low': 'min', 'price_close': 'last'})
)
推荐阅读
- python - 运行回归后,如何摆脱获得负系数的列并使用剩余的列重新运行回归?使用 Python
- visual-studio-code - 如何设置工作区中文件夹之间的依赖关系?
- flutter - flutter_ffmpeg 包名
- vb.net - VB.net HTTP POST 请求
- javascript - CSS 过渡百分比(用于进度条)
- css - 在产品页面图像滑块上自动移动(滚动)产品缩略图
- python - 在 python 中使用 ghostscript 和 facturx 库创建符合 factur-x PDF/A-3 的 (Zugferd)
- vue.js - 关键依赖:依赖的请求是一个表达式,当使用 v-bind 时
- java - 在中断处理程序线程开始时运行任务
- delphi - 从 URL 中提取 URL 参数?在德尔福