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

如何调用自定义函数遍历DataFrame列生成密码强度新列?

问题解决方法

错误原因分析

你写的循环代码有两个关键问题:

  • 变量j未定义,应该明确指定新列名"strength"
  • 循环中每次执行FinalData["strength"] = password_complexity(i)都会把整个列覆盖为当前i的计算结果,最终所有行的值都会变成最后一个元素的计算结果(比如你的示例中最后一个元素是azerty,返回1,所以全列都是1)

另外你的password_complexity函数存在两个小问题:

  • 未导入string模块,运行时会报错
  • 最后一个elif的判断逻辑冗余,因为能走到这一步的密码必然包含非小写/大写/数字的字符(也就是标点),无需再用any判断

修正后的实现代码

步骤1:导入依赖并修正复杂度函数

import string
import pandas as pd

def password_complexity(password):
    if all(x.islower() for x in password):
        return 1
    elif all(x.islower() or x.isupper() for x in password):
        return 2
    elif all(x.islower() or x.isdigit() for x in password):
        return 3
    elif all(x.islower() or x.isupper() or x.isdigit() for x in password):
        return 4
    # 走到这里说明包含标点符号,直接返回5
    return 5

步骤2:生成新列

无需手动循环,直接用pandas的apply方法批量处理:

# 假设你的DataFrame是FinalData
FinalData["strength"] = FinalData["plaintPDP"].apply(password_complexity)

测试结果

用你提供的示例数据测试:

DomainplaintPDPstrength
NaN25frozen3
NaNazerty1

完全符合预期。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.02 19:41:04