python中的numpy.sum()用法详细介绍

2021年3月15日09:00:44 发表评论 2,397 次浏览

numpy.sum(arr, axis, dtype, out):此函数返回指定轴上的数组元素的总和

参数:arr:输入数组。 axis:我们要沿其计算总和值的轴。否则, 它将认为arr是平坦的(在所有轴上均有效)。 axis = 0表示沿列, 而axis = 1表示沿行。 out:要在其中放置结果的另一个数组。数组必须具有与预期输出相同的尺寸。默认为无。 initial:[标量, 可选]和的起始值。返回值:数组元素的总和(如果轴不存在, 则为标量值)或具有沿指定轴的总和的数组。

代码1:

# Python Program illustrating 
# numpy.sum() method
import numpy as np 
       
# 1D array 
arr = [ 20 , 2 , . 2 , 10 , 4 ]  
   
print ( "\nSum of arr : " , np. sum (arr)) 
   
print ( "Sum of arr(uint8) : " , np. sum (arr, dtype = np.uint8)) 
print ( "Sum of arr(float32) : " , np. sum (arr, dtype = np.float32))
   
print ( "\nIs np.sum(arr).dtype == np.uint : " , np. sum (arr).dtype = = np.uint) 
  
print ( "Is np.sum(arr).dtype == np.float : " , np. sum (arr).dtype = = np. float )

输出如下:

Sum of arr :  36.2
Sum of arr(uint8) :  36
Sum of arr(float32) :  36.2

Is np.sum(arr).dtype == np.uint :  False
Is np.sum(arr).dtype == np.uint :  True

代码2:

# Python Program illustrating 
# numpy.sum() method
import numpy as np 
       
# 2D array 
arr = [[ 14 , 17 , 12 , 33 , 44 ], [ 15 , 6 , 27 , 8 , 19 ], [ 23 , 2 , 54 , 1 , 4 , ]]  
   
print ( "\nSum of arr : " , np. sum (arr)) 
   
print ( "Sum of arr(uint8) : " , np. sum (arr, dtype = np.uint8)) 
print ( "Sum of arr(float32) : " , np. sum (arr, dtype = np.float32))
   
print ( "\nIs np.sum(arr).dtype == np.uint : " , np. sum (arr).dtype = = np.uint) 
  
print ( "Is np.sum(arr).dtype == np.uint : " , np. sum (arr).dtype = = np. float )

输出如下:

Sum of arr :  279
Sum of arr(uint8) :  23
Sum of arr(float32) :  279.0

Is np.sum(arr).dtype == np.uint :  False
Is np.sum(arr).dtype == np.uint :  False

代码3:

# Python Program illustrating 
# numpy.sum() method 
       
import numpy as np 
       
# 2D array  
arr = [[ 14 , 17 , 12 , 33 , 44 ], [ 15 , 6 , 27 , 8 , 19 ], [ 23 , 2 , 54 , 1 , 4 , ]]  
   
print ( "\nSum of arr : " , np. sum (arr)) 
print ( "Sum of arr(axis = 0) : " , np. sum (arr, axis = 0 )) 
print ( "Sum of arr(axis = 1) : " , np. sum (arr, axis = 1 ))
  
print ( "\nSum of arr (keepdimension is True): \n" , np. sum (arr, axis = 1 , keepdims = True ))

输出如下:

Sum of arr :  279
Sum of arr(axis = 0) :  [52 25 93 42 67]
Sum of arr(axis = 1) :  [120  75  84]

Sum of arr (keepdimension is True): 
 [[120]
 [ 75]
 [ 84]]

首先, 你的面试准备可通过以下方式增强你的数据结构概念:Python DS课程。


木子山

发表评论

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: