24

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.

2 Answers 2

27

Access the .name attribute and use get_loc:

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

Out[10]:
2
Sign up to request clarification or add additional context in comments.

6 Comments

Unfortunately, this refers to the original index. Try: df = pd.DataFrame({'a': [2, 3, 4, 2, 4, 6]}, index=[4, 3, 7, 1, 5, 9]);result = df[df.a > 3];result.iloc[0].name which returns 7.
sorry what are you after exactly? the ordinal position of the index value?
Yes, sorry "row number" may have been misleading.
Thanks for the edit. I think it should to be df.index.get_loc(result.index[0]) if I'm not mistaken...
result.index[0] is the same as result.iloc[0].name the difference here is that you're explicitly accessing the first index element, whilst the latter is accessing the first element's index value
|
0

Looking this from a different side:

for r in df.itertuples():
    getattr(r, 'Index')

Where df is the data frame. May be you want to use a conditional to get the index when a condition are met.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.