Reputation: 4618
I have a pandas dataframe as follows.
name x1 x2
0 a 5 5
1 b 8 6
2 e 3 8
I also have a list of names
as follows.
lst = [a, e]
I want to add a column named as final_values
to my current dataframe where;
name
is in lst
the column value should be 1
0
So, my updated dataframe should look as follows.
name x1 x2 final_values
0 a 5 5 1
1 b 8 6 0
2 e 3 8 1
Is there any easy way of doing this in pandas?
I am happy to provide more details if needed.
Upvotes: 2
Views: 1188
Reputation: 863531
Check membership by Series.isin
and cast boolean to integer for True/False
to 1/0
map:
df['final_values'] = df['name'].isin(lst).astype(int)
Or use numpy.where
:
df['final_values'] = np.where(df['name'].isin(lst), 1, 0)
Upvotes: 2