1. 程式人生 > >【numpy求和】numpy.sum()求和

【numpy求和】numpy.sum()求和

numpy.sum(a, axis=None, dtype=None, out=None, keepdims=, initial=)[source])用於計算array元素的和.

python中常用的numpy進行數學計算,其中array的求和運算分為兩種,一種是呼叫numpy.array自身的sum()方法,另一種是利用numpy的內建函式numpy.sum()使用。(tips:python從0開始計數axis=0對應第一個維度)

#example
import numpy as np
x = np.random.rand(2,3,4)    #生成三維隨array
print("This is a 2*3rows 4cols array\n",x) ''' >>> This is a 2*3rows 4cols array [[[ 0.88264952 0.12446208 0.82166137 0.31747846] [ 0.51436626 0.03051283 0.46987831 0.64086531] [ 0.14819094 0.6395191 0.21753309 0.61340538]] [[ 0.0878878 0.5317064 0.65523138 0.704961 ] [ 0.51081521 0.88710145 0.92958269 0.89587262] [ 0.60233393 0.26146419 0.26584161 0.0823285 ]]] '''
print('instance method:',x.sum()) print('numpy function:',np.sum(x)) ''' >>> 'instance method:', 11.835649415181807 >>> 'numpy function:', 11.835649415181807 ''' #對特定的軸求和 print('First axis sum',x.sum(axis=0)) ''' >>> 'First axis sum', #第一維是軸0,對前後兩頁array加和得到3*4的array輸出 array([[ 0.97053732, 0.65616848, 1.47689275, 1.02243946], [ 1.02518147, 0.91761428, 1.399461 , 1.53673793], [ 0.75052486, 0.90098329, 0.4833747 , 0.69573388]]) '''
print('Second axis sum',x.sum(axis=1)) ''' >>> 'Second axis sum', #第二維是軸1,將每列的三行進行sum(對行求sum),得到2*4的輸出 array([[ 1.54520672, 0.79449401, 1.50907277, 1.57174914], [ 1.20103694, 1.68027204, 1.85065568, 1.68316212]]) ''' print('Third axis sum',x.sum(axis=2)) ''' >>> 'Third axis sum', #第三維是軸2,有4個數,將每行四個數加和(對列求sum),得到2*3輸出 array([[ 2.14625142, 1.65562271, 1.6186485 ], [ 1.97978658, 3.22337197, 1.21196823]]) ''' #對多個軸求和 print('axis1,2 sum:',x.sum(axis=(1,2))) ''' >>> 'axis1,2 sum: #對第二維(axis=1)和第三維(axis=2)求和,歸在第一維(axis=0)上 array([ 5.42052263, 6.41512678]) '''

在這裡插入圖片描述pic from pexels


ref:
https://docs.scipy.org/doc/numpy/reference/generated/numpy.ndarray.sum.html
https://docs.scipy.org/doc/numpy/reference/generated/numpy.sum.html
https://blog.csdn.net/Leekingsen/article/details/76242244
https://blog.csdn.net/addmana/article/details/78472608