0

In the example dataframe created below:

   Name  Age
0   tom   10
1  nick   15
2  juli   14

I want to add another column 'Checks' and get the values in it as 0 or 1 if the list check contain s the value as check=['nick']

I have tried the below code:

import numpy as np
import pandas as pd
 
# initialize list of lists
data = [['tom', 10], ['nick', 15], ['juli', 14]]
 
check = ['nick']
 
# Create the pandas DataFrame
df = pd.DataFrame(data, columns = ['Name', 'Age'])

df['Checks'] = np.where(df['Name']== check[], 1, 0)

#print dataframe.
print(df)
print(check)
2
  • 1
    use isin since check is a list np.where(df['Name'].isin(check), 1, 0) or df['Name'].isin(check).astype(int) Commented Aug 18, 2021 at 17:23
  • see stackoverflow.com/questions/17071871/… for detailed info Commented Aug 18, 2021 at 17:26

2 Answers 2

2

str.containts

phrase = ['tom', 'nick']
df['check'] = df['Name'].str.contains('|'.join(phrase))

enter image description here

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

Comments

1

You can use pandas.Series.isin:

check = ['nick']
df['check'] = df['Name'].isin(check).astype(int)

output:

   Name  Age  check
0   tom   10      0
1  nick   15      1
2  juli   14      0

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.