2

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;

  • if the name is in lst the column value should be 1
  • else 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.

1
  • 1
    df.name.isin(lst).astype(int) Commented Mar 26, 2019 at 13:22

1 Answer 1

2

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)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.