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
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
Try this:
df.reset_index(inplace=True)
df[-1].index
Try
df.last_valid_index()
Works for me.
Edit:
To store last element you can use iloc
last_element = df.iloc[-1:]
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
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?