Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
520 views
in Technique[技术] by (71.8m points)

python - Sum across all NaNs in pandas returns zero?

I'm trying to sum across columns of a Pandas dataframe, and when I have NaNs in every column I'm getting sum = zero; I'd expected sum = NaN based on the docs. Here's what I've got:

In [136]: df = pd.DataFrame()

In [137]: df['a'] = [1,2,np.nan,3]

In [138]: df['b'] = [4,5,np.nan,6]

In [139]: df
Out[139]: 
    a   b
0   1   4
1   2   5
2 NaN NaN
3   3   6

In [140]: df['total'] = df.sum(axis=1)

In [141]: df
Out[141]: 
    a   b  total
0   1   4      5
1   2   5      7
2 NaN NaN      0
3   3   6      9

The pandas.DataFrame.sum docs say "If an entire row/column is NA, the result will be NA", so I don't understand why "total" = 0 and not NaN for index 2. What am I missing?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

pandas documentation ? API Reference ? DataFrame ? pandas.DataFrame ?

DataFrame.sum(self, axis=None, skipna=None, level=None, numeric_only=None, min_count=0, **kwargs)

min_count: int, default 0

The required number of valid values to perform the operation. If fewer than min_count non-NA values are present the result will be NA.

New in version 0.22.0: Added with the default being 0. This means the sum of an all-NA or empty Series is 0, and the product of an all-NA or empty Series is 1.

Quoting from pandas latest docs it says the min_count will be 0 for the all-NA series.

If you say min_count=1 then the result of the sum will be a NaN.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...