Reputation: 2753
I am new to python and pandas in general, but I am having trouble where I want to change a column in all rows that meet a list of conditions. The code that I am currently using is as follows:
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
The variables are what I need them to be and when I print() the conditions out in the console they are working individually, but when I try to do a grouping of them together I get the error:
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'
Is there a better way to do this that I haven't found yet or is my syntax just off? Thank you in advance for any help!
Upvotes: 1
Views: 339
Reputation: 9019
IIUC, you need to wrap your conditions in parenthesis when applying multiple conditional filters to your dataframe:
raw_table[(raw_table['id'] > id_) & (raw_table['type name'].str.replace(' ', '') == tableName) & (raw_table['ordinal'] > ordinal_)]['type name'] = newTableName
Or more legibly:
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
Upvotes: 4