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

标签 python pandas dataframe multi-index

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

这两个数据框如下所示:

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 进入 df1df2


例如,

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)

关于 python Pandas :get rolling value of one Dataframe by rolling index of another Dataframe,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37271209/

相关文章:

python - Tkinter导入问题

python - 在基类 __init__ 的子类 __init__ 之后调用基类方法?

python - 使用 re 在另一个字符串中查找一个字符串

python - 按期限顺序对 pandas 数据框进行排序

python - 根据条件获取 DataFrame 列中的最后一个字符串元素

python - 从 Pandas 索引中查找整数行索引

python - 如何在Python中重新初始化变量?

python - 在 Python 中读取 .grd 文件

python - 数据框按最大值排序并显示行名称

python - 沿时间线的条形码位置组合的总和