python-3.x - 获取 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 循环中的输出:
没有,因为所有字段都不为空/空白
解决方案
您可以使用此代码段获取具有空值的索引列表:
每列
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']
推荐阅读
- javascript - `TypeError`:`checkbox` 在尝试添加事件监听器时为 `null`
- html - 相对位置导致问题我的容器在陈列柜下为什么会发生?
- python - 将 pandasql 或 sqltopandas 安装到 Spyder 4.0
- vue.js - 使用 nuxt/apollo 和 github API 时出现 401
- php - 由于 php 扩展,带有 laravel 的 Docker 失败
- connection-string - 如何使用 Splunk DB connect 获取 2 个 DB 的 sql 输出?
- java - Java 中的泛型 - 通配符用例
- python - 尝试在 powershell/cmd 提示符中打开 .py 文件时出现语法错误
- python - 每秒刷新一次值 Tkinter
- android - 如何在没有 activity_main.xml 文件的情况下将 admob 广告放置到应用程序