假设我有一个包含 3 列的数据表:
Category Color Date
triangle red 2017-10-10
square yellow 2017-11-10
triangle blue 2017-02-10
circle yellow 2017-07-10
circle red 2017-09-10
我想找出每个类别的最早日期。 所以我想要的输出是:
Category Color Date
square yellow 2017-11-10
triangle blue 2017-02-10
circle yellow 2017-07-10
我浏览了几篇关于如何做到这一点的帖子:
Finding the min date in a Pandas DF row and create new Column
Pandas groupby category, rating, get top value from each category?
With Pandas in Python, select the highest value row for each group
还有更多。
一种流行的方法是 groupby 方法:
df.groupby('Category').first().reset_index()
但是如果我使用这种方法,那么它会按类别 分组,但它会保留triangle 的两条记录,因为它有两种不同的颜色。
是否有更好、更有效的方法来做到这一点?
请您参考如下方法:
您可以使用sort_values + drop_duplicates:
df.sort_values(['Date']).drop_duplicates('Category', keep='first')
Category Color Date
2 triangle blue 2017-02-10
3 circle yellow 2017-07-10
1 square yellow 2017-11-10
如果您想保留 Category 的原始顺序,您需要对 groupby 调用进行排序:
df.groupby('Category', group_keys=False, sort=False)\
.apply(lambda x: x.sort_values('Date'))\
.drop_duplicates('Category', keep='first')
Category Color Date
2 triangle blue 2017-02-10
1 square yellow 2017-11-10
3 circle yellow 2017-07-10
