簡體   English   中英

如何在具有其他條件的熊貓中創建滾動窗口

[英]How to create a rolling window in pandas with another condition

我有一個包含 2 列的數據框

df = pd.DataFrame(np.random.randint(0,100,size=(100, 2)), columns=list('AB'))


    A   B
0   11  10
1   61  30
2   24  54
3   47  52
4   72  42
... ... ...
95  61  2
96  67  41
97  95  30
98  29  66
99  49  22
100 rows × 2 columns

現在我想創建第三列,它是 col 'A' 的滾動窗口最大值,但最大值必須低於 col 'B' 中的相應值。 換句話說,我想要 'A' 列中的 4(使用 4 的窗口大小)的值最接近 col 'B' 中的值,但小於 B

因此,例如在第 3 行 47 52 中,我正在尋找的新值不是 61 而是 47,因為它是不高於 52 的 4 的最高值

偽代碼

df['C'] = df['A'].rolling(window=4).max()  where < df['B']

您可以使用concat + shift使用先前的值創建一個寬 DataFrame,這使得復雜的滾動計算變得更容易一些。

樣本數據

np.random.seed(42)
df = pd.DataFrame(np.random.randint(0, 100, size=(100, 2)), columns=list('AB'))

代碼

N = 4
# End slice ensures same default min_periods behavior to `.rolling`
df1 = pd.concat([df['A'].shift(i).rename(i) for i in range(N)], axis=1).iloc[N-1:]

# Remove values larger than B, then find the max of remaining.
df['C'] = df1.where(df1.lt(df.B, axis=0)).max(1)

print(df.head(15))

     A   B     C
0   51  92   NaN  # Missing b/c min_periods
1   14  71   NaN  # Missing b/c min_periods
2   60  20   NaN  # Missing b/c min_periods
3   82  86  82.0
4   74  74  60.0
5   87  99  87.0
6   23   2   NaN  # Missing b/c 82, 74, 87, 23 all > 2
7   21  52  23.0  # Max of 21, 23, 87, 74 which is < 52
8    1  87  23.0
9   29  37  29.0
10   1  63  29.0
11  59  20   1.0
12  32  75  59.0
13  57  21   1.0
14  88  48  32.0

您可以使用自定義函數.apply到滾動窗口。 在這種情況下,您可以使用默認參數傳入B列。

df = pd.DataFrame(np.random.randint(0,100,size=(100, 2)), columns=('AB'))

def rollup(a, B=df.B):
    ix = a.index.max()
    b = B[ix]
    return a[a<b].max()

df['C'] = df.A.rolling(4).apply(rollup)

df
# returns:
     A   B     C
0    8  17   NaN
1   23  84   NaN
2   75  84   NaN
3   86  24  23.0
4   52  83  75.0
..  ..  ..   ...
95  38  22   NaN
96  53  48  38.0
97  45   4   NaN
98   3  92  53.0
99  91  86  53.0

當 A 的窗口中沒有數字小於 B 或在窗口對於前幾行來說太大時在系列的開始時會出現NaN值。

您可以使用wherenp.nan替換不滿足條件的值,然后使用rolling(window=4, min_periods=1)

In [37]: df['C'] = df['A'].where(df['A'] < df['B'], np.nan).rolling(window=4, min_periods=1).max()                                                                                            

In [38]: df                                                                                                                                                                                   
Out[38]: 
    A   B    C
0   0   1  0.0
1   1   2  1.0
2   2   3  2.0
3  10   4  2.0
4   4   5  4.0
5   5   6  5.0
6  10   7  5.0
7  10   8  5.0
8  10   9  5.0
9  10  10  NaN

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM