python - 如何根据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?
解决方案
定义条件时缺少括号。这背后的原因是按位运算符的优先级高于比较运算符。而是使用:
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
推荐阅读
- javascript - 如何删除在控制台中显示未定义的代码行?
- android - 查看 SQLite 数据库时,片段列表视图崩溃
- javascript - 分配失败 - loopback.js 中的 javascript 堆内存不足
- ajax - 如何使用 Ajax 并在另一个 URL 上发布数据请求?
- xml - 如何从 Scala 中的“#PCDATA”获取数据?
- trace32 - 如何从 t32 cmm 脚本中的给定地址查看变量名?
- javascript - ESRI TypeError:this.spatialReference 未定义
- python - 从文件中读取字典并将其转换为 python 数据类型 dict
- asp.net-mvc - 如何保护 asp.net mvc5 应用程序?
- prestashop - Prestashop 1.7 如何添加换行符