首页 > 解决方案 > 获取 Pandas Dataframe 中具有 Null/Blank 值的行号和列名的索引

问题描述

我有一个 Pandas 数据框,我需要在其中遍历 for 循环,看看哪个是行号,以及该行中具有空白/空值的列名(不是列值)是什么。然后将该行号和列名存储在两个单独的变量(Row_Number 和 Column_Names)中具有空白/空值的行中。通过循环的原因是我想逐行记录空行,这些空行将以 JSON 形式发送到 HTTP Post 请求。最终应用程序只收到 JSON 格式。

ID 姓名 部门 邮政编码
100 金融 173212
233 亚历克斯
344 卢瑟 销售量 173453

第一次迭代的 for 循环中的输出:

Row_Number = 1  
Column Names = [Name]

第 2 次迭代的 for 循环输出:

Row_Number = 2  
Column Names = [Dept, Zipcode]

第 3 次迭代的 for 循环中的输出:
没有,因为所有字段都不为空/空白

标签: python-3.xpandasdataframe

解决方案


您可以使用此代码段获取具有空值的索引列表:

每列

nulls = df.isnull()
(nulls.mul(df.index.values, axis=0)
      .where(nulls)
      .apply(lambda x: x.dropna().astype(int).unique())
)

输出:

ID          []
Name       [0]
Dept       [1]
Zipcode    [1]

每行:

nulls = df.isnull()
(nulls.mul(df.columns, axis=1)
      .where(nulls)
      .apply(lambda x: x.dropna().unique(), axis=1)
)

输出:

0             [Name ]
1    [Dept , Zipcode]
2                  []

编辑:使用 iterrows:

for idx, r in df.iterrows():
    nulls = list(r[r.isnull()].index)
    if nulls:
        print(f'row {idx}: those columns are null:', nulls)

输出:

row 0: those columns are null: ['Name ']
row 1: those columns are null: ['Dept ', 'Zipcode']

推荐阅读