Home > database >  Pandas create boolean column from subset index array
Pandas create boolean column from subset index array

Time:01-04

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?

CodePudding user response:

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
  •  Tags:  
  • Related