1. 通过array
函数创建多维数组
- 创建一维数组
a = np.array([1,2,3,4])
print(a)
[1 2 3 4]
- 创建二维数组
b = np.array([[1,2,3],[4,5,6],[3,2,1]])
print(b)
[[1 2 3]
[4 5 6]
[3 2 1]]
2. 数组对象常用的属性(维度、形状、元素个数、元素字节数)
以下面的二维数组为例:
b = np.array([[1,2,3],[4,5,6],[3,2,1]])
print(b)
[[1 2 3]
[4 5 6]
[3 2 1]]
- 通过
ndim
属性,查看数组的维度
dim = b.ndim
print("b数组的维度是:", dim)
b数组的维度是: 2
- 通过
shape
属性,查看数组的形状
shape = b.shape
print("b数组的形状是:", shape)
b数组的形状是: (3, 3)
- 通过
size
属性,查看数组的元素个数
size = b.size
print("b数组的元素个数是:", size)
b数组的元素个数是:9
- 通过
dtype
属性,查看数组的元素字节数
dtype = b.dtype
print("b数组的元素字节数是:", dtype)
3. 创建特殊数组
- 通过
np.arange(start, end, step)
创建一个范围数组
c = np.arange(1, 10, 2)
print(c)
array([1, 3, 5, 7, 9])
- 通过
np.ones((shape))
创建一个元素全是1的数组
d = np.ones((3,4))
array([[1., 1., 1., 1.],
[1., 1., 1., 1.],
[1., 1., 1., 1.]])
- 通过
np.zeros((shape))
创建一个元素全是0的数组
d = np.zeros((4,5))
array([[0, 0, 0, 0, 0],
[0, 0, 0, 0, 0],
[0, 0, 0, 0, 0],
[0, 0, 0, 0, 0]])
- 通过
np.eye()
创建一个对角线为1,其余为0的数组
f = np.eye(3)
array([[1., 0., 0.],
[0., 1., 0.],
[0., 0., 1.]])
4. 通过reshape和resize改变已经创建的数组形状
reshape会创建一个新的数组;resize则是直接在原数组上修改。
以下面的这个一维数组为例:
arr = np.arange(0, 20, 2)
print(arr)
[ 0 2 4 6 8 10 12 14 16 18]
- 通过
reshape
修改,在实际使用过程中需要结合赋值语句,将修改后的数组保存。
newarr = arr.reshape(2,5)
print(newarr)
array([[ 0, 2, 4, 6, 8],
[10, 12, 14, 16, 18]])
- 通过
resize
修改,直接在原数组上修改,不需要结合赋值语句。
arr.resize(2,5)
print(arr)
array([[ 0, 2, 4, 6, 8],
[10, 12, 14, 16, 18]])
5. Numpy的随机模块——numpy.random
np.random.rand(d0,d1,…,dn) 元素在[0,1)区间均匀分布的数组 浮点数
np.random.uniform(low, hige, size) 元素在[low, hige)区间均匀分布的数组 浮点数
np.random.randint(low, hige, size) 元素在[low, hige)区间均匀分布的数组 整数
np.random.randn(d0,d1,…,dn) 产生标准正泰分布的数组 浮点数
np.random,normal(loc, scale, size) 产生正态分布的数组 浮点数
np.random.seed(shuzi) 设置随机种子,仅一次有效
np.random.shuffle(序列) 打乱顺序函数(可以是列表或numpy数组)。如果是np,只打乱第一维。所以,如果是minist这样的数据集,可以将图片顺序打乱,而不会改变每张图片数据。
- 例如创建一个数值在1至255之间的整数,28x28的二维矩阵
arr = np.random.randint(1,256, (28,28))
通过matplotlib显示这个矩阵图像:
import matplotlib.pyplot as plt
plt.imshow(arr)
plt.show()