[英]How to keep only the most recent revised order for each order in 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: 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
UPDATE: 更新:
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
One way is use drop_duplicates, note dataframe should be sorted on RevNum from smallest to largest or you can add sort_values: 一种方法是使用drop_duplicates,请注意应将数据帧在RevNum上从最小到最大排序,或者可以添加sort_values:
df1.drop_duplicates(subset='OrderNum', keep='last')
Output: 输出:
OrderNum RevNum TotalPrice
3 0AXL3 3 $8.00
6 0BDF1 2 $8.50
OR 要么
df1[~df1.duplicated(subset='OrderNum', keep='last')]
Output: 输出:
OrderNum RevNum TotalPrice
3 0AXL3 3 $8.00
6 0BDF1 2 $8.50
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.