[英]Python Dataframe select last n rows based on present value condition
我有一個數據框。 如果當前值為True
我想選擇最后 n (=2) 行。
我的代碼:
df = pd.DataFrame({'A':[10,20,30,40,50,60],'B':[False,False,True,False,True,False]})
A B
0 10 False
1 20 False
2 30 True # Here, I should select 30,20
3 40 False
4 50 True # Here, I should select 50,40
5 60 False
cl_id = df.columns.tolist().index('B') ### cl_id for index number of the column for using in .iloc
op = [df['A'].iloc[x+1-n:x+1,cl_id] if all(df['B'].iloc[x]) for x in np.arange(2,len(df))]
代碼給出錯誤提示invalid syntax
如果 B 列值為 True 我想選擇 A 列中的最后 2 個值我的預期輸出:
opdf =
A B
1 20 False
2 30 True # Here, I should select 30,20
3 40 False
4 50 True # Here, I should select 50,40
讓我們嘗試使用bfill
limit
n = 2
df[df.B.where(df.B).bfill(limit=n-1)==1]
Out[95]:
A B
1 20 False
2 30 True
3 40 False
4 50 True
使用布爾系列或移位的布爾系列進行切片以獲取上一行。
df.loc[df['B'] | df['B'].shift(-1).fillna(False)]
A B
1 20 False
2 30 True
3 40 False
4 50 True
對於任意前一行,BEN_YO 的解決方案更好。 但是我們可以使用np.logical_or.reduce
制作掩碼
import numpy as np
N = 1 # Number of previous rows
m = np.logical_or.reduce([df['B'].shift(-i).fillna(False) for i in range(N+1)])
df.loc[m]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.