数据帧中最后一个元素的访问索引 [英] Access index of last element in data frame

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

问题描述

我一直在寻找这个,但是我似乎找不到它(尽管它必须是非常琐碎的).

I've looking around for this but I can't seem to find it (though it must be extremely trivial).

我遇到的问题是我想检索数据帧的第一个条目和最后一个条目的列的值.但是,如果我这样做:

The problem that I have is that I would like to retrieve the value of a column for the first and last entries of a data frame. But if I do:

df.ix[0]['date']

我得到:

datetime.datetime(2011, 1, 10, 16, 0)

但如果我这样做:

df[-1:]['date']

我得到:

myIndex
13         2011-12-20 16:00:00
Name: mydate

使用其他格式.理想情况下,我希望能够访问数据帧的最后一个索引的值,但找不到方法.

with a different format. Ideally, I would like to be able to access the value of the last index of the data frame, but I can't find how.

我什至试图用索引值创建一列(IndexCopy)并尝试:

I even tried to create a column (IndexCopy) with the values of the index and try:

df.ix[df.tail(1)['IndexCopy']]['mydate']

但是这也会产生不同的格式(因为df.tail(1)['IndexCopy']不会输出简单的整数).

but this also yields a different format (since df.tail(1)['IndexCopy'] does not output a simple integer).

有什么想法吗?

推荐答案

以前的答案现已由

The former answer is now superseded by .iloc:

>>> df = pd.DataFrame({"date": range(10, 64, 8)})
>>> df.index += 17
>>> df
    date
17    10
18    18
19    26
20    34
21    42
22    50
23    58
>>> df["date"].iloc[0]
10
>>> df["date"].iloc[-1]
58


我想到的最短的方法是使用.iget():

>>> df = pd.DataFrame({"date": range(10, 64, 8)})
>>> df.index += 17
>>> df
    date
17    10
18    18
19    26
20    34
21    42
22    50
23    58
>>> df['date'].iget(0)
10
>>> df['date'].iget(-1)
58

或者:

>>> df['date'][df.index[0]]
10
>>> df['date'][df.index[-1]]
58

还有.first_valid_index().last_valid_index(),但是取决于您是否要排除NaN,它们可能不是您想要的.

There's also .first_valid_index() and .last_valid_index(), but depending on whether or not you want to rule out NaNs they might not be what you want.

请记住,df.ix[0]不会给您第一个,但给您索引为0的那个.例如,在上述情况下,df.ix[0]会产生

Remember that df.ix[0] doesn't give you the first, but the one indexed by 0. For example, in the above case, df.ix[0] would produce

>>> df.ix[0]
Traceback (most recent call last):
  File "<ipython-input-489-494245247e87>", line 1, in <module>
    df.ix[0]
[...]
KeyError: 0

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

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