How do I get the name of the rows from the index of a data frame?

PythonPandasDataframe

Python Problem Overview


Consider a data frame with row names that aren't a column of their own per se, such as the following:

        X  Y
 Row 1  0  5
 Row 2  8  1
 Row 3  3  0

How would I extract the name of these rows as a list, if I have their index? For example, it would look something like:

function_name(dataframe[indices])
> ['Row 1', 'Row 2']

Python Solutions


Solution 1 - Python

df.index

  • outputs the row names as pandas Index object.

list(df.index)

  • casts to a list.

df.index['Row 2':'Row 5']

  • supports label slicing similar to columns.

Solution 2 - Python

this seems to work fine :

dataframe.axes[0].tolist()

Solution 3 - Python

If you want to pull out only the index values for certain integer-based row-indices, you can do something like the following using the iloc method:

In [28]: temp
Out[28]:
       index                 time  complete
row_0      2  2014-10-22 01:00:00         0
row_1      3  2014-10-23 14:00:00         0
row_2      4  2014-10-26 08:00:00         0
row_3      5  2014-10-26 10:00:00         0
row_4      6  2014-10-26 11:00:00         0

In [29]: temp.iloc[[0,1,4]].index
Out[29]: Index([u'row_0', u'row_1', u'row_4'], dtype='object')

In [30]: temp.iloc[[0,1,4]].index.tolist()
Out[30]: ['row_0', 'row_1', 'row_4']

Solution 4 - Python

if you want to get the index values, you can simply do:

>dataframe.index

this will output a pandas.core.index

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionlinamntView Question on Stackoverflow
Solution 1 - PythonAdam HughesView Answer on Stackoverflow
Solution 2 - PythonAlex KushkuleyView Answer on Stackoverflow
Solution 3 - PythonK RaphaelView Answer on Stackoverflow
Solution 4 - PythonchunpoonView Answer on Stackoverflow