首先,日常导包
import numpy as np
创建数组
第一种方式 -> np.array() 要求数组中数据类型必须全部一致
示例
a=np.array([1,2,3,4])
print(a)
示例结果:[1 2 3 4]
第二种方式 -> np.arange(a,b,c) 类似python中range,其中a,b为区间,c为步长
示例
b = np.arange(0,10,2)
print(b)
示例结果:[0 2 4 6 8]
第三种方式 -> np.random.random(a,b,size=(c,d)) 产生a~b随机数,并生成c*d数组
示例
c = np.random.randint(0,9,size=(4,4))
print(c)
示例结果:
[[1 6 1 8]
[4 8 7 3]
[2 2 6 2]
[2 3 1 6]]
第四种方式 -> np.zeros((2,2))#生成全为0的2*2数组
np.ones((2,2))#生成全为1的2*2数组
np.full((2,2),8)#生成一个2*2全为8的数组
np.eye(3)#生成一个对角线全为1,其他全为0的对称数组
示例
e = np.zeros((2,2))
f = np.ones((2,2))
g = np.full((2,2),8)
h = np.eye(3)
print(e)
print(f)
print(g)
print(h)
示例结果:
[[0. 0.]
[0. 0.]]
[[1. 1.]
[1. 1.]]
[[8 8]
[8 8]]
[[1. 0. 0.]
[0. 1. 0.]
[0. 0. 1.]]