python - Pandas:如何为 groupby 获取具有最大时间戳的行
问题描述
给定一个DataFrame,我想为具有最大时间戳的行创建一个新的DataFrame,用于列组合
组合:类别、修订、类型、子类型
sub_type 可能/没有值(但 None 是其唯一性的一部分)
根据上述内容,我不会有重复项(时间戳没有联系)
action category YYYYMM timestamp sub_type type
0 buy A 202002 4 None apple
1 sell A 202002 5 None apple
2 buy A 202002 4 green apple
3 buy A 202002 4 red apple
4 sell A 202002 3 red apple
5 sell A 202002 1 None orange
6 sell B 202002 6 None apple
上述 DataFrame 的结果如下所示:
action category revision timestamp sub_type type
0 sell A 202002 5 None apple
1 buy A 202002 4 green apple
2 buy A 202002 4 red apple
3 sell A 202002 1 None orange
4 sell B 202002 6 None apple
基本上 - 我想要属性组合的最后一个动作
解决方案
所以我们需要fillna
在这里使用,因为 None == None 将返回 True。之后我们可以sort_values
做drop_duplicates
out = df.sort_values('timestamp').fillna('None').\
drop_duplicates(['category','sub_type','YYYYMM','type'],keep='last').\
sort_index()
out
Out[128]:
action category YYYYMM timestamp sub_type type
1 sell A 202002 5 None apple
2 buy A 202002 4 green apple
3 buy A 202002 4 red apple
5 sell A 202002 1 None orange
6 sell B 202002 6 None apple
推荐阅读
- r - Octave 和 R 中的线性回归
- android - 由于弹出窗口,Android WebView 不允许使用 @solid/react 库进行身份验证
- r - 如何根据情节的存在制作闪亮的渲染图?
- python-3.x - 如何在 asyncio 中停止协程而不发出警告“任务已被破坏,但它正在等待处理!”
- javascript - 返回从多行文本文件中获得的拆分字符串
- c - 从内核级别使用 sys_open
- python - 如何使用 SimpleHttpRequestHandler 运行 python
- javascript - 如果订单低于 X(不含增值税),则向 WooCommerce 结帐添加费用
- database - 一个实体的多个实例转化为另一个实体
- ios - 如何让领域集合观察者部分像`NSFetchedResultsController`一样感知?