1

I have a MWE that can be reproduced with the following code:

import pandas as pd
a = pd.DataFrame([[1,2],[3,4]], columns=['A', 'B'])
b = pd.DataFrame([[True,False],[False,True]], columns=['A', 'B'])

Which creates the following dataframes:

In [8]: a
Out[8]: 
   A  B
0  1  2
1  3  4

In [9]: b
Out[9]: 
       A      B
0   True  False
1  False   True

My question is, how can I change the values for dataframe A based on the boolean values in dataframe B?

Say for example if I wanted to make NAN values in dataframe A where there's an instance of False in dataframe B?

1 Answer 1

1

If need replace False to NaN:

print (a[b])
     A    B
0  1.0  NaN
1  NaN  4.0

or:

print (a.where(b))
     A    B
0  1.0  NaN
1  NaN  4.0

and if need replace True to NaN:

print (a[~b])
     A    B
0  NaN  2.0
1  3.0  NaN

or:

print (a.mask(b))
     A    B
0  NaN  2.0
1  3.0  NaN

Also you can use where or mask with some scalar value:

print (a.where(b, 7))
   A  B
0  1  7
1  7  4

print (a.mask(b, 7))
   A  B
0  7  2
1  3  7

print (a.where(b, 'TEST'))
      A     B
0     1  TEST
1  TEST     4
Sign up to request clarification or add additional context in comments.

6 Comments

That does seem to work, thanks. Just to expand upon my question, is it possible to make all False values in dataframe B into the string 'TEST' in dataframe A? I'm interested to see how flexible I can be with this kind of mapping.
Thanks, interesting this doesn't seem to work with multi-index dataframes.
Hmmm, Dataframes with Multiindex have same indexes and same columns?
Yes, or rather more specifically in my example, I have 2 dataframes, both have the same index (time series) and the same set of multi-level columns (7 levels). The above methods don't work with those.
Then try add values print (a.mask(b.values))
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.