np.sum()

np.sum(a, axis=None, dtype=None, out=None, keepdims=np._NoValue)

参数:

  • a:用于进行加法运算的数组形式的元素。

  • axis\(axis\) 的取值有三种情况:1.\(None\),2.整数, 3.整数元组。(在默认/缺省的情况下,\(axis\)\(None\)

  • dtype:改变元素的类型后相加。

  • keepdims:是否保持维数,默认是 \(False\)

实例:

import numpy as np

a = np.linspace(1,20,20).reshape(4,5)
print(a)
[[ 1.  2.  3.  4.  5.]
 [ 6.  7.  8.  9. 10.]
 [11. 12. 13. 14. 15.]
 [16. 17. 18. 19. 20.]]


axis

b = np.sum(a)
c = np.sum(a,axis = 0)		# 压缩行
d = np.sum(a,axis = 1)		# 压缩列
print(b)
print(c)
print(d)
210.0
[34. 38. 42. 46. 50.]
[15. 40. 65. 90.]
import numpy as np
x = np.array([
              [
                  [1, 5, 5, 2],
                  [9, -6, 2, 8],
                  [-3, 7, -9, 1]
              ],

              [
                  [-1, 5, -5, 2],
                  [9, 6, 2, 8],
                  [3, 7, 9, 1]
              ]
            ])
print(np.sum(x, axis=0))
[[ 0 10  0  4]
 [18  0  4 16]
 [ 0 14  0  2]]

np.sum(x, axis=0)的含义是 \(x[0][j][k], x[1][j][k] (j=0,1,2,k=0,1,2,3)\) 中对应项相加的结果。

\([[1, 5, 5, 2],[9, -6, 2, 8],[-3, 7, -9, 1]]+[[-1, 5, -5, 2],[9, 6, 2, 8],[3, 7, 9, 1]]=[[0,10,0,4],[18,0,4,16],[0,14,0,2]]\)

\(axis=1,axis=2\) 的道理是类似的。



dtype

e = np.sum([0.5, 0.7, 1.2, 1.5], dtype=np.int32)
f = np.sum([0.5, 0.7, 1.2, 1.5], dtype=np.float32)
print(e)
print(f)
2
3.9


keepdims

m = np.sum(a, axis=0)
print(m.shape)
n = np.sum(a, axis=0, keepdims=True)		# keepdims =True 保持a的维度
print(n.shape)
(5,)
(1, 5)


posted @ 2022-08-24 11:28  做梦当财神  阅读(481)  评论(0编辑  收藏  举报