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

如何查看DataFrame中缺失值的索引或关联值?附代码问题排查

问题排查与解决方法

原代码的问题

  • surveydf.isnull()返回的是整个DataFrame的布尔值矩阵,不是单个元素的缺失状态,用surveydf.isnull() is True永远不会成立,逻辑完全错误
  • 循环遍历surveydf['email_address']的元素,但判断时没用到当前元素i,而是去判断整个DataFrame的缺失情况,逻辑不匹配
  • 就算判断成功,print(surveydf['first_name'])会打印整个first_name列,而不是缺失值对应的单行数据

正确实现方式

方法1:用Pandas向量操作(推荐,效率更高)

不需要手动循环,直接筛选出email_address为空的行,获取索引和对应的first_name:

import pandas as pd

# 获取缺失email对应的first_name和索引
missing_data = surveydf[surveydf['email_address'].isnull()][['first_name']]
print(missing_data)

# 如果只需要索引
missing_indices = surveydf[surveydf['email_address'].isnull()].index
print(missing_indices)

# 如果只需要first_name列表
missing_first_names = surveydf.loc[surveydf['email_address'].isnull(), 'first_name'].tolist()
print(missing_first_names)

方法2:手动循环(仅作演示,不推荐)

如果一定要用循环遍历,需要结合索引来判断每行的状态:

import pandas as pd

# 遍历每行的索引和email_address值
for idx, email in surveydf['email_address'].items():
    if pd.isnull(email):
        # 打印索引和对应的first_name
        print(f"索引{idx}对应的first_name: {surveydf.loc[idx, 'first_name']}")

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.17 07:52:01