如何仅保留 pandas 中每个订单的最新修订订单 [英] How to keep only the most recent revised order for each order in Pandas

查看:60
本文介绍了如何仅保留 pandas 中每个订单的最新修订订单的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

说我有一个数据框,该数据框在两个不同的列中跟踪订单号和该订单的修订号,如下所示:

Say I have a data frame that tracks the order number, and the revision number for that order in two different columns like so:

OrderNum  RevNum  TotalPrice
 0AXL3     0       $5.00
 0AXL3     1       $4.00
 0AXL3     2       $7.00
 0AXL3     3       $8.00
 0BDF1     0       $3.00
 0BDF1     1       $2.50
 0BDF1     2       $8.50

我们想要的结果是一个新的数据框,该数据框仅包含每个订单的最新版本,因此:

The result we want is a new data frame that only has the most recent version of each order, so :

OrderNum  RevNum  TotalPrice
 0AXL3     3       $8.00
 0BDF1     2       $8.50

在大熊猫中有快速的方法吗?

Is there a quick way to do this in pandas?

推荐答案

IIUC:

In [100]: df.groupby('OrderNum', as_index=False).last()
Out[100]:
  OrderNum  RevNum TotalPrice
0    0AXL3       3      $8.00
1    0BDF1       2      $8.50

更新:

如果数据框中还有其他列,这会保留那些 还有吗?

If there were other columns in the data frame, would this keep those as well?

In [116]: df['new'] = np.arange(len(df))

In [117]: df
Out[117]:
  OrderNum  RevNum TotalPrice  new
0    0AXL3       0      $5.00    0
1    0AXL3       1      $4.00    1
2    0AXL3       2      $7.00    2
3    0AXL3       3      $8.00    3
4    0BDF1       0      $3.00    4
5    0BDF1       1      $2.50    5
6    0BDF1       2      $8.50    6

In [118]: df.groupby('OrderNum', as_index=False).last()
Out[118]:
  OrderNum  RevNum TotalPrice  new
0    0AXL3       3      $8.00    3
1    0BDF1       2      $8.50    6

这篇关于如何仅保留 pandas 中每个订单的最新修订订单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆