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)
Anurag Dabas
  • 23,866
  • 9
  • 21
  • 41
Him3090
  • 21
  • 7
  • 1
    use isin since check is a list `np.where(df['Name'].isin(check), 1, 0)` or `df['Name'].isin(check).astype(int)` – Anurag Dabas Aug 18 '21 at 17:23
  • see https://stackoverflow.com/questions/17071871/how-do-i-select-rows-from-a-dataframe-based-on-column-values for detailed info – Anurag Dabas Aug 18 '21 at 17:26

2 Answers2

2

str.containts

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

enter image description here

Piotr Żak
  • 2,046
  • 5
  • 18
  • 30
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
mozway
  • 194,879
  • 13
  • 39
  • 75