Pandas Series: sum()方法


 

sum()函數用於獲取所請求軸的值之和。

這等效於numpy.sum方法。

句法

The sum() function is used to getg the sum of the values for the requested axis.

This is equivalent to the method numpy.sum.

Syntax:

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

Pandas Series sum image

Parameters:

Name Description Type/Default Value Required / Optional
axis 要應用的功能的軸。 {index (0)} Required
skipna 計算結果時排除NA / null值。 bool
Default Value: True
Required
level 如果軸是MultiIndex(分層),則沿特定級別計數,並折疊成標量。 int or level name
Default Value: None
Required
numeric_only 僅包括float,int,boolean列。 如果為None,將嘗試使用所有內容,然后僅使用數字數據。 未針對系列實施。 bool
Default Value: None
Required
min_count

執行操作所需的有效值數量。 如果存在少於min_count個非NA值,則結果將為NA。
0.22.0版中的新增功能:添加了默認值0。這表示全NA或空系列的總和為0,全NA或空系列的乘積為1。

int
Default Value: 0
Required
**kwargs 要傳遞給函數的其他關鍵字參數。   Required

Returns: scalar or Series (if level specified)

Example:

Examples

In [1]:
import numpy as np import pandas as pd 
In [2]:
idx = pd.MultiIndex.from_arrays([ ['warm', 'warm', 'cold', 'cold'], ['fox', 'cat', 'snake', 'spider']], names=['blooded', 'animal']) 
In [3]:
s = pd.Series([4, 4, 0, 8], name='legs', index=idx) s 
Out[3]:
blooded  animal
warm     fox       4
         cat       4
cold     snake     0
         spider    8
Name: legs, dtype: int64
 

In [4]:
s.sum() 
Out[4]:
16
 

Sum using level names, as well as indices.

In [5]:
s.sum(level='blooded') 
Out[5]:
blooded
warm    8
cold    8
Name: legs, dtype: int64
 

默認情況下,空系列或全NA系列的總和為0。

In [6]:
pd.Series([]).sum() # min_count=0 is the default 
Out[6]:
0.0
 

可以使用min_count參數進行控制。 例如,如果您想要一個空值的總和
系列為NaN,傳遞min_count = 1。

In [7]:
pd.Series([]).sum(min_count=1) 
Out[7]:
nan
 多虧了skipna參數,min_count可以完全處理all-NA和空序列。
In [8]:
pd.Series([np.nan]).sum() 
Out[8]:
0.0
In [9]:
pd.Series([np.nan]).sum(min_count=1) 
Out[9]:
nan


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM