python - Python Pandas返回具有多个条件的行-TypeError:&:'str'和'str'不支持的操作数类型
问题描述
一般来说,我是 python 和 pandas 的新手,但是我想更改满足条件列表的所有行中的列时遇到了麻烦。我目前使用的代码如下:
raw_table.loc[raw_table[raw_table['id'] > id_] & raw_table[raw_table['type name'].str.replace(' ', '') == tableName] & raw_table[raw_table['ordinal'] > ordinal_], 'type name'] = newTableName
这些变量是我需要的,当我在控制台中打印()条件时,它们是单独工作的,但是当我尝试将它们组合在一起时,我得到了错误:
ipdb> print ((raw_table[raw_table['id'] > id_]) & (raw_table[raw_table['type name'].str.replace(' ', '') == tableName]))
*** TypeError: unsupported operand type(s) for &: 'str' and 'str'
有没有更好的方法来做到这一点,我还没有找到或者我的语法刚刚结束?预先感谢您的任何帮助!
解决方案
IIUC,在将多个条件过滤器应用于数据框时,您需要将条件括在括号中:
raw_table[(raw_table['id'] > id_) & (raw_table['type name'].str.replace(' ', '') == tableName) & (raw_table['ordinal'] > ordinal_)]['type name'] = newTableName
或者更清楚地说:
cond1 = raw_table['id'] > id_
cond2 = raw_table['type name'].str.replace(' ', '') == tableName
cond3 = raw_table['ordinal'] > ordinal_
raw_table[(cond1) & (cond2) & (cond3)]['type name'] = newTableName
推荐阅读
- java - Spring 不会为方法参数验证调用 Hibernate 验证器
- javascript - How to call functions and variables in Component in Vue.js
- java - 如何在 Java 中读取特定字符之前的字符?
- javascript - 有没有按索引合并数组的好方法?
- html - 选择器 CSS 父级高级
- php - 可以合并数组吗?
- c# - 是否可以在具有运算符重载的结构上抑制从 null 的隐式转换?
- php - SimpleXmlElement PCDATA 无效字符值 11
- ios - Swift 类属性引用点在 init 方法后消失
- javascript - When does for loop, .map() or .filter() have better performance?