0

我正在使用来自 yfinance 的数据,它返回一个熊猫数据框。

                            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(business-days) 作为重采样周期,所以不应该有任何空序列。

我应该说 .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
4

2 回答 2

1

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

df = df.resample("B")["Volume"].agg(lambda x: np.nan if x.isna().all() else x.idxmax())
于 2021-12-07T09:00:54.603 回答
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
于 2021-12-07T10:06:03.653 回答