Search code examples
pythonpandascompareisin

How to compare between each columns text value?


I want to compare with each columns in python.

for instance :

no. name name_convert contains
0 applepie apple True
1 applepie strawberry False
2 bananashake banana True
3 bananashake banana True

I want to create contains columns. It defines result of comparison of each column (name with name_convert). applepie (in name) contains apple(in name_convert) string.

How can I create a new column that contains True if the name_convert is substring of name?

Here is my attempt:

data['contains'] = data['name'].isin(data['name_convert'])

Solution

  • You can do it with list comprehension and zip function:

    df['contains']=[i in j for i,j in zip(df['name_convert'],df['name'])]
    
    : df
    Out[10]: 
       no.         name name_convert  contains
    0    0     applepie        apple      True
    1    1     applepie   strawberry     False
    2    2  bananashake       banana      True
    3    3  bananashake       banana      True