【问题标题】:Missing Values: Why is isnull() not reporting NaN缺失值:为什么 isnull() 不报告 NaN
【发布时间】:2019-12-20 04:27:13
【问题描述】:

想知道NULL(我的意思是空单元格)是否与 python 中的NaN 或na 不同。我正在检查我的数据集关于缺失值的信息。但似乎 pandas 并未报告所有缺失值。

df2.isnull().any()
id          False
trip_id     False
distance    False
duration    False
speed       False
foot        False
bike        False
car         False
bus         False
metro       False
mode         True
dtype: bool

df2.isnull().any().sum()
1

但是,只是进一步检查,我注意到 2 个缺失值:

df2.head(10)
+---+-----------+---------+----------+----------+-------+-------+-------+-------+-------+-------+-------+
|   |    id     | trip_id | distance | duration | speed | foot  | bike  |  car  |  bus  | metro | mode  |
+---+-----------+---------+----------+----------+-------+-------+-------+-------+-------+-------+-------+
| 0 | 441814000 |  441814 | 10632.93 |     2076 | 5.12  | False | False | True  | False | False | car   |
| 1 | 442313000 |  442313 | 738.02   |     2075 | 0.36  | True  | False | False | False | False | foot  |
| 2 | 442795000 |  442795 | 5759.29  |     3879 | 1.48  | True  | False | False | False | False | NaN   |
| 3 | 441817000 |  441817 | 31110.93 |     2948 | 10.55 | False | False | True  | False | False | car   |
| 4 | 442316000 |  442316 | 49636.50 |     2971 | 16.71 | False | False | True  | False | False | car   |
| 5 | 441316000 |  441316 | 9736.87  |     3185 | 3.06  | True  | False | True  | False | False | car   |
| 6 | 441818000 |  441818 | 10027.53 |     1181 | 8.49  | False | False | True  | False | False | car   |
| 7 | 442798000 |  442798 | 1862.62  |     2039 | 0.91  | True  | False | False | False | False | foot  |
| 8 | 442318000 |  442318 | 39738.04 |     4468 | 8.89  | True  | False | False | False | True  | metro |
| 9 | 441318000 |  441318 | 18472.13 |     5670 | 3.26  | True  | False | False | False | False | NaN   |
+---+-----------+---------+----------+----------+-------+-------+-------+-------+-------+-------+-------+

我很奇怪为什么 isnull().any.sum() 只报告了一个 NaN

【问题讨论】:

  • 是NaN 字符串'NaN' 还是空值?
  • 因为您使用的是any。试试df2.isnull().sum().sum()
  • 你正在总结你发布的系列。

标签: python pandas dataframe


【解决方案1】:

对于您的情况,这是因为您使用的是.any(),如果任何值为NaN,您可能只想返回isnull().sum()

编辑:这将为您提供每列的计数,如果您想要一个总值,那么您可以像 ayhan 提到的那样做 isnull().sum().sum()

【讨论】:

  • 啊,没错,就是这样。
  • 不确定是否更好,但由于 numpy 的总和默认为展平,那么您可以这样做:df.isnull().values.sum() 而不是 df.isnull().sum().sum()
  • @JonClements 所以你的评论让我的兴趣达到了顶峰,所以我跑了一些时间看看它是否更快(我能想到的唯一衡量“更好”的方法),结果是 df .isnull().values.sum() 要快得多。每个循环 130 µs ± 932 ns,而 df.isnull().sum().sum() 为 374 µs ± 6.19 µs
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-08-06
  • 2014-05-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-06-23
  • 2014-06-09
相关资源
最近更新 更多