Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 497
jonas Avatar asked Dec 06 '25 02:12

jonas


1 Answers

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
like image 116
Corralien Avatar answered Dec 08 '25 15:12

Corralien



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!