# Replace values in dataframe with another dataframes values based on condition [closed]

I have 2 dataframes with the same columns names and rows number but the elements' values are different. I need to change the value of each element in the first dataframe to 1 if its value in the the other dataframe is 1. I am stuck on this task. Any help pls?

The easiest way to do it for your case is something like this:


In [1]: import pandas as pd

In [2]: df1 = pd.DataFrame([0, 1, 2, 3, 1, 2, 3, 1, 2], columns=["A"])

In [3]: df2 = pd.DataFrame([9] * len(df1), columns=["A"])

In [4]: df1
Out[4]:
A
0  0
1  1
2  2
3  3
4  1
5  2
6  3
7  1
8  2

In [5]: df2
Out[5]:
A
0  9
1  9
2  9
3  9
4  9
5  9
6  9
7  9
8  9


Wherever the row of column A in df1 is equal to 1, insert 1 into the same row of column A in df2

In [6]: df2.A[df1.A == 1] = 1

In [7]: df2
Out[7]:
A
0  9
1  1
2  9
3  9
4  1
5  9
6  9
7  1
8  9



You could also use the pd.DataFrame.where method, to replace the part df1.A == 1.

There are also many other ways to get the same thing done, but my example is the most straighforward :)