我有一个包含三列的数据框:target_degrees,low_degrees和high_degrees。我想创建一个标记为成功的新列,以检查target_degrees是否位于low_degrees和high_degrees之间。 示例数据框:
target_degrees low_degrees high_degrees success
10 0 50 1
50 45 100 1
20 100 200 0
1 300 350 0
我尝试在以下代码中使用np.where,但是出现语法错误。
df['success'] = np.where(df['target_degrees'] is in np.arange(df['low_degrees'], df['high_degrees']), 1, 0)
答案 0 :(得分:1)
使用多个条件:
df['success'] = np.where(((df['target_degrees'] >= df['low_degrees']) & (df['target_degrees']<= df['high_degrees'])), 1, 0)
输出:
target_degrees low_degrees high_degrees success
0 10 0 50 1
1 50 45 100 1
2 20 100 200 0
3 1 300 350 0
答案 1 :(得分:0)
使用between
方法更为简洁:
df['success'] = df['target_degrees'].between(df['low_degrees'], df['high_degrees'])