【问题标题】:How to index a pandas dataframe by datetime?如何按日期时间索引熊猫数据框?
【发布时间】:2021-05-03 19:07:49
【问题描述】:

我正在使用 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的关键?谢谢!

【问题讨论】:

  • 尝试添加对 reset_index() 的调用。另外,确保正在加载的数据实际上被读取为日期时间,您可以在读取 csv 时手动指定它
  • 谢谢,df=df.reset_index() 帮助了。但是,现在我想重新采样数据框并使用: dailyFrame=df.resample('D').agg({'price_open': 'first', 'price_high': 'max', 'price_low': 'min', 'price_close': 'last'}) 现在我收到错误“TypeError:仅对 DatetimeIndex、TimedeltaIndex 或 PeriodIndex 有效,但有一个 'RangeIndex' 的实例”——这是我之前没有得到的。你知道我该如何解决这个问题吗?

标签: python django pandas django-pandas


【解决方案1】:

正如@ThePorcius 所指出的,reset_index 应该还给你时间列。

df = df.reset_index() 

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

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

【讨论】:

    猜你喜欢
    • 2017-02-08
    • 2021-03-19
    • 2019-02-11
    • 1970-01-01
    • 1970-01-01
    • 2021-03-27
    • 2021-03-12
    • 2019-03-11
    • 1970-01-01
    相关资源
    最近更新 更多