首页 > 解决方案 > 按分组从数据框中选择行并在给定列中选择最大值

问题描述

我有一个结构如下的数据集。这是一个示例,所以请想象一个包含许多序列的数据框。几件事要精确: time按降序排列。 created_at也是降序排列的。当新的OR出现时两者都time重置。created_atsourcecurrency

index  time          app_v   last     source   currency   created_at
1      2019-10-23    3       4488     gol      JPY        66
2      2019-10-23    29193   6687     gol      JPY        65
3      2019-10-22    3       4587     gol      JPY        64
4      2019-10-20    3       5687     gol      JPY        63
5      2019-10-19    3       34787    gol      JPY        62
6      2019-10-18    3       11789    gol      JPY        61
...

预期输出是last按和time分组的最新输出。对于此示例,我们有 2 行对应:source currencyapp_v

index  time          app_v   last     source   currency   created_at
1      2019-10-23    3       4488     gol      JPY        66
2      2019-10-23    29193   6687     gol      JPY        65

标签: pythonpandas

解决方案


您可以调用lastwhich 计算每个组的最后一个值并用于iloc获取行值:

df.groupby(["source", "currency", "app_v"]).last().iloc[-1]

您可以使用 name 属性访问索引组值,例如: df.get_group(df.groupby('a').last().iloc[-1].name)


推荐阅读