You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何合并df.isnull().sum()与(df==0).sum()获取NaN和0值统计?

Combine NaN and Zero Counts in a Pandas DataFrame

Got it, let's work through this problem together. You want to calculate the total number of zeros and NaN values per column in your DataFrame, right? Here's a clean, efficient way to do it in one line:

First, let's recap your sample DataFrame for context:

import pandas as pd
import numpy as np

df = pd.DataFrame({'a':[1,0,0,1,3], 'b':[0,np.nan,1,np.nan,1], 'c':[0,0,0,0,np.nan]})

To get the combined count of zeros and NaNs per column, use this code:

combined_counts = ((df == 0) | df.isnull()).sum()

Running this will give you exactly the result you're looking for:

a    2
b    3
c    5
dtype: int64

How this works:

  • df == 0 creates a boolean DataFrame where every cell is True if the value is 0 (this works for both integer 0 and float 0.0, since pandas treats them as equal).
  • df.isnull() creates another boolean DataFrame that marks all NaN positions.
  • The | operator combines these two masks with a logical OR, so any cell that's either 0 or NaN becomes True.
  • Finally, .sum() adds up all the True values per column (pandas treats True as 1 and False as 0 when summing, so we get the total count directly).

As an alternative, you could also calculate the two sums separately and add them together: df.isnull().sum() + (df == 0).sum()—but the single mask method is more concise and readable.

内容的提问来源于stack exchange,提问作者stomar02

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 10:01:57