熊猫:如果在循环中滚动计数

时间:2017-03-18 17:36:42

标签: python loops pandas windowing

在我的数据框中,我想创建一个列'5D_Peak'作为滚动最大值,然后创建另一列,其中滚动计数的历史数据接近峰值。我想知道是否有一种更简单或理想的矢量化计算方法。

这是我的代码,简单但复杂:

import numpy as np
import pandas as pd

df = pd.DataFrame([[1,2,4],[4,5,2],[3,5,8],[1,8,6],[5,2,8],[1,4,10],[3,5,9],[1,4,7],[1,4,6]], columns=list('ABC'))

df['5D_Peak']=df['C'].rolling(window=5,center=False).max()

for i in range(5,len(df.A)):
    val=0
    for j in range(i-5,i):
        if df.loc[j,'C']>df.loc[i,'5D_Peak']-2 and df.loc[j,'C']<df.loc[i,'5D_Peak']+2:
            val+=1
    df.loc[i,'5D_Close_to_Peak_Count']=val

这是我想要的输出:

   A  B   C  5D_Peak  5D_Close_to_Peak_Count
0  1  2   4      NaN                     NaN
1  4  5   2      NaN                     NaN
2  3  5   8      NaN                     NaN
3  1  8   6      NaN                     NaN
4  5  2   8      8.0                     NaN
5  1  4  10     10.0                     0.0
6  3  5   9     10.0                     1.0
7  1  4   7     10.0                     2.0
8  1  4   6     10.0                     2.0

1 个答案:

答案 0 :(得分:1)

我相信这就是你想要的。您可以设置以下两个值:

'''the window within which to search "close-to_peak" values'''
lkp_rng = 5 

'''how close is close?'''
closeness_measure = 2

'''function to count the number of "close-to_peak" values in the lkp_rng'''
fc = lambda x: np.count_nonzero(np.where(x >= x.max()- closeness_measure))

'''apply fc to the coulmn you choose'''
df['5D_Close_to_Peak_Count'] = df['C'].rolling(window=lkp_range,center=False).apply(fc)
df.head(10)
        A   B   C   5D_Peak     5D_Close_to_Peak_Count
    0   1   2   4   NaN            NaN
    1   4   5   2   NaN            NaN
    2   3   5   8   NaN            NaN
    3   1   8   6   NaN            NaN
    4   5   2   8   8.0            3.0
    5   1   4   10  10.0           3.0
    6   3   5   9   10.0           3.0
    7   1   4   7   10.0           3.0
    8   1   4   6   10.0           2.0

我猜你的意思是“历史数据”。