我有两个 pandas DataFrame,daily_data 包含股票的每日收盘价数据,weekly_data 包含每周收盘价数据。
每日数据:
close
Date
2022-05-02 00:00:00-04:00 30.389999
2022-05-03 00:00:00-04:00 29.469999
2022-05-04 00:00:00-04:00 28.100000
2022-05-05 00:00:00-04:00 26.830000
2022-05-06 00:00:00-04:00 26.070000
2022-05-09 00:00:00-04:00 23.049999
2022-05-10 00:00:00-04:00 23.670000
2022-05-11 00:00:00-04:00 22.570000
2022-05-12 00:00:00-04:00 23.290001
2022-05-13 00:00:00-04:00 24.389999
2022-05-16 00:00:00-04:00 23.590000
...
每周数据:
close
Date
2022-05-02 00:00:00-04:00 26.070000
2022-05-09 00:00:00-04:00 24.389999
2022-05-16 00:00:00-04:00 23.350000
2022-05-23 00:00:00-04:00 23.670000
2022-05-30 00:00:00-04:00 24.150000
2022-06-06 00:00:00-04:00 23.719999
...
我正在每日 DataFrame 上运行 apply(func1)。
在 func1() 中,我需要获取当天所属周的 iloc 索引:
import pandas as pd
def func1(x)
weekly_index = data_weekly.index.get_indexer([pd.to_datetime(x.index)], method='pad')
return weekly_index[0]
daily_data['weekly_index'] = daily_data.apply(func1)
运行此代码时,我收到“不可散列类型:'DatetimeIndex'”错误。
但是,如果我只是在 func1() 之外运行以下代码,它就可以工作:
index = weekly_data.index.get_indexer([pandas.to_datetime('2022-05-23 00:00:00-04:00')], method='pad')
任何关于如何在 apply() 中实现这项工作的见解将不胜感激。
IIUC 你可以做:
def func1(x):
weekly_index = weekly_data.index.get_indexer(x.index, method="pad")
return weekly_index
daily_data["weekly_index"] = daily_data.apply(func1)
print(daily_data)
打印:
close weekly_index
Date
2022-05-02 00:00:00-04:00 30.389999 0
2022-05-03 00:00:00-04:00 29.469999 0
2022-05-04 00:00:00-04:00 28.100000 0
2022-05-05 00:00:00-04:00 26.830000 0
2022-05-06 00:00:00-04:00 26.070000 0
2022-05-09 00:00:00-04:00 23.049999 1
2022-05-10 00:00:00-04:00 23.670000 1
2022-05-11 00:00:00-04:00 22.570000 1
2022-05-12 00:00:00-04:00 23.290001 1
2022-05-13 00:00:00-04:00 24.389999 1
2022-05-16 00:00:00-04:00 23.590000 2