return True if partial match success between two column

Viewed 520

I am looking for partial matches success. below is the code for the dataframe.

import pandas as pd
data = [['tom', 10,'aaaaa','aaa'], ['nick', 15,'vvvvv','vv'], ['juli', 14,'sssssss','kk']] 
# Create the pandas DataFrame 
df = pd.DataFrame(data, columns = ['Name', 'Age','random','partial'])
df

Output: I am expecting the output shown below

   Name  Age   random partial  Matches
0   tom   10    aaaaa     aaa  True
1  nick   15    vvvvv      vv  True
2  juli   14  sssssss      kk  False
2 Answers

You can use df.apply in combination with a lambda function that checks whether the partial string is part of the other string by using in.

Then we can assign this to a new column in the dataframe:

>>>import pandas as pd
>>>data = [['tom', 10,'aaaaa','aaa'], ['nick', 15,'vvvvv','vv'], ['juli',14,'sssssss','kk']] 
>>>df = pd.DataFrame(data, columns = ['Name', 'Age','random','partial'])

>>>df['matching'] = df.apply(lambda x : x.partial in x.random, axis=1)
>>>print(df)
   Name  Age   random partial  matching
0   tom   10    aaaaa     aaa      True
1  nick   15    vvvvv      vv      True
2  juli   14  sssssss      kk     False

One important thing to be aware of when using df.apply is the axis argument, as it here allows us to access all columns of a given row at once.

df['Matches'] = df.apply(lambda row: row['partial'] in row['random'], axis = 'columns')
df

gives


Name    Age random  partial Matches
0   tom 10  aaaaa   aaa True
1   nick    15  vvvvv   vv  True
2   juli    14  sssssss kk  False
Related