python – 从Pandas数据框中获取最后一个条目的最佳方法

我最近必须获得某些项目的最后设置状态,标记为ID.我找到了这个答案: Python : How can I get Rows which have the max value of the group to which they belong?

令我惊讶的是,只有~2e6行的数据集相当慢.但是我不需要获得所有最大值,只需要最后一个.

import numpy as np
import pandas as pd

df = pd.DataFrame({
    "id": np.random.randint(1, 1000, size=5000),
    "status": np.random.randint(1, 10, size=5000),
    "date": [
        time.strftime("%Y-%m-%d", time.localtime(time.time() - x))
        for x in np.random.randint(-5e7, 5e7, size=5000)
    ],
})

%timeit df.groupby('id').apply(lambda t: t[t.date==t.date.max()])
1 loops, best of 3: 576 ms per loop

%timeit df.reindex(df.sort_values(["date"], ascending=False)["id"].drop_duplicates().index)
100 loops, best of 3: 4.82 ms per loop

第一个是我在链接中找到的解决方案,这似乎是一种允许更复杂操作的方法.

但是对于我的问题,我可以排序和删除重复项和重新索引,这会更好地执行.特别是在较大的数据集上,这确实有所不同.

我的问题:有没有其他方法可以实现我想做的事情?可能会有更好的表现?

最佳答案 解决此问题的另一种方法是在groupby上使用聚合,然后在完整数据帧上进行选择.

df.iloc[df.groupby('id')['date'].idxmax()]

这似乎比您提出的解决方案快5-10倍(见下文).请注意,这仅在’date’列是数字而不是字符串类型时才有效,并且此转换还可以加快基于排序的解决方案:

# Timing your original solutions:
%timeit df.groupby('id').apply(lambda t: t[t.date==t.date.max()])
# 1 loops, best of 3: 826 ms per loop
%timeit df.reindex(df.sort_values(["date"], ascending=False)["id"].drop_duplicates().index)
# 100 loops, best of 3: 5.1 ms per loop

# convert the date
df['date'] = pd.to_datetime(df['date'])

# new times on your solutions
%timeit df.groupby('id').apply(lambda t: t[t.date==t.date.max()])
# 1 loops, best of 3: 815 ms per loop
%timeit df.reindex(df.sort_values(["date"], ascending=False)["id"].drop_duplicates().index)
# 1000 loops, best of 3: 1.99 ms per loop

# my aggregation solution
%timeit df.iloc[df.groupby('id')['date'].idxmax()]
# 10 loops, best of 3: 135 ms per loop
点赞