python - 按分组从数据框中选择行并在给定列中选择最大值
问题描述
我有一个结构如下的数据集。这是一个示例,所以请想象一个包含许多序列的数据框。几件事要精确:
time
按降序排列。
created_at
也是降序排列的。当新的OR出现时两者都time
重置。created_at
source
currency
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
currency
app_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
解决方案
您可以调用last
which 计算每个组的最后一个值并用于iloc
获取行值:
df.groupby(["source", "currency", "app_v"]).last().iloc[-1]
您可以使用 name 属性访问索引组值,例如:
df.get_group(df.groupby('a').last().iloc[-1].name)
推荐阅读
- mongodb - 如何使用 Mongodb 验证器验证非空字段
- sql - insert into statements,如何快速插入记录
- javascript - 可调整大小的拆分 DIV Vue.js
- flutter - 如何在颤动中管理开关小部件的原生外观
- android - queryPurchases() 返回一个空列表
- html - 防止 Flexbox 变大,截断文本
- c++ - 如何解析包含整数的字符串并检查是否大于C++中的最大值
- javascript - 我如何/可以通过在请求正文中使用 x-www-form-urlencoded 来发送我的有效负载的 RxJs POST 请求
- android - 如何柔化和调整cameraX中预览和抓图的亮度?
- javascript - 使用 R Shiny 比较条件面板中的日期