Numpy 如何根据数据帧中其他列的值为每行获取n-period的最大值?

Numpy 如何根据数据帧中其他列的值为每行获取n-period的最大值?,numpy,dataframe,Numpy,Dataframe,假设我有一个df: idx c1 A 1 B 7 C 8 D 6 E 5 F 6 G 9 H 8 I 0 J 10 根据c1为每行获得n个句点的最大值,然后为其创建新列的最快方法是什么?如果是三周期,那么它将是这样的: idx c1 new_col A 1 0 B 7 0 C 8 0 D 6 8

假设我有一个df:

idx   c1   
A     1  
B     7  
C     8  
D     6  
E     5  
F     6 
G     9 
H     8 
I     0 
J    10 
根据c1为每行获得n个句点的最大值,然后为其创建新列的最快方法是什么?如果是三周期,那么它将是这样的:

idx   c1   new_col
A     1     0
B     7     0
C     8     0
D     6     8      (prev. 3-period, 1,7,8, 8 is the highest)
E     5     8      (prev. 3-period, 7,8,6  8 is the highest)
F     6     8      (prev. 3-period, 8,6,5  8 is the highest)
G     9     6      (prev. 3-period, 6,5,6  6 is the highest)
H     8     9      (prev. 3-period, 5,6,9  9 is the highest)
I     0     9      (prev. 3-period, 6,9,8  9 is the highest)
J    10     9      (prev. 3-period, 9,8,0  9 is the highest)
我现在的代码是:

list=[]
for row in range(len(df)):
    if row < 3:
       list.append(0)
    else:
       list.append(max(c1[row-3:row]))
df['new_col'] = list
list=[]
对于范围内的行(len(df)):
如果行<3:
列表。追加(0)
其他:
list.append(最大值(c1[第3行:第4行])
df['new_col']=列表

这个方法非常慢,因为我有很多行,必须循环整个过程。有没有更快的方法?谢谢。

这只是
滚动
轮班

df['new_col'] = df['c1'].rolling(3).max().shift().fillna(0)
输出:

  idx  c1  new_col
0   A   1      0.0
1   B   7      0.0
2   C   8      0.0
3   D   6      8.0
4   E   5      8.0
5   F   6      8.0
6   G   9      6.0
7   H   8      9.0
8   I   0      9.0
9   J  10      9.0