[python][代码]遍历一个字典或列表替换其中的 NaN 值为None

代码定义了一个名为 replace_nan 的函数,其目的是遍历一个字典或列表,查找并替换其中的 NaN 值(不是数字,Not a Number)为 None

下面是代码的逐行解释:

  1. #coding:utf-8:指定文件的编码格式为UTF-8。
  2. import math:导入Python的数学模块,用于访问数学函数和常量。
  3. 定义了 replace_nan 函数,它接受一个参数 test_dict
  4. if isinstance(test_dict, dict)::检查 test_dict 是否是一个字典。
  5. for key in test_dict::遍历字典中的所有键。
  6. if (isinstance(test_dict[key], float) and math.isnan(test_dict[key]))::检查字典中当前键的值是否为浮点数,并且是否是 NaN
  7. test_dict[key] = None:如果是 NaN,则将其替换为 None
  8. else::如果当前值不是 NaN,则执行以下操作:
    • replace_nan(test_dict[key]):递归调用 replace_nan 函数,以处理字典中的嵌套结构。
  9. elif isinstance(test_dict, list)::检查 test_dict 是否是一个列表。
  10. for val in test_dict::遍历列表中的所有值。
  11. replace_nan(val):对列表中的每个值递归调用 replace_nan 函数。

这个函数可以处理嵌套的字典和列表结构,将所有 NaN 值替换为 None。不过,代码中有一个逻辑上的小错误:在处理字典的 else 块中,应该先递归调用 replace_nan 函数,然后再检查是否为列表。此外,代码没有考虑字典的值可能是其他可迭代类型,如集合或另一个字典的列表。如果需要处理这些情况,可能需要进一步扩展函数的功能。

#coding:utf-8
import math

def replace_nan(test_dict):
    if isinstance(test_dict, dict):
        for key in test_dict:
            if (isinstance(test_dict[key], float) and math.isnan(test_dict[key])):
                test_dict[key] = None
            else:
                replace_nan(test_dict[key])

    elif isinstance(test_dict, list):
        for val in test_dict:
            replace_nan(val)

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

awonw

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值