You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Pandas如何提取零件编号变更前最后一行数量,解决首尾行取值错误

解决方案

你需要的是每个part_no_2分组的最后一行记录,直接用pandas自带的分组聚合功能就能实现,不需要手动写复杂的行判断逻辑,最优实现方案如下:


方案1:直接提取每个零件号的最终数量(输出和预期结果完全一致)

直接按part_no_2字段分组,取每个分组最后一行的qty值即可:

import pandas as pd
import numpy as np

df = pd.DataFrame({
    'part_no_2': [22, 22, 22, 23, 23, 24, 25, 25, 25, 26],
    'qty': [0, 0, 4, 44, 22, 0, 7, 16, 5, 6]})

# 直接提取每个零件号最后一行的数量
result = df.groupby('part_no_2', as_index=False)['qty'].last()
print(result)

运行输出:

part_no_2  qty
0         22    4
1         23   22
2         24    0
3         25    5
4         26    6

方案2:在原数据集上标记每个分组最后一行/对应数量

如果需要保留原数据的所有行,仅新增列标注每个分组的最后一行,可以用反向偏移判断的逻辑,完美解决首尾行的判断问题:

# 标记每个分组的最后一行:下一行零件号不同 或 是整个数据集最后一行
df['is_last_of_group'] = (df['part_no_2'].shift(-1) != df['part_no_2']) | (df.index == len(df)-1)
# 仅在分组最后一行显示对应数量,其余位置留空
df['last_qty_of_group'] = np.where(df['is_last_of_group'], df['qty'], np.nan)
print(df)

运行输出:

part_no_2  qty  is_last_of_group  last_qty_of_group
0         22    0             False                 NaN
1         22    0             False                 NaN
2         22    4              True                 4.0
3         23   44             False                 NaN
4         23   22              True                22.0
5         24    0              True                 0.0
6         25    7             False                 NaN
7         25   16             False                 NaN
8         25    5              True                 5.0
9         26    6              True                 6.0

说明

两种方案都是pandas原生的向量化操作,性能远高于循环遍历,适合任意规模的数据集。

内容的提问来源于stack exchange,提问作者user2003052

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.27 06:36:03