Yadhu
Yadhu

Reputation: 125

Comparing two dataframe and replacing the column values

I have two dataframe df

df1

I need to compare both dataframe and my output should in such a way that if the values a df1 is present in df leave it as it is else it should be replaced by Out. For example values of column in Level_count should be like L1,L1,L1,L2,L2,L2,L2,Out,Out,Out (as L3 and l4 are not in df1) like this same way i need to compare Edu and Occ as well.

This is my desired output Output Could anyone help me in solving out this solution.

Thanks in Advance.

Upvotes: 0

Views: 36

Answers (1)

Sociopath
Sociopath

Reputation: 13401

You need:

df2_dict=df2.to_dict(orient='list')
# {'Level_Count': ['L1', 'L2'], 'Edu': ['MBBS', None], 'Occ': ['MBBS1', None]}

for c in df1.columns:
    df1[c]=df1[c].apply(lambda x: x if x in df2_dict[c] else 'out')

Output:

    Level_Count Edu Occ
0   L1  MBBS    MBBS1
1   L1  MBBS    MBBS1
2   L1  out     out
3   L2  MBBS    MBBS1
4   L2  MBBS    MBBS1
5   L2  MBBS    MBBS1
6   L2  MBBS    MBBS1
7   out MBBS    MBBS1
8   out out     out
9   out MBBS    MBBS1

Upvotes: 1

Related Questions