Home > other >  Updated all values in a pandas dataframe based on all instances of a specific value in another dataf
Updated all values in a pandas dataframe based on all instances of a specific value in another dataf

Time:06-04

My apologies beforehand! I have done this before a few times, but I am having some brain fog. I have two dataframes df1, and df2. I would like to update all values in df2 if it matches a specific value in df1, while not changing the other values in df2. I can do this pretty easily with np.where on columns of a dataframe, I am having brain fog on how I did this previously with 2 dataframes!

Goal: Set values in Df2 to 0 if they are 0 in DF1 - otherwise keep the DF2 value

Example

df1

A B C
4 0 1
0 2 0
1 4 0

df2

A B C
1 8 1
9 2 7
1 4 6

Expected df2 after our element swap

A B C
1 0 1
0 2 0
1 4 0

brain fog is bad! thank you for the assistance!

CodePudding user response:

Using fillna

>>> df2[df1 != 0].fillna(0)

CodePudding user response:

You can try

df2[df1.eq(0)] = 0
print(df2)

   A  B  C
0  1  0  1
1  0  2  0
2  1  4  0

CodePudding user response:

You can use a boolean mask, but only if you are sure that your dataframes have the same shape:

for col in df1.columns:
    mask = df1[df1[col] == 0]
    df2.loc[mask, col] = 0
  • Related