尝试根据条件语句对二进制变量进行编码
Trying to code a binary variable based on a conditional statement
根据以下代码编写二进制变量时出现问题。如果 feature
小于或等于 30,我希望变量 metric
为 1,否则为 0。当我 运行 此代码时,出现以下错误: ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().
if df1.Feature <= 30:
df1.metric=1
else:
df1.metric=0
您正在测试整个系列作为一个对象的真值。您可以使用 np.where
来测试每个元素。你的情况:
df1.loc[:, 'REC30PY'] = np.where(df1.velocity<=30, 1, 0)
或者,获取布尔值:
df1.loc[:, 'REC30PY'] = np.where(df1.velocity<=30, True, False)
您可以通过 astype
:
将布尔掩码 True
转换为 1
并将 False
转换为 0
df1['REC30PY'] = (df1.velocity<=30).astype(int)
对于 True
和 False
s:
df1['REC30PY'] = df1.velocity<=30
根据以下代码编写二进制变量时出现问题。如果 feature
小于或等于 30,我希望变量 metric
为 1,否则为 0。当我 运行 此代码时,出现以下错误: ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().
if df1.Feature <= 30:
df1.metric=1
else:
df1.metric=0
您正在测试整个系列作为一个对象的真值。您可以使用 np.where
来测试每个元素。你的情况:
df1.loc[:, 'REC30PY'] = np.where(df1.velocity<=30, 1, 0)
或者,获取布尔值:
df1.loc[:, 'REC30PY'] = np.where(df1.velocity<=30, True, False)
您可以通过 astype
:
True
转换为 1
并将 False
转换为 0
df1['REC30PY'] = (df1.velocity<=30).astype(int)
对于 True
和 False
s:
df1['REC30PY'] = df1.velocity<=30