EmJ
EmJ

Reputation: 4618

How to add a column with missing values in pandas in python

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 namesas follows.

lst = [a, e]

I want to add a column named as final_values to my current dataframe where;

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

Answers (1)

jezrael
jezrael

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

Related Questions