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

使用Python移除字典与列表中nan值,work类电话全nan时删除整字典

报错原因

你的代码存在两个核心问题直接触发了报错:

  1. 语法逻辑错误:直接将字典当做可按整数索引的列表遍历,dic[i]的写法对字典结构本身不生效,且你没有提前定义key、value变量,导致pd.isna()实际接收到的是不符合预期的对象
  2. 判断逻辑错误:你直接将pd.isna()作用在了列表类型的对象上,返回的是布尔值数组,无法直接用if做单真值判断

解决方案

以下代码可直接实现你的需求,既可以移除所有嵌套结构中的nan,也满足work类型Phone全为nan时删除整个条目的规则:

import pandas as pd
import numpy as np

# 输入数据
nan = np.nan
dic = {
    'Customer_Number': 12345, 
    'Email': [{'Email_Type': 'Primary', 'Email': ['sa@ru.edu', nan]}],
    'Phone_Number': [
        {'Phone_Type': 'Mobile', 'Phone': [1217]}, 
        {'Phone_Type': 'work', 'Phone': [nan]}
    ]
}

# 处理Email字段,过滤列表中nan
for email_entry in dic["Email"]:
    email_entry["Email"] = [val for val in email_entry["Email"] if not pd.isna(val)]

# 处理Phone字段,同时应用特殊过滤规则
processed_phone = []
for phone_entry in dic["Phone_Number"]:
    # 先清理Phone列表中的nan
    cleaned_phone = [val for val in phone_entry["Phone"] if not pd.isna(val)]
    # 符合删除规则的条目直接跳过,不加入结果
    if phone_entry["Phone_Type"] == "work" and len(cleaned_phone) == 0:
        continue
    phone_entry["Phone"] = cleaned_phone
    processed_phone.append(phone_entry)
dic["Phone_Number"] = processed_phone

# 输出结果
print(dic)

运行后输出结果和你要求的一致(注:你期望结果中Email地址的拼写变更属于输入笔误,代码保留原始有效地址)。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 03:36:07