我想通過以下方式向我的資料框中添加一個新列:
df['new']= np.where(df['code']== 0 or 1, 1, 0 )
在這里,當代碼列中的值為 0 或 1 時,我想將值 1 分配給 'new' 列。它給出了一個錯誤。但如果我只使用一個條件,則該陳述句有效。
以下陳述句有效:
df['new']= np.where(df['code']== 0, 1, 0 )
在為新列分配值時如何使用這兩個條件?
uj5u.com熱心網友回復:
嘗試:
df["new"] = np.where(df["code"].isin([0,1]), 1, 0)
uj5u.com熱心網友回復:
您不必使用np.where,使用布爾掩碼并將其轉換為 int:
df['new'] = df['code'].isin([0, 1]).astype(int)
例子:
>>> df
code
0 2
1 3
2 0
3 3
4 1
>>> df['new'] = df['code'].isin([0, 1]).astype(int)
>>> df
code new
0 2 0
1 3 0
2 0 1
3 3 0
4 1 1
uj5u.com熱心網友回復:
df['new'] = df['code'].isin([0,1])*1
uj5u.com熱心網友回復:
df['new']= np.where((df['code']== 0) | (df['code']== 1), 1 , 0)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/337937.html
