Yusuf Ahmed
Yusuf Ahmed

Reputation: 38

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?

Upvotes: 0

Views: 914

Answers (2)

BENY
BENY

Reputation: 323226

You can just assign

iris[~iris_bool]=np.nan

Upvotes: 0

user17242583
user17242583

Reputation:

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

Upvotes: 1

Related Questions