+2 votes
in Programming Languages by (73.2k points)

I want to get the index values of row of a Pandas DataFrame as a list or Numpy array. How can I get those values?

E.g.

>>> df

      animal

0  alligator

1        bee

2     falcon

3       lion

4     monkey

5     parrot

6      shark

7      whale

8      zebra

I want either 

[0, 1, 2, 3, 4, 5, 6, 7, 8]

or 

array([0, 1, 2, 3, 4, 5, 6, 7, 8])

1 Answer

+1 vote
by (346k points)
selected by
 
Best answer

To get row index values as a Numpy array, do the following:

df.index.values

and to get row index values as a list, do the following:

df.index.values.tolist()

Here is your example:

>>> import pandas as pd
>>> df = pd.DataFrame({'animal':['alligator', 'bee', 'falcon', 'lion','monkey', 'parrot', 'shark', 'whale', 'zebra']})
>>> df
      animal
0  alligator
1        bee
2     falcon
3       lion
4     monkey
5     parrot
6      shark
7      whale
8      zebra
>>> df.animal.tolist()
['alligator', 'bee', 'falcon', 'lion', 'monkey', 'parrot', 'shark', 'whale', 'zebra']
>>> df.index
RangeIndex(start=0, stop=9, step=1)
>>> df.index.values
array([0, 1, 2, 3, 4, 5, 6, 7, 8])
>>> df.index.values.tolist()
[0, 1, 2, 3, 4, 5, 6, 7, 8]


...