[英]Python Pandas - If statement checking a True False Boolean Column
我有一個 Pandas df,其中有一列 True False 值。 我正在嘗試構建一個 if 語句來測試該列,但沒有得到想要的結果。 我想我錯誤地使用了 .bool 方法。 基本思路是檢查當前行 Col1 的值是否為 True,如果前面的三個行 Col1 中的任何一個為 False,則在 Col2 中返回 True
from pandas import DataFrame
names = {'col1': [False, False, False, False, False, True, True,
True, False, False]}
df = DataFrame(names, columns =['col1'])
if df.col1.bool == True:
if df.col1.shift(1).bool == False:
df['col2'] = True
elif df.col1.shift(2).bool == False:
df['col2'] = True
elif df.col1.shift(3).bool == False:
df['col2'] = True
else:
df['col2'] = False
df
from pandas import DataFrame
names = {'col1': [False, False, False, False, False, True, True,
True, False, False]}
df = DataFrame(names, columns =['col1'])
df['col2'] = False
df['col2'][df['col1']==False] = True
df['col2'][df['col1'].shift(1)==False] = True
df['col2'][df['col1'].shift(2)==False] = True
df['col2'][df['col1'].shift(3)==False] = True
df
或者如果你想壓縮一點
from pandas import DataFrame
names = {'col1': [False, False, False, False, True, True, True,
True, False, False]}
df = DataFrame(names, columns =['col1'])
df['col2'] = False
df['col2'][(df['col1']==False) | (df['col1'].shift(1)==False) | (df['col1'].shift(2)==False) | (df['col1'].shift(3)==False)] = True
這是一種方法,使用 np.where 和 pd.rolling 並取 boolean 值的總和,除非所有前三個值都是真的 IIUC,前三個值不包括當前行,否則它將小於 3
df['col2']=np.where((df['col1'].shift(1).rolling(3).sum()<3) &(df['col1']==True),
True,
False)
df
col1 col2
0 False False
1 False False
2 False False
3 False False
4 False False
5 True True
6 True True
7 True True
8 False False
9 False False
df['col2'] = True
和df['col2'] = False
行分別將整列設置為 True 和 False。 由於您需要逐元素操作,因此您需要使用重載的按位運算&
(用於 AND)和|
(對於 OR)。
當col1
的當前值為 True 並且前 3 個值中的至少一個為 False 時,您的新列應該為真,因此將被編碼為:
df['col2'] = df.col1 & (
(df.col1.shift(1) == False) |
(df.col1.shift(2) == False) |
(df.col1.shift(3) == False)
)
使用按位運算時要注意運算符的優先級,因為它們的優先級低於比較運算符,因此建議使用圓括號。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.