Christine Tan
Christine Tan

Reputation: 53

Comparing common strings in two pandas dataframe columns

I have a pandas data frame as follows:

coname1        coname2
Apple          [Microsoft, Apple, Google]
Yahoo          [American Express, Jet Blue]
Gap Inc       [American Eagle, Walmart, Gap Inc]

I want to create a new column that flags whether the string in coname1 is contained in conames. So, from the above example, the dataframe would now be:

coname1        coname2                               isin
Apple          [Microsoft, Apple, Google]            True
Yahoo          [American Express, Jet Blue]          False
Gap Inc       [American Eagle, Walmart, Gap Inc]     True

Upvotes: 5

Views: 5174

Answers (1)

JAB
JAB

Reputation: 12781

set up frame:

df =pd.DataFrame({'coname1':['Apple','Yahoo','Gap Inc'],
          'coname2':[['Microsoft', 'Apple', 'Google'],['American Express', 'Jet Blue'],
                     ['American Eagle', 'Walmart', 'Gap Inc']]})

try this:

df['isin'] =df.apply(lambda row: row['coname1'] in row['coname2'],axis=1)

Upvotes: 6

Related Questions