Tom Cusack Tom Cusack - 9 months ago 40
Python Question

String matching plus Boolean value reassignment in Pandas

I'm trying to find all the value, which is a more complex query than I'm used to. I'll be changing the values of millions of values potentially, so the most efficient way to find rows, which meet these conditions, and how to change their values would be really helpful.

What I'm trying to do is the following:

import pandas as pd

example = pd.DataFrame({'a': ['9+'],
'b': [False]})

# If example['a'] contains a '9' or a '10' AND example['b'] is 'False' then change example['a'] to '8'

Answer Source

we can use Pandas boolean indexing:

In [126]: example
     a      b
0   9+  False
1  10-  False
2    9   True
3    1   True
4    2  False

In [127]: example.loc[example['a'].str.contains('9|10') & ~example['b'], 'a'] = '8'

In [128]: example
   a      b
0  8  False
1  8  False
2  9   True
3  1   True
4  2  False
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download