如何合并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 == 0creates a boolean DataFrame where every cell isTrueif 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 becomesTrue. - Finally,
.sum()adds up all theTruevalues per column (pandas treatsTrueas 1 andFalseas 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
相关产品推荐
相关产品推荐

