简体   繁体   中英

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

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM