-2

I want to return the index of the last element of a pandas series. I've been looking at SO entries, but none of the solutions worked.

I tried

 last_element=df.index[-1]

and

 last_element=df[-1].index
cheesus
  • 1,111
  • 1
  • 16
  • 44
  • 1
    Can you add some data sample for explain, why not working? – jezrael Oct 23 '19 at 07:53
  • Then `df[-1].index` should do IIUC? – yatu Oct 23 '19 at 07:53
  • Could you post the error messages (if you get any), or the "wrong" results you are getting using the methods mentioned in your question? The first method seems to work well for me. – UJIN Oct 23 '19 at 08:35

4 Answers4

1

Try this:

df.reset_index(inplace=True)
df[-1].index
Kshitij Saxena
  • 930
  • 8
  • 19
0

Try

 df.last_valid_index()

Works for me.

Edit:

To store last element you can use iloc

last_element = df.iloc[-1:]
tyb9900
  • 214
  • 2
  • 11
  • 1
    [`DataFrame.last_valid_index`](http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.last_valid_index.html) - Return index for last non-NA/null value. - it is somethibng else like need OP – jezrael Oct 23 '19 at 07:58
  • 1
    @cheesus - exactly, answer is really bad for general data with mising values, not use it. – jezrael Oct 23 '19 at 08:16
  • all is wrong, OP need `I want to return the index of the last element of a pandas series. ` – jezrael Oct 23 '19 at 08:47
  • 1
    yes, in my case there won't be a nan value at the last row ever :) – cheesus Oct 23 '19 at 09:37
0

Call the tail() function with the argument 1 (you want one element from the end, or the last element), and index[0] on this, which returns the index of the element.

df.tail(1).index[0]

Check out this post for more details: index And this one for info about tail: tail function

Xhattam
  • 195
  • 1
  • 11
0

I know you said it didn't work for you, but really the way I usually retrieve the last index is with df.index[-1]. I tested it and it works both for DataFrames and Series:

df = pd.DataFrame(data={'col1':[1,4,5,3,3,5,6,7,8,9,5,4,2], 
                        'col2':[1,4,5,3,3,5,6,7,8,9,5,4,2]})

df.index[-1]
>> 12

And

df = pd.Series([1,4,5,3,3,5,6,7,8,9,5,4,2])

df.index[-1]
>> 12

If this doesn't work, can you tell us more about the errors you are getting?

UJIN
  • 1,648
  • 13
  • 28