Python 返回系列中最后一个元素的索引

Python 返回系列中最后一个元素的索引,python,pandas,time-series,Python,Pandas,Time Series,我想返回熊猫系列最后一个元素的索引。我一直在研究,但没有一个解决方案有效 我试过了 last_element=df.index[-1] 及 试一试 对我有用 编辑: 要存储最后一个元素,可以使用iloc last_element = df.iloc[-1:] 试试这个: df.reset_index(inplace=True) df[-1].index 调用带有参数1的tail()函数(您希望从末尾或最后一个元素中提取一个元素),并在此基础上调用index[0],该函数返回元素的索引 d

我想返回熊猫系列最后一个元素的索引。我一直在研究,但没有一个解决方案有效

我试过了

 last_element=df.index[-1]

试一试

对我有用

编辑:

要存储最后一个元素,可以使用
iloc

last_element = df.iloc[-1:]
试试这个:

df.reset_index(inplace=True)
df[-1].index
调用带有参数
1
tail()
函数(您希望从末尾或最后一个元素中提取一个元素),并在此基础上调用
index[0]
,该函数返回元素的索引

df.tail(1.index[0]

查看此帖子了解更多详细信息:
这是关于
tail
的信息:

我知道你说它不适合你,但实际上我通常检索最后一个索引的方法是使用
df.index[-1]
。我测试了它,它适用于数据帧和系列:

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


如果这不起作用,你能告诉我们更多关于你得到的错误吗?

你能添加一些数据样本来解释为什么不起作用吗?然后
df[-1]。index
应该做IIUC吗?你能发布错误消息(如果你得到),或者使用你问题中提到的方法得到的“错误”结果吗?第一种方法似乎对我很有效返回最后一个非NA/null值的索引。-这是另一种需要OP@cheesus-准确地说,答案对于具有错误值的常规数据来说是非常糟糕的,不要使用它。一切都是错误的,OP need
我想返回系列中最后一个元素的索引
yes,在我的例子中,最后一行永远不会有nan值:)尝试创建一个
pd.Series
如下:
s=pd.Series({0:1});s、 追加(pd.Series({0:2}))
如果您的序列有索引,那么
df[-1]。索引应该可以工作。显示系列的标题或任何错误。
df.reset_index(inplace=True)
df[-1].index
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
df = pd.Series([1,4,5,3,3,5,6,7,8,9,5,4,2])

df.index[-1]
>> 12