Skip to content Skip to sidebar Skip to footer

More Complex Logic With Pandas Loc?

If I want to match a column for multiple characteristics, i.e. df.loc[df['col1'] == (5 or 6), 'col2'] = 5 How can I do this? I tried this method but it did not work.

Solution 1:

df.loc[(df['col1']==5) | (df['col1']==6),'col2'] = 5

You can also use in for this example, but in some cases of complex logic, using the bitwise operations of | (or) and & (and) are necessary.


Solution 2:

You can use pandas.query

idx  = df.query('col1 == 1.178238 or col1 == 0.144455').index
df.loc[idx, 'col2'] = 5

Post a Comment for "More Complex Logic With Pandas Loc?"