我正在测试“ daychange”列中的数据。如果值在范围内,则我希望在单独的列中显示100(是)和0(否)。我尝试了这段代码:
cond16 = df[(df['daychange']<8) & (df['daychange']>2)]
df['day3'] = np.where(cond16, 100, 0)
但是出现以下错误:
ValueError: Length of values (932) does not match length of index (13063)
非常感谢您的帮助!
答案 0 :(得分:0)
正如Erfan在评论中提到的,您已经创建了过滤器。只需使用它来设置DataFrame中的值即可。
# Create filter condition
cond16 = (df['daychange']<8) & (df['daychange']>2)
# Set rows where condition is true to 100
df.loc[cond16, 'day3'] = 100
# Set rows where condition is not true to 0
df.loc[~cond16, 'day3'] = 0
答案 1 :(得分:0)
您几乎明白了。 @Erfan的评论中提到了小错误。您只需要条件,而不需要np.where
中的选择。
cond16 = (df['daychange']<8) & (df['daychange']>2)
df['day3'] = np.where(cond16, 100, 0)