首页 > 解决方案 > 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'

有没有更好的方法来做到这一点,我还没有找到或者我的语法刚刚结束?预先感谢您的任何帮助!

标签: pythonpandas

解决方案


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

推荐阅读