2

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
johannesack
  • 660
  • 3
  • 19
Ayush
  • 95
  • 2
  • 8
  • name age random partial matches tom 10 aaaaa aa TRUE nick 15 vvvvv vvv TRUE juli 14 sssssss kk Flase – Ayush Aug 04 '20 at 12:07
  • Does this answer your question? [Creating a new column based on if-elif-else condition](https://stackoverflow.com/questions/21702342/creating-a-new-column-based-on-if-elif-else-condition) – Tomerikoo Aug 04 '20 at 12:21

2 Answers2

2

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.

johannesack
  • 660
  • 3
  • 19
2
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
pfuhlert
  • 533
  • 4
  • 16
  • Name Age random partial Matches 0 tom 10 JP b c Morgan JP Morgan True 1 nick 15 morgan ba stanley Morgan stanley True How we can solve this problem? – Ayush Aug 05 '20 at 05:56