如何按日期时间索引熊猫数据框?

时间:2021-01-29 21:01:22

标签: python django pandas django-pandas

我正在使用 django_pandas 包从存储的 Django 模型中获取 Pandas 数据帧。

df = qs.to_dataframe(['time', 'price_open', 'price_high', 'price_low', 'price_close'], index='time')

现在我想按日期时间访问数据框,但是,这不起作用。打印 df 看起来像这样,其中时间列有一个奇怪的位置:printing the df

如果我执行 print(df.keys()),我会得到以下结果: Index(['price_open', 'price_high', 'price_low', 'price_close', ], dtype='object') 但我有更多的预期时间。此外,df.columns 不包含时间,而只包含其他列。

如何在给定的日期时间访问 df?为什么时间不是 df 的关键?谢谢!

1 个答案:

答案 0 :(得分:0)

正如@ThePorcius 所指出的,reset_index 应该将时间列返回给您。

df = df.reset_index() 

根据docs,您可以在on 中使用resample 参数来使用列而不是索引。 您需要确保 time 列是 datetime

dailyFrame=(
    df.resample('D', on='time')
    .agg({'price_open': 'first', 'price_high': 'max', 'price_low': 'min', 'price_close': 'last'})
)