import numpy as np
# 一维数组
n1=np.array([1,5,3,4,5,6],dtype="float32")
print(n1)
# 二维数组
n2=np.array([[1,2,3],[4,5,6],[7,8,9]])
print(n2)
[1. 5. 3. 4. 5. 6.]
[[1 2 3]
[4 5 6]
[7 8 9]]
np.arange(1,9,3)
import numpy as np
# 创建一个 3x3 的单位矩阵
matrix = np.eye(3)
# 输出单位矩阵
print(matrix)
执行结果:
[[1. 0. 0.]
[0. 1. 0.]
[0. 0. 1.]]
print(n2+3)
[[ 4 5 6]
[ 7 8 9]
[10 11 12]]
import numpy as np
A = np.array([[1, 2], [3, 4]]) # 创建一个 2x2 的矩阵 A
B = np.array([[5, 6], [7, 8]]) # 创建一个 2x2 的矩阵 B
A_transpose = A.T
A_transpose
array([[1, 3],
[2, 4]])
import numpy as np
# 定义两个矩阵 A 和 B
A = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
B = np.array([[9, 8, 7], [6, 5, 4], [3, 2, 1]])
# 计算矩阵乘法
dot_product = np.dot(A, B)
# 输出结果
print(dot_product)
输出结果为:
[ 58 42 29]
[139 99 63]
[203 142 105]
import numpy as np
a = np.array([[1, 2, 3], [4, 5, 6]]) # 2x3 的数组
b = np.array([1, 2, 3]) # 1x3 的数组
result = a + b # 广播运算
print(result)
执行结果:
[[2 4 6]
[5 7 9]]
import numpy as np
x=np.random.randint(100,size=(5,5))
print(x)
print(x>60)
print(np.sum(x>60))
[[68 53 32 27 41]
[87 49 21 48 32]
[16 31 64 72 34]
[18 63 65 55 10]
[93 47 66 18 73]]
[[ True False False False False]
[ True False False False False]
[False False True True False]
[False True True False False]
[ True False True False True]]
9
x[x>60]
array([68, 87, 64, 72, 63, 65, 93, 66, 73])