23

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

23

Access the .name attribute and use get_loc:

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

Out[10]:
2
6
  • 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.
    – orange
    Feb 6, 2016 at 7:27
  • 1
    sorry what are you after exactly? the ordinal position of the index value?
    – EdChum
    Feb 6, 2016 at 7:38
  • Yes, sorry "row number" may have been misleading.
    – orange
    Feb 6, 2016 at 8:18
  • Thanks for the edit. I think it should to be df.index.get_loc(result.index[0]) if I'm not mistaken...
    – orange
    Feb 7, 2016 at 4:42
  • 1
    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
    – EdChum
    Feb 7, 2016 at 19:45
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.

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.