Python中的NumPy(三)——阵列数学(Array Math)

版权声明:本文版权归作者所有,未经允许不得转载! https://blog.csdn.net/m0_37827994/article/details/86494777

阵列数学

1、基础数学

# Basic math
x = np.array([[1,2], [3,4]], dtype=np.float64)
y = np.array([[1,2], [3,4]], dtype=np.float64)
print("x:\n",x)
print("y:\n",y)
print ("x + y:\n", np.add(x, y)) # or x + y
print ("x - y:\n", np.subtract(x, y)) # or x - y
print ("x * y:\n", np.multiply(x, y)) # or x * y

输出结果:

x:
 [[1. 2.]
 [3. 4.]]
y:
 [[1. 2.]
 [3. 4.]]
x + y:
 [[2. 4.]
 [6. 8.]]
x - y:
 [[0. 0.]
 [0. 0.]]
x * y:
 [[ 1.  4.]
 [ 9. 16.]]
  • 注:这里的乘法各自位置上的数字相乘*

2、点乘

在这里插入图片描述

# Dot product
a = np.array([[1,2,3], [4,5,6]], dtype=np.float64) # we can specify dtype
b = np.array([[7,8], [9,10], [11, 12]], dtype=np.float64)
print("a:\n",a)
print("b:\n",b)
print (a.dot(b))

输出结果:

[[ 58.  64.]
 [139. 154.]]

3、维度和

# Sum across a dimension
x = np.array([[1,2],[3,4]])
print (x)
print ("sum all: ", np.sum(x)) # adds all elements
print ("sum by col: ", np.sum(x, axis=0)) # add numbers in each column
print ("sum by row: ", np.sum(x, axis=1)) # add numbers in each row

输出结果:

[[1 2]
 [3 4]]
sum all:  10
sum by col:  [4 6]
sum by row:  [3 7]

4、转置

# Transposing
x = np.array([[1,2],[3,4]])
print ("x:\n", x)
print ("x.T:\n", x.T)

输出结果:

x:
 [[1 2]
 [3 4]]
x.T:
 [[1 3]
 [2 4]]

猜你喜欢

转载自blog.csdn.net/m0_37827994/article/details/86494777