Reputation:
I have this dataframe having one column of my interest:
Col1
code
goal
python
detail
I would like to create a new column, Col2 having values 1 or 0 depending on rows' value in Col1; specifically:
my_list=['goal', 'detail', 'objective']
, then assign 1;My output would be:
Col1 Col2
code 0
goal 1
python 0
detail 1
I tried
# set default value
df['Col2'] = 0
# update according to conditions
df.loc[df['Col1'].str.contains('goal'), 'Col2'] = 1
df.loc[df['Col1'].str.contains('detail'), 'Col2'] = 1
df.loc[df['Col1'].str.contains('objective'), 'Col2'] = 1
but this seems to be partially wrong.
I think I should use apply and consider word x in my_list
rather than doing manually (it would be difficult in case of many, many!, values in the list).
I hope you can help me.
Upvotes: 0
Views: 1315
Reputation: 8302
Use np.where
+ Series.isin
import numpy as np
my_list=['goal', 'detail', 'objective']
df['Col2'] = np.where(df.Col1.isin(my_list), 1, 0)
or as mentioned by @Ch3steR
df['Col2'] = df.Col1.isin(my_list).astype('int')
Col1 Col2
0 code 0
1 goal 1
2 python 0
3 detail 1
Upvotes: 1
Reputation: 531
How about apply:
import pandas as pd
df = pd.DataFrame(data = ['code', 'goal', 'python', 'detail'], columns = ['Col1'])
mylist=['goal', 'detail', 'objective']
df['Col2'] = df['Col1'].apply(lambda cell: 1 if cell in mylist else 0)
gives
Col1 Col2
0 code 0
1 goal 1
2 python 0
3 detail 1
Upvotes: 0