2

I have two large dataframes, df1:

Col1    Col2    Val1    Val2    Val3
asd     ASYL    4.2             4.2
ppq     CONE            35      35
DA      HU      100     100

And df2 is

Col1    Col2    Val1    Val2  Val3
asd     ASYL    7       12    17
ppq     CONE    17      19    19
DA      HU      5       14    13

Both dataframes have same index columns Col1 and Col2 and same value columns Val1, Val2, Val3.

I want to set the values in df2 to nan where it is Null in df1 to get the following:

Col1    Col2    Val1    Val2  Val3
asd     ASYL    7             17
ppq     CONE            19    19
DA      HU      5       14      

I tried the following:

idx = df1.isnull()
df2.loc[idx] = np.nan

But it is not working.

0

2 Answers 2

3

You can use df.where with df.notna

df2.where(df1.notna())

Col1    Col2    Val1   Val2  Val3
asd     ASYL    7      NaN    17
ppq     CONE   NaN      19    19
DA      HU      5       14    NaN   
Sign up to request clarification or add additional context in comments.

Comments

2

Another way

df1.mask(df1.notna(),df2)

Alternatively

m=df1.notna()

pd.DataFrame(np.where(m, df2, np.nan))

enter image description here

1 Comment

See two alternatives to @Ch3steR solution

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.