使用 pandas groupby 获取满足条件的最后一行

问题描述 投票:0回答:1

我有一个像这样的数据框:

日期_来自 日期_至 item_id VALUE_NEW VALUE_OLD cost_var
1/1/1900 00:00:00 2022 年 3 月 11 日 15:31:18 452953 5366,46 4024,71 33.34%
2022 年 3 月 11 日 15:31:18 2200年1月1日00:00:00 452953 9122,57 5366,46 69.99%
1/1/1900 00:00:00 2022 年 3 月 11 日 15:31:18 452954 5366,46 4024,71 33.34%
2022 年 3 月 11 日 15:31:18 2200年1月1日00:00:00 452954 9122,57 5366,46 69.99%
1/1/1900 00:00:00 2021年7月21日16:30:46 452961 6170,98 4024,71 53.33%
2021年7月21日16:30:46 11/3/2022 15:31:09 452961 5312 6170,98 13.92%
11/3/2022 15:31:09 2200年1月1日00:00:00 452961 9122,57 5312 71.74%
1/1/1900 00:00:00 2021年10月13日14:39:55 801286 4052,1 1332,8 204.03%
2021年10月13日14:39:55 13/10/2021 14:43:09 801286 4,4732 4052,1 99.89%
13/10/2021 14:43:09 2022 年 3 月 2 日 17:16:23 801286 4473,2 4,4732 99900.00%
2022 年 3 月 2 日 17:16:23 2200年1月1日00:00:00 801286 4946,8 4473,2 10.59%

我需要检查每个 item_id,并获取 cost_var >60% 的最后一行。如果是最后一行,那没问题,但如果有下一行,那就是 <60%, I have to drop the last row>60%。输出应如下所示:

日期_来自 日期_至 item_id VALUE_NEW VALUE_OLD cost_var
2022 年 3 月 11 日 15:31:18 2200年1月1日00:00:00 452953 9122,57 5366,46 69.99%
2022 年 3 月 11 日 15:31:18 2200年1月1日00:00:00 452954 9122,57 5366,46 69.99%
11/3/2022 15:31:09 2200年1月1日00:00:00 452961 9122,57 5312 71.74%

项目 802186 没有返回任何值,因为最后一行>60% (99900.00%) 有下一行和 cost_var<60% (10.59%)... Is it possible to do? I couldn't find a way to solve it.

python pandas dataframe group-by filtering
1个回答
2
投票

我们可以使用

item_id
选择每个
groupby
的最后一行,并使用
cost_var > 60%
仅选择
query
的行。

df.groupby('item_id', as_index=False).last().query("cost_var.str.rstrip('%').astype('float')>60")

© www.soinside.com 2019 - 2024. All rights reserved.