如何在数据框中添加新列时应用 'And' 和 'Or' 等条件语句?
How to apply conditional statements like 'And' and 'Or' while adding a new column in a dataframe?
我想按以下方式将新列添加到我的数据框中:
df['new']= np.where(df['code']== 0 or 1, 1, 0 )
在这里,当代码列中的值为0或1时,我想将值1分配给'new'列。它给出了一个错误。但如果我只使用一个条件,则该语句有效。
以下语句有效:
df['new']= np.where(df['code']== 0, 1, 0 )
如何在为新列赋值时同时使用这两个条件?
尝试:
df["new"] = np.where(df["code"].isin([0,1]), 1, 0)
df['new']= np.where((df['code']== 0) | (df['code']== 1), 1 , 0)
您不必使用 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
df['new'] = df['code'].isin([0,1])*1
我想按以下方式将新列添加到我的数据框中:
df['new']= np.where(df['code']== 0 or 1, 1, 0 )
在这里,当代码列中的值为0或1时,我想将值1分配给'new'列。它给出了一个错误。但如果我只使用一个条件,则该语句有效。
以下语句有效:
df['new']= np.where(df['code']== 0, 1, 0 )
如何在为新列赋值时同时使用这两个条件?
尝试:
df["new"] = np.where(df["code"].isin([0,1]), 1, 0)
df['new']= np.where((df['code']== 0) | (df['code']== 1), 1 , 0)
您不必使用 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
df['new'] = df['code'].isin([0,1])*1