0

I have a df with a column of strings like so:

      col1         
         a            
         b            
         c            
         d            

I also have a string variable x = 'x' and a list of strings list1 = ['ax', cx']

I want to create a new column that checks if the concatenated string of col1 + x is in list1. If yes then col2 = 1 else col2 = 0.

Here is my attempt:

df['col2'] = 1 if str(df['col1'] + x) in list1 else 0

Which doesn't work.

df['col2'] = 1 if df['col1'] + x in list1 else 0

Doesn't work either.

What would be the correct way to format this? Thank you for any help.

      col1         col2  <-- should be this
         a            1
         b            0
         c            1
         d            0

3 Answers 3

1

Use isin:

df['col2'] = df.col1.add('x').isin(list1).astype(int)

#  col1  col2
#0    a     1
#1    b     0
#2    c     1
#3    d     0

Check Results

Sign up to request clarification or add additional context in comments.

1 Comment

Both answers work perfectly. Will accept this because its slightly cleaner. Thanks all!
1

You can use map function as follows.

df['col2'] = df['col1'].map(lambda val: 1 if x + val in list1 else 0)

Comments

0

An other solution using apply :

import pandas as pd

df = pd.DataFrame({'col1': ['a','b','c', 'd']})

def func(row):
    list1 = {'ax', 'cx'}
    row['col2'] = 1 if row.col1 + 'x' in list1 else 0
    return row

df2 = df.apply(func, axis='columns')

# OUTPUTS : 
#  col1  col2
#0    a     1
#1    b     0
#2    c     1
#3    d     0

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.