如何访问 pandas 系列中的最后一个元素? [英] How to access the last element in a Pandas series?

查看:53
本文介绍了如何访问 pandas 系列中的最后一个元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

让我们考虑以下数据框:

Let us consider the following data frame:

import pandas as pd

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

如果我要访问熊猫系列 df ['col1'] 中的第一个元素,我可以简单地转到 df ['col1'] [0] .

If I want to access the first element in pandas series df['col1'], I can simply go df['col1'][0].

但是如何访问本系列中的 last 元素?我已经尝试过 df ['col1'] [-1] ,它返回以下错误:

But how can I access the last element in this series? I have tried df['col1'][-1] which returns the following error:

KeyError:-1L

KeyError: -1L

我知道我可以使用类似 df ['col1'] [len(df)-1] 的东西,但是为什么在这里无法进行反向索引?

I know that I could go for something like df['col1'][len(df)-1] but why is reverse indexing impossible here?

推荐答案

对于选择最后一个值,需要

For select last value need Series.iloc or Series.iat, because df['col1'] return Series:

print (df['col1'].iloc[-1])
3
print (df['col1'].iat[-1])
3

或将Series转换为numpy数组,然后选择last:

Or convert Series to numpy array and select last:

print (df['col1'].values[-1])
3

或使用 DataFrame.iloc DataFrame.iat -但必须通过

Or use DataFrame.iloc or DataFrame.iat - but is necessary position of column by Index.get_loc:

print (df.iloc[-1, df.columns.get_loc('col1')])
3
print (df.iat[-1, df.columns.get_loc('col1')])
3

或者可以使用索引的最后一个值(不必重复),并按

Or is possible use last value of index (necessary not duplicated) and select by DataFrame.loc:

print (df.loc[df.index[-1], 'col1'])
3

这篇关于如何访问 pandas 系列中的最后一个元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆