Skip to main content
 首页 » 编程设计

python Pandas :get rolling value of one Dataframe by rolling index of another Dataframe

2025年04月02日14cmt

我有两个数据框:一个有多级列,另一个只有单级列(这是第一个数据框的第一级,或者说第二个数据框是通过对第一个数据框进行分组计算的)。

这两个数据框如下所示:

first dataframe-df1 second dataframe-df2 df1和df2的关系是:

df2 = df1.groupby(axis=1, level='sector').mean() 

然后,我通过以下方式获取 df1 的 rolling_max 索引:

result1=pd.rolling_apply(df1,window=5,func=lambda x: pd.Series(x).idxmax(),min_periods=4) 

让我稍微解释一下 result1。例如,在2016/2/23-2016/2/29这5天(窗口长度)内,股票sh600870的最高价出现在2016/2/24,2016/2/24的指数在5- day range是1。所以在result1中,股票sh600870在2016/2/29的值(value)是1。

现在,我想通过 result1 中的索引获取每只股票的行业价格。

以同一只股票为例,股票sh600870在‘家用电器视觉听器 Material 白色家电’板 block 。所以在2016/2/29,我想得到2016/2/24的板 block 价格,也就是8.770。

我该怎么做?

请您参考如下方法:

idxmax(或np.argmax)返回一个相对于滚动的索引 window 。要使索引相对于 df1,请添加左边缘的索引 滚动窗口:

index = pd.rolling_apply(df1, window=5, min_periods=4, func=np.argmax) 
shift = pd.rolling_min(np.arange(len(df1)), window=5, min_periods=4) 
index = index.add(shift, axis=0) 

一旦你有了相对于 df1 的序号索引,你就可以使用它们来索引 使用 .iloc 进入 df1 或 df2。


例如,

import numpy as np 
import pandas as pd 
np.random.seed(2016) 
N = 15 
columns = pd.MultiIndex.from_product([['foo','bar'], ['A','B']]) 
columns.names = ['sector', 'stock'] 
dates = pd.date_range('2016-02-01', periods=N, freq='D') 
df1 = pd.DataFrame(np.random.randint(10, size=(N, 4)), columns=columns, index=dates) 
df2 = df1.groupby(axis=1, level='sector').mean() 
 
window_size, min_periods = 5, 4 
index = pd.rolling_apply(df1, window=window_size, min_periods=min_periods, func=np.argmax) 
shift = pd.rolling_min(np.arange(len(df1)), window=window_size, min_periods=min_periods) 
# alternative, you could use 
# shift = np.pad(np.arange(len(df1)-window_size+1), (window_size-1, 0), mode='constant') 
# but this is harder to read/understand, and therefore it maybe more prone to bugs. 
index = index.add(shift, axis=0) 
 
result = pd.DataFrame(index=df1.index, columns=df1.columns) 
for col in index: 
    sector, stock = col 
    mask = pd.notnull(index[col]) 
    idx = index.loc[mask, col].astype(int) 
    result.loc[mask, col] = df2[sector].iloc[idx].values 
 
print(result) 

产量

sector      foo       bar      
stock         A    B    A    B 
2016-02-01  NaN  NaN  NaN  NaN 
2016-02-02  NaN  NaN  NaN  NaN 
2016-02-03  NaN  NaN  NaN  NaN 
2016-02-04  5.5    5    5  7.5 
2016-02-05  5.5    5    5  8.5 
2016-02-06  5.5  6.5    5  8.5 
2016-02-07  5.5  6.5    5  8.5 
2016-02-08  6.5  6.5    5  8.5 
2016-02-09  6.5  6.5  6.5  8.5 
2016-02-10  6.5  6.5  6.5    6 
2016-02-11    6  6.5  4.5    6 
2016-02-12    6  6.5  4.5    4 
2016-02-13    2  6.5  4.5    5 
2016-02-14    4  6.5  4.5    5 
2016-02-15    4  6.5    4  3.5 

请注意,在 pandas 0.18 中,rolling_apply 语法已更改。 DataFrames 和 Series 现在有一个 rolling 方法,所以现在你可以使用:

index = df1.rolling(window=window_size, min_periods=min_periods).apply(np.argmax) 
shift = (pd.Series(np.arange(len(df1))) 
         .rolling(window=window_size, min_periods=min_periods).min()) 
index = index.add(shift.values, axis=0)