首页 > 解决方案 > 如何根据python中其他列中的多个条件设置列的值?

问题描述

我已经尝试使用许多答案中的代码来解决与此类似的问题,但是当我尝试设置决定列值的多个条件时,我没有发现任何对我有用的东西 - 我也想在 3 中执行此操作不同的方法。

我拥有的数据如下所示:

col1 col2 col3 col4 col5
 1     1    1    4    1
 0     1    1    1    1
 0     0    1    1    1

我想添加另一列,具体取决于第 1-5 列是否具有 >=1 的值,如下所示:

col1 col2 col3 col4 col5 category
 1     1    1    4    1   certain
 0     1    1    1    1   probable
 0     0    1    1    1   possible

我试过这样的代码:

df = pd.read_csv('file.csv',header=0)
m1 = df.col1 >= 1 & df.col2 >= 1 & df.col3 >= 1 & df.col4 >= 1 & df.col5 >= 1
m2 = df.col2 >= 1 & df.col3 >= 1 & df.col4 >= 1 & df.col5 >= 1
m3 = df.col3 >= 1 & df.col4 >= 1 & df.col5 >= 1

df['category'] = np.select([m1, m2, m3], ['certain', 'possible', 'probable'], default='Other')

但这在第一行给出了一个错误:

ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().

从试图理解这个错误开始,我是否需要在运行此代码之前将值 >=1 设置为 True,而其他任何值都为 False?

标签: pythonpandas

解决方案


定义条件时缺少括号。这背后的原因是按位运算符的优先级高于比较运算符。而是使用:

m1 = (df.col1 >= 1) & (df.col2 >= 1) & (df.col3 >= 1) & 
     (df.col4 >= 1) & (df.col5 >= 1)
m2 = (df.col2 >= 1) & (df.col3 >= 1) & (df.col4 >= 1) & (df.col5 >= 1)
m3 = (df.col3 >= 1) & (df.col4 >= 1) & (df.col5 >= 1)

df['category'] = np.select([m1, m2, m3], ['certain', 'possible', 'probable'], 
                           default='Other')

这导致预期的输出:

    col1  col2  col3  col4  col5  category
0     1     1     1     4     1   certain
1     0     1     1     1     1  possible
2     0     0     1     1     1  probable

推荐阅读