1

I have a DataFrame, let's say:

#d = {'col1': [1, 2, 3], 'col2': [3, 4, 5]} // that's what the data might look like
df = pd.DataFrame(data=d)

and I have a np array with [0, 2].

Now I want to add a column to the DataFrame, where there is a 1, when the index of the row is in the np array, otherwise a 0.

Does anyone have an idea?

1 Answer 1

3

Use Index.isin with cast mask to integers:

d = {'col1': [1, 2, 3], 'col2': [3, 4, 5]} 
df = pd.DataFrame(data=d)

a = np.array([0, 2])

df['new'] = df.index.isin(a).astype(int)
#alternative
#df['new'] = np.in1d(df.index, a).astype(int)

Or use numpy.where:

df['new'] = np.where(df.index.isin(a), 1, 0)
#alternative
#df['new'] = np.where(np.in1d(df.index, a), 1, 0)

print (df)
   col1  col2  new
0     1     3    1
1     2     4    0
2     3     5    1
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.