如何访问多索引数据帧的最后一个元素

2024-04-25 00:16:20 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个带有id和时间戳的数据帧作为多索引。数据帧中的索引按id和时间戳排序,我想为每个id选择最新的时间戳。例如:

IDs    timestamp     value
0      2010-10-30     1
       2010-11-30     2
1      2000-01-01     300
       2007-01-01     33
       2010-01-01     400
2      2000-01-01     11

所以基本上我想要的结果是

^{pr2}$

在大熊猫身上,命令是什么?在


Tags: 数据命令idids排序value时间timestamp
2条回答

给定此设置:

import pandas as pd
import numpy as np
import io

content = io.BytesIO("""\
IDs    timestamp     value
0      2010-10-30     1
0      2010-11-30     2
1      2000-01-01     300
1      2007-01-01     33
1      2010-01-01     400
2      2000-01-01     11""")

df = pd.read_table(content, header=0, sep='\s+', parse_dates=[1])
df.set_index(['IDs', 'timestamp'], inplace=True)

使用reset_index后跟groupby

^{pr2}$

收益率

              timestamp  value
IDs                           
0   2010-11-30 00:00:00      2
1   2010-01-01 00:00:00    400
2   2000-01-01 00:00:00     11

然而,这并不是最好的解决方案。应该有一种方法可以在不调用reset_index的情况下完成此操作。。。在


正如您在评论中指出的,last忽略了NaN值。要不跳过NaN值,可以使用groupby/agg,如下所示:

df.reset_index(['timestamp'], inplace=True)
grouped = df.groupby(level=0)
print(grouped.agg(lambda x: x.iloc[-1]))

你也可以用

df.groupby("IDs").tail(1)

这将获取级别“IDs”中每个标签的最后一行,并且不会忽略NaN值。在

相关问题 更多 >