python - np.mean(data.isnull()) 到底是什么?

标签 python python-3.x

在通过 Python 创建清洁项目时,我发现了以下代码:

# let's see if there is any missing data

for col in df.columns:
    pct_missing = np.mean(df[col].isnull())
    print('{} - {}%'.format(col, round(pct_missing,2)))

这实际上工作得很好,返回数据框中每列空值的百分比,但我对它的工作原理有点困惑:

首先,我们为数据帧中的每一列定义一个循环,然后我们执行该平均值,但确切的平均值是什么?每列的空单元格数量的平均值还是什么?

仅供引用,我已经解决了这个问题:

NullValues=df.isnull().sum()/len(df)
print('{} - {}%'.format(col, round(NullValues,2)))

这给了我基本相同的结果,但只是为了理解机制......我对第一段代码感到困惑......

最佳答案

一旦你习惯了它,它就会变得非常直观。生成此类代码的步骤可能如下所示:

  1. 要获取空值的百分比,我们需要计算所有空行的数量,并将计数除以总行数。
  2. 因此,首先我们需要检测空行。这很简单,因为提供了一个方法: df[col].isnull() .
  3. df[col].isnull() 的结果是一个由 bool 值组成的新列 -- TrueFalse .
  4. 现在我们需要计算True s。这里我们可以实现计数True bool 数组中的 s 与对数组求和相同:True可以转换为1,并且False归零。
  5. 所以我们将剩下 df[col].isnull().sum() / len(df[col]) .
  6. 但是求和除以长度只是算术平均值!因此,我们可以缩短它以获得最终结果: mean(df[col].isnull()) .

关于python - np.mean(data.isnull()) 到底是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/75109914/

相关文章:

python - 更新字典的键和值

python - Pytrends - 响应错误 : The request failed: Google returned a response with code 400

Python - 导入 tweepy ImportError : No module named tweepy

Python Mechanize 找不到链接

python - 列表中所有值的平均值 - 是否有更多 'Pythonic' 方法来执行此操作?

python - 如何迭代数据框列表并在未找到特定字符串时删除所有数据

python - 获取 NumPy 数组(或列表)的 "slices"长度而不实际切片

python - 如何在Python中从GITLAB读取csv文件(或任何文件)

python - TypeError : can't concat bytes to str时如何转换为字节

Python 脚本调用不同的 python 脚本,然后从辅助脚本将字符串/结果带到主脚本