Python – How do I add a column to a data frame using a list of row numbers?

How do I add a column to a data frame using a list of row numbers?… here is a solution to the problem.

How do I add a column to a data frame using a list of row numbers?

I have a data frame and want to add a new bool value column that references a list of row numbers.

>>> df
    col1  col2
0     1     1
1     2     2
2     4     3
3     8     4

>>> lst_rowNumbers
[1, 3]

The result is as follows:

    col1  col2   bool
0     1     1  False
1     2     2   True
2     4     3  False
3     8     4   True

I thought it would work, but it didn’t.

>>> df['bool'] = False
>>> df.iloc[ lst_rowNumbers ]['bool'] = True

What do I do with Pandas?

Solution

If you want to select by index name:

df['bool'] = False
df.loc[ lst_rowNumbers , 'bool'] = True

Or:

df['bool'] = df.index.isin(lst_rowNumbers)

print (df)
   col1  col2   bool
0     1     1  False
1     2     2   True
2     4     3  False
3     8     4   True

If you need to

select by location, you need to Index.get_loc by the true index value returned by the ISIN index:

df['bool'] = df.index.isin(df.index[lst_rowNumbers])

print (df)
   col1  col2   bool
a     1     1  False
b     2     2   True
c     4     3  False
d     8     4   True

Related Problems and Solutions