[英]Pandas rolling window rank order with condition
I supposed I have Pandas DataFrame look like below:我想我有 Pandas DataFrame 如下所示:
account amount
A 10
A 10
A 20
A 10
A 10
A 10
B 10
B 10
B 20
B 18
B 18
B 12
B 14
B 18
B 19
I want a new column look like below:我想要一个如下所示的新列:
account want
A nan
A nan
A 1
A 2
A 3
A 1
B nan
B nan
B 1
B 2
B 3
B 1
B 2
B 1
B 1
The idea is to rank order (starting with 1) after maximum value found in the given window.这个想法是在给定 window 中找到最大值之后对顺序(从 1 开始)进行排序。
For example, the given window is 3
, in the account A
, the maximum amount is 20
.例如,给定的 window 为3
,在账户A
中,最大金额为20
。 Then, index 2
will return 1
since 20
is the maximum value in given window.然后,索引2
将返回1
,因为20
是给定 window 中的最大值。 After that for the next rolling window, at index 3
will return 2
since the amount is 10
which is less than 20
from above.之后,对于下一个滚动 window,在索引3
处将返回2
,因为数量为10
,比上面的20
少。
Applied the logic to account B
, the results as shown.将逻辑应用于帐户B
,结果如图所示。 I could think about create the maximum of amount rolling window with 3 but I cannot do further.我可以考虑用 3 创建最大的滚动 window 数量,但我不能再做进一步了。
I think I could solve this issue by code below:我想我可以通过下面的代码解决这个问题:
def rank(window):
newWindow = np.array(window)
lastMax = np.where(newWindow == np.amax(newWindow))[0][-1]
maxLocation = np.repeat(lastMax, newWindow.shape[0])
location = np.arange(0, newWindow.shape[0])
ranks = location - maxLocation + 1
return ranks[-1]
df['want'] = df.groupby('account')['amount'].rolling(window = 3).apply(rank).droplevel(0)
Thanks, every one!感谢大家!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.