我有一個看起來像這樣的函式:
if (Var_A Var_B <7):
Do something ...
問題是,資料框中的 Var_B 列具有整數或 NaN 值。
如果我按現在的方式撰寫函式,它會回傳錯誤為"TypeError: boolean value of NA is ambiguous"
.
我應該如何重新撰寫函式,以便如果 Var_B 為 NaN,則跳過比較并回傳 Var_A?
是不是像:
if Var_B is not null:
if (Var_A Var_B <7):
Do something ...
else:
Var_A
或者,我可以在不添加 if 陳述句的情況下做一些更優雅的事情:
if (Var_A Var_B < 7) and (Var_B is not null):
Do something ...
此外,我究竟如何撰寫檢查 Var_B 不為空的語法?我試圖寫!= isnull()
,!is.na()
但都沒有作業..
對 Python 非常陌生,非常感謝您的幫助!
uj5u.com熱心網友回復:
簡單地做
df = df.fillna(0)
# if you want to get rid of all NaN values and replace with 0
(or)
df['DataFrame Column'] = df['DataFrame Column'].fillna(0)
# if you only want to replace NaN in a particular column to 0
現在你可以繼續加/減/你想做的任何事情。
uj5u.com熱心網友回復:
如果使用標量,IIUC 使用:
Var_A = 1
Var_B = 2
if (Var_A Var_B < 7) and pd.notna(Var_B):
print ('pass')
pass
Var_A = 1
Var_B = np.nan
if (Var_A Var_B < 7) and pd.notna(Var_B):
print ('pass')
如果使用列輸出是布爾掩碼,則更改代碼:
df = pd.DataFrame({'Var_A':[1,2,3], 'Var_B':[np.nan, 2, 7]})
print (df)
0 False
1 True
2 False
dtype: bool
mask = ((df.Var_A df.Var_B) < 7) & df.Var_B.notna()
print (mask)
0 False
1 True
2 False
dtype: bool
但是隨后if mask:
不能使用,因為使用陣列。
鏈接中的更多資訊
uj5u.com熱心網友回復:
Pandas 有 isnull 函式,如果列的專案是 Nan 或 no Nan,則回傳 True 或 False。所以嘗試這樣做
if not Var_B.isnull().values.any():
if (Var_A Var_B <7):
Do something ...
else:
Var_A
uj5u.com熱心網友回復:
你也可以嘗試這樣的事情,它通常對我有用:
def func(a,b):
try:
check = np.isnan(b)
if check == True:
print("B is nan")
print(int(a))
else:
np.sum(a b)
if a b<7:
print("Something")
except TypeError:
print("Error")
for x in .....:
for y in .....:
func(x,y)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/470313.html