Him3090
Him3090

Reputation: 21

Adding column in a dataframe with 0,1 values based on another column values

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)

Upvotes: 0

Views: 1899

Answers (2)

mozway
mozway

Reputation: 261675

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

Upvotes: 1

Piotr Żak
Piotr Żak

Reputation: 2132

str.containts

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

enter image description here

Upvotes: 2

Related Questions