python pandas:通过滚动另一个Dataframe的索引来获取一个Dataframe的滚动值

问题描述 投票:2回答:1

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

这两个数据框如下所示:

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的五天(窗口长度)期间,股票sh600870的最高价格发生在2016/2/24,即2016/2/24的指数日期范围是1.因此,在result1中,2016/2/29的股票sh600870的值为1。

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

Let's take the same stock as example, the stock sh600870 is in sector ’家用电器视听器材白色家电‘. So in 2016/2/29, I wanna get the sector price in 2016/2/24, which is 8.770.

我怎样才能做到这一点?

python pandas dataframe multi-index
1个回答
1
投票

idxmax(或np.argmax)返回一个相对于滚动窗口的索引。要使索引相对于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的序数指数,你可以使用它们使用df1索引到df2.iloc


例如,

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)
© www.soinside.com 2019 - 2024. All rights reserved.