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

如何在pandas dataframe中删除id校验不通过的行

解决方案

实现思路

  • 先自定义ID有效性校验函数,完全匹配你给出的校验规则
  • 用apply方法对id列逐行校验,只保留返回True的行
  • 过滤完成后重置索引保证序号连续

完整代码

import pandas as pd

# 示例数据
d = {'name': ['a', 'b', 'c', 'd'], 'id': [9356622,9030321,9408530, 1112200]}
df = pd.DataFrame(data=d)

# ID有效性校验函数
def is_valid(id_num):
    id_str = str(id_num)
    # 非7位ID直接判定为无效
    if len(id_str) != 7:
        return False
    # 前6位对应系数[7,6,5,4,3,2]相乘求和
    coeff = [7,6,5,4,3,2]
    total = sum(int(id_str[i]) * coeff[i] for i in range(6))
    # 校验求和结果最后一位是否与ID最后一位相等
    return total % 10 == int(id_str[-1])

# 过滤无效ID行,重置索引
df_valid = df[df['id'].apply(is_valid)].reset_index(drop=True)
print(df_valid)

输出结果

运行代码后会自动删除无效ID对应的行,最终输出的有效数据如下:

name       id
0    a  9356622
1    b  9030321
2    c  9408530

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.16 17:45:00