Python——numpy中的 sum 函数

import numpy as np

# 初始化二维数组
a = np.random.randn(4, 3)
# 数组普通相加,默认 axis=0
b = np.sum(a)
# 按行相加,不保持其二维特性
c = np.sum(a, axis=1)
# 按行相加,并且保持其二维特性
d = np.sum(a, axis=1, keepdims=True)
print('a:')
print(a)
print('b:')
print(b)
print('c:')
print(c)
print('d:')
print(d)

 

输出:

a:
[[ 0.71521185  0.670411   -0.22968195]
 [ 0.396861    1.26080256  0.30575231]
 [ 0.16985268 -0.01680635  0.84183202]
 [ 0.1024042  -2.30671794 -0.07339714]]
b:
1.8365242565860904
c:
[ 1.1559409   1.96341587  0.99487836 -2.27771088]
d:
[[ 1.1559409 ]
 [ 1.96341587]
 [ 0.99487836]
 [-2.27771088]]

 

posted @ 2020-09-22 10:38  yx啦啦啦  阅读(2146)  评论(0编辑  收藏  举报
……