Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Pandas create boolean column from subset index array

I would like to create a boolean column in a pandas data frame of length 499.
I have an array a of index values :

a = np.array([206, 252, 272, 315, 349, 374, 394, 406, 440, 466])

I would like a column of True values at these index positions in the df data frame.
Simplified example to work on:

arr = np.array(range(0,499))
df = pd.DataFrame(data = arr, columns = ['var1'])

any ideas?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Create a list of 499 False values and use .loc to set True to selected rows from a array:

df = pd.DataFrame(data=[False]*499, columns=['var1'])
df.iloc[a] = True

Output:

>>> df[df['var1'] == True]
     var1
206  True
252  True
272  True
315  True
349  True
374  True
394  True
406  True
440  True
466  True
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading