首页 > 解决方案 > 如何按日期时间索引熊猫数据框?

问题描述

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

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

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

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

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

标签: pythondjangopandasdjango-pandas

解决方案


正如@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'})
)

推荐阅读