【问题标题】:How to resample intra-day intervals and use .idxmax()?如何重新采样日内间隔并使用 .idxmax()?
【发布时间】:2022-01-12 08:35:46
【问题描述】:

我正在使用来自 yfinance 的数据,它返回一个 pandas 数据帧。

                            Volume
Datetime                          
2021-09-13 09:30:00-04:00   951104
2021-09-13 09:35:00-04:00   408357
2021-09-13 09:40:00-04:00   498055
2021-09-13 09:45:00-04:00   466363
2021-09-13 09:50:00-04:00   315385
2021-12-06 15:35:00-05:00   200748
2021-12-06 15:40:00-05:00   336136
2021-12-06 15:45:00-05:00   473106
2021-12-06 15:50:00-05:00   705082
2021-12-06 15:55:00-05:00  1249763

数据框中有 5 分钟的日内间隔。我想重新采样到每日数据并获取当天最大音量的 idxmax。

df.resample("B")["Volume"].idxmax()

返回错误:

ValueError: attempt to get argmax of an empty sequence

我使用 B(工作日)作为重采样周期,所以不应该有任何空序列。

我应该说 .max() 工作正常。

按照另一个问题的建议使用 .agg 也会返回错误:

df["Volume"].resample("B").agg(lambda x : np.nan if x.count() == 0 else x.idxmax()) 

错误:

IndexError: index 77 is out of bounds for axis 0 with size 0

【问题讨论】:

    标签: pandas time-series yfinance pandas-timeindex


    【解决方案1】:

    您可以使用groupby 代替resample

    >>> df.groupby(df.index.normalize())['Volume'].agg(Datetime='idxmax', Volume='max')
    
                          Datetime   Volume
    Datetime                               
    2021-09-13 2021-09-13 09:30:00   951104
    2021-12-06 2021-12-06 15:55:00  1249763
    

    【讨论】:

    • 谢谢。我从未在 agg 函数中看到过这种类型的参数。我想这是因为您在 groupby 之后选择一列。
    • 是的,你是对的。您可能知道 DataFrame 的这种形式:df.groupby(df.index.normalize()).agg(Datetime=('Volume', 'idxmax'), Volume=('Volume', 'max'))?
    • 如果你没有像 (Datetime Peak) 这样的有效 python 标识符,你可以使用这种形式:df.groupby(df.index.normalize())['Volume'].agg(**{'Datetime Peak': 'idxmax', 'Volume Max': 'max'})
    【解决方案2】:

    对我来说,如果 if-else 中每个组的所有 NaNs 都在工作测试:

    df = df.resample("B")["Volume"].agg(lambda x: np.nan if x.isna().all() else x.idxmax())
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-10-20
      • 2014-01-20
      • 2018-03-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-11-12
      相关资源
      最近更新 更多