當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


Python numpy.cumsum()用法及代碼示例

numpy.cumsum()函數用於計算給定軸上數組元素的累積和。

用法: numpy.cumsum(arr, axis=None, dtype=None, out=None)

參數:
arr :[數組]包含需要累積總和的數字的數組。如果arr不是數組,則嘗試進行轉換。
axis :計算累計和的軸。默認值是計算展平數組的總和。
dtype :返回數組的類型,以及與元素相乘的累加器的類型。如果未指定dtype,則默認為arr的dtype,除非arr的整數dtype的精度小於默認平台整數的精度。在這種情況下,將使用默認平台整數。
out :[ndarray,可選]將結果存儲到的位置。
->如果提供,則必須具有廣播輸入的形狀。
->如果未提供或沒有,則返回新分配的數組。


Return :除非指定out,否則將返回保存結果的新數組,在這種情況下將返回該數組。

代碼1:工作

# Python program explaining 
# numpy.cumsum() function 
import numpy as geek 
  
in_num = 10
  
print ("Input  number:", in_num) 
    
out_sum = geek.cumsum(in_num)  
print ("cumulative sum of input number:", out_sum) 

輸出:

Input  number: 10
cumulative sum of input number: [10]


代碼2:

# Python program explaining 
# numpy.cumsum() function 
  
import numpy as geek 
  
in_arr = geek.array([[2, 4, 6], [1, 3, 5]]) 
   
print ("Input array:", in_arr)  
    
out_sum = geek.cumsum(in_arr)  
print ("cumulative sum of array elements:", out_sum) 

輸出:

Input array: [[2 4 6]
 [1 3 5]]
cumulative sum of array elements: [ 2  6 12 13 16 21]


代碼3:

# Python program explaining 
# numpy.cumsum() function 
  
import numpy as geek 
  
in_arr = geek.array([[2, 4, 6], [1, 3, 5]]) 
   
print ("Input array:", in_arr)  
    
out_sum = geek.cumsum(in_arr, axis = 1)  
print ("cumulative sum of array elements taking axis 1:", out_sum) 

輸出:

Input array: [[2 4 6]
 [1 3 5]]
cumulative sum of array elements taking axis 1: [[ 2  6 12]
 [ 1  4  9]]


相關用法


注:本文由純淨天空篩選整理自jana_sayantan大神的英文原創作品 numpy.cumsum() in Python。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。