1

Let's say I have two dataframes of the same size, one with values:

d1 = {'values1': [1, 1,2,2], 'values2': [10, 50,200,100]}
df1 = pd.DataFrame(data=d1)

And a dataframe of booleans:

d2 = {'boolean1': [True, False,True,True], 'boolean2': [False, False,False,True]}
df2 = pd.DataFrame(data=d2)

How can I repplace values in df1 to zeros where booleans are True?

The result I am looking for is:

r = {'values1': [0, 1,0,0], 'values2': [10, 50,200,0]}
result = pd.DataFrame(data=r)
1
  • Do you want to replace in place? df1[df2.to_numpy()] = 0 Commented Nov 15, 2022 at 10:42

1 Answer 1

4

Because differnt columns names between both DataFrames use DataFrame.mask with converting df2 to numpy array:

result = df1.mask(df2.to_numpy(), 0)
print (result)
   values1  values2
0        0       10
1        1       50
2        0      200
3        0        0

If set columns names in boolean DataFrame - same columns in both DataFrames is not necessary convert to numpy array:

result = df1.mask(df2.set_axis(df1.columns, inplace=False, axis=1), 0)
print (result)

   values1  values2
0        0       10
1        1       50
2        0      200
3        0        0
Sign up to request clarification or add additional context in comments.

Comments

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.