python - 如果列值等于 NaN 或零,我该如何计算?
问题描述
我使用下面的代码来指示列中是否有任何缺失值 (NaN) 或零 (0.00)。
# Specifying the NaNs
num_nan_totals = df.loc[ (pd.isna(df['Totals'])) , 'Totals' ].shape[0]
# Specifying the zeros
num_zero_totals = df["Totals"] == 0.00
# For output
print(f"There are {num_nan_totals} NaNs in the totals column")
print(f"There are {num_zero_totals} zeros in the totals column")
我的输出:
There are 0 NaNs in the totals column
There are 433 False
434 False
435 False
436 False
# etc. etc. etc.
目视检查数据集后,应该至少有一个“0.00”实例,这就是我知道它出错的方式。我怀疑问题出在零定义上,任何人都可以给出任何提示吗?谢谢!
解决方案
您在构建面具方面走在了正确的轨道上。假设您只需要计数,则可以使用sum
pandas 中的方法。这里的信息:https ://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.sum.html
对于掩码,False 为 0,True 为 1,因此将所有值相加是获取所有真值计数的快速方法。
# Count of nan
num_nan_totals = df['Totals'].isna().sum()
# Count of 0
num_zero_totals = (df['Totals'] == 0.00).sum()
推荐阅读
- javascript - 是否可以创建使用 WebAudio API 来分析在没有 MP3 文件的情况下在浏览器中播放的声音?
- python - 制作从 1 到数字 n 的所有大小 k 的组合
- gitlab - GitLab Markdown 中的 Markdown 选项卡
- javascript - Javascript可以写在.edge文件中吗?
- .net - “IdentityType”中的“名称”是什么(System.DirectoryServices.AccountManagement)
- java - 在 oracle maf 中 IDCS 登录后如何检查 Java 中的 HTTP Basic 用户身份验证?
- reactjs - 反应表单动态输入字段
- php - 使用 Symfony 4 和 Doctrine 2 实现存档表
- firebase - 使用 Firebase 凭据访问谷歌云存储
- javascript - html 暂停画布游戏有效......但我的简历没有。为什么不?