我正在嘗試匹配條件,以便如果 A 列和 B 列中都存在文本并且 C 列中為 0,則代碼應在 C 列中回傳“新”(覆寫 0)。下面的示例資料框:
import pandas as pd
df = pd.DataFrame({"A":['something',None,'filled',None], "B":['test','test','test',None], "C":['rt','0','0','0']})
我嘗試了以下操作,但是它似乎只接受最后一個條件,以便 C 列中的任何“0”條目都變為“新”,而不管 A 列或 B 列中的“無”。(在本例中,我只希望出現“新”在第 2 行。
import numpy as np
conditions = [(df['A'] is not None) & (df['B'] is not None) & (df['C'] == '0')]
values = ['new']
df['C'] = np.select(conditions, values, default=df["C"])
感謝任何幫助!
uj5u.com熱心網友回復:
您將需要使用.isna()和過濾它不是 nan/none (使用~)的地方,如下所示:
conditions = [~(df['A'].isna()) & ~(df['B'].isna()) & (df['C'] == '0')]
輸出:
A B C
0 something test rt
1 None test 0
2 filled test new
3 None None 0
uj5u.com熱心網友回復:
使用Series.notna測驗None或NaNS:
conditions = [df['A'].notna() & df['B'].notna() & (df['C'] == '0')]
或者:
conditions = [df[['A','B']].notna().all(axis=1) & (df['C'] == '0')]
values = ['new']
df['C'] = np.select(conditions, values, default=df["C"])
print (df)
A B C
0 something test rt
1 None test 0
2 filled test new
3 None None 0
uj5u.com熱心網友回復:
用
mask = df[['A', 'B']].notna().all(1) & df['C'].eq('0')
df.loc[mask, 'C'] = 'new'
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/376290.html
上一篇:NA在另一列中時粘貼字串
