Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get row index from DataFrame row

Is it possible to get the row number (i.e. "the ordinal position of the index value") of a DataFrame row without adding an extra row that contains the row number (the index can be arbitrary, i.e. even a MultiIndex)?

>>> import pandas as pd
>>> df = pd.DataFrame({'a': [2, 3, 4, 2, 4, 6]})
>>> result = df[df.a > 3]
>>> result.iloc[0]
a    4
Name: 2, dtype: int64
# but how can I get the original row index of iloc[0] in df?

I could have done df['row_index'] = range(len(df)) which would maintain the original row number, but I am wondering if Pandas has a built-in way of doing this.

like image 583
orange Avatar asked Feb 06 '16 07:02

orange


People also ask

How do you get a row from a DataFrame in Python?

To get the nth row in a Pandas DataFrame, we can use the iloc() method. For example, df. iloc[4] will return the 5th row because row numbers start from 0.


1 Answers

Access the .name attribute and use get_loc:

In [10]:
df.index.get_loc(result.iloc[0].name)

Out[10]:
2
like image 82
EdChum Avatar answered Nov 17 '22 04:11

EdChum