Make NaN in a dataframe based on mask value of another dataframe in pandas

Viewed 558

I have a data frame

df1 = pd.DataFrame([["A",1,98,56,51], ["B",1,99,74,36], ["C",1,97,82,83],["B",1,96,31,90], ["C",1,45,92,12], ["A",1,67,33,55]], columns=["id","date","c1","c2","c3"])

I have another dataframe having the same column names

df2 = pd.DataFrame([["A",1,False,False,True], ["B",1,False,False,True], ["C",1,False,False,False],["B",1,False,True,False], ["C",1,True,False,True], ["A",1,False,True,False]], columns=["id","date","c1","c2","c3"])

I want a dataframe df_out, where the value is True in df2, replace with blank/nan in df1, if False keep as it is in df1.

Expected Output:

df_out = pd.DataFrame([["A",1,98,56, ""], ["B",1,99,74,""], ["C",1,97,82,83],["B",1,96,"",90], ["C",1,"",92,""], ["A",1,67,"",55]], columns=["id","date","c1","c2","c3"])

How to do it?

1 Answers

Try with where

l = ['c1','c2','c3']
df1[l] = df1[l].where(df2[l]==False,'')
df1
Out[199]: 
  id  date  c1  c2  c3
0  A     1  98  56    
1  B     1  99  74    
2  C     1  97  82  83
3  B     1  96      90
4  C     1      92    
5  A     1  67      55
Related