Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Replace values in one pandas dataframe using boolean values from another dataframe?

I have two pandas dataframes, one containing data and another consisting of True/False values

  1. iris
Sepal.Length Sepal.Width Petal.Length Petal.Width Species
5.1 3.5 1.4 0.2 setosa
4.9 3.0 1.4 0.2 setosa
4.7 3.2 1.3 0.2 setosa
  1. iris_bool
Sepal.Length Sepal.Width Petal.Length Petal.Width Species
True False True False False
False True False False False
False False False False True

I would like to replace values in table 1 with NA/NaNs based on the corresponding boolean in table 2. Is there an easy way to do this?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Try mask:

iris = iris.mask(~iris_bool)

Output:

>>> iris
   Sepal.Length  Sepal.Width  Petal.Length  Petal.Width Species
0           5.1          NaN           1.4          NaN     NaN
1           NaN          3.0           NaN          NaN     NaN
2           NaN          NaN           NaN          NaN  setosa
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading