-2

我想通过以下方式向我的数据框中添加一个新列:

df['new']= np.where(df['code']== 0 or 1, 1, 0 )

在这里,当代码列中的值为 0 或 1 时,我想将值 1 分配给“新”列。它给出了一个错误。但如果我只使用一个条件,则该语句有效。

以下语句有效:

df['new']= np.where(df['code']== 0, 1, 0 )

在为新列分配值时如何使用这两个条件?

4

4 回答 4

2

尝试:

df["new"] = np.where(df["code"].isin([0,1]), 1, 0)
于 2021-10-26T14:01:27.347 回答
0
df['new']= np.where((df['code']== 0) | (df['code']== 1), 1 , 0)
于 2021-10-26T14:04:49.540 回答
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
于 2021-10-26T14:08:06.967 回答
0
df['new'] = df['code'].isin([0,1])*1
于 2021-10-26T14:08:34.817 回答