数组操作
更改形状
在对数组进行操作时,为了满足格式与计算的需要我们常常会改变数组的形状。
numpy.ndarray.shape
表示数组的维度,返回一个tuple,tuple的长度等于维数ndim
【例】通过修改 shape 属性来改变数组的形状。
import numpy as np
x = np.array([1, 2, 9, 4, 5, 6, 7, 8])
print(x.shape) # (8,)
x.shape = [2, 4]
print(x)
# [[1 2 9 4]
# [5 6 7 8]]
numpy.ndarray.flat
将数组转换为一维的迭代器,可以用for访问数组每一个元素。
【例】
import numpy as np
x = np.array([[11, 12, 13, 14, 15],
[16, 17, 18, 19, 20],
[21, 22, 23, 24, 25],
[26, 27, 28, 29, 30],
[31, 32, 33, 34, 35]])
y = x.flat
print(y)
# <numpy.flatiter object at 0x0000020F9BA10C60>
for i in y:
print(i, end=' ')
# 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35
y[3] = 0
print(end='\n')
print(x)
# [[11 12 13 0 15]
# [16 17 18 19 20]
# [21 22 23 24 25]
# [26 27 28 29 30]
# [31 32 33 34 35]]
numpy.ndarray.flatten([order='C'])
将数组的副本转换为一维数组,并返回。- order:‘C’ – 按行,‘F’ – 按列,‘A’ – 原顺序,‘k’ – 元素在内存中的出现顺序。(简记)
- order:{'C / F,'A,K},可选使用此索引顺序读取a的元素。'C’意味着以行大的C风格顺序对元素进行索引,最后一个轴索引会更改F表示以列大的Fortran样式顺序索引元素,其中第一个索引变化最快,最后一个索引变化最快。请注意,'C’和’F’选项不考虑基础数组的内存布局,仅引用轴索引的顺序.A’表示如果a为Fortran,则以类似Fortran的索引顺序读取元素在内存中连续,否则类似C的顺序。“ K”表示按照步序在内存中的顺序读取元素,但步幅为负时反转数据除外。默认情况下,使用Cindex顺序。
flatten()
返回的是拷贝。
numpy.ravel(a, order='C')
Return a contiguous flattened array.ravel()
返回的是视图;若order=F’则返回的是拷贝。
numpy.reshape(a, newshape[, order='C'])
在不更改数据的情况下为数组赋予新的形状。reshape()
函数当参数newshape = [rows,-1]
时,将根据行数自动确定列数。reshape()
函数当参数newshape = -1
时,表示将数组降为一维。reshape()
函数返回的也是视图。
数组转置
numpy.transpose(a, axes=None)
Permute the dimensions of an array.numpy.ndarray.T
Same asself.transpose()
, except that self is returned if self.ndim < 2.
更改维度
在创建数组之后,还可以给它增加或减少维度,只在矩阵计算中经常会用到。
numpy.newaxis = None
None
的别名,对索引数组很有用。
【例】很多工具包在进行计算时都会先判断输入数据的维度是否满足要求,如果输入数据达不到指定的维度时,可以使用newaxis
参数来增加一个维度。
import numpy as np
x = np.array([1, 2, 9, 4, 5, 6, 7, 8])
print(x.shape) # (8,)
print(x) # [1 2 9 4 5 6 7 8]
y = x[np.newaxis, :]
print(y.shape) # (1, 8)
print(y) # [[1 2 9 4 5 6 7 8]]
y = x[:, np.newaxis]
print(y.shape) # (8, 1)
print(y)
# [[1]
# [2]
# [9]
# [4]
# [5]
# [6]
# [7]
# [8]]
numpy.squeeze(a, axis=None)
从数组的形状中删除单维度条目,即把shape中为1的维度去掉。a
表示输入的数组;axis
用于指定需要删除的维度,但是指定的维度必须为单维度,否则将会报错;
【例】
import numpy as np
x = np.array([[[0], [1], [2]]])
print(x.shape) # (1, 3, 1)
print(x)
# [[[0]
# [1]
# [2]]]
y = np.squeeze(x)
print(y.shape) # (3,)
print(y) # [0 1 2]
y = np.squeeze(x, axis=0)
print(y.shape) # (3, 1)
print(y)
# [[0]
# [1]
# [2]]
y = np.squeeze(x, axis=2)
print(y.shape) # (1, 3)
print(y) # [[0 1 2]]
y = np.squeeze(x, axis=1)
# ValueError: cannot select an axis to squeeze out which has size not equal to one
在机器学习和深度学习中,通常算法的结果是可以表示向量的数组(即包含两对或以上的方括号形式[[]]),如果直接利用这个数组进行画图可能显示界面为空(见后面的示例)。我们可以利用squeeze()
函数将表示向量的数组转换为秩为1的数组,这样利用 matplotlib 库函数画图时,就可以正常的显示结果了。
数组组合
如果要将两个或多个数组拼在一起,就需要拼接操作。
numpy.concatenate((a1, a2, ...), axis=0, out=None)
Join a sequence of arrays along an existing axis.- 注意:除axis以外,其他维度必须完全相等
numpy.stack(arrays, axis=0, out=None)
Join a sequence of arrays along a new axis.numpy.vstack(tup)
Stack arrays in sequence vertically (row wise).numpy.hstack(tup)
Stack arrays in sequence horizontally (column wise).hstack()
,vstack()
分别表示水平和竖直的拼接方式。在数据维度等于1时,比较特殊。而当维度大于或等于2时,它们的作用相当于concatenate
,用于在已有轴上进行操作。
数组拆分
-
numpy.split(ary, indices_or_sections, axis=0)
Split an array into multiple sub-arrays as views into ary. -
numpy.vsplit(ary, indices_or_sections)
Split an array into multiple sub-arrays vertically (row-wise). -
numpy.hsplit(ary, indices_or_sections)
Split an array into multiple sub-arrays horizontally (column-wise).
数组平铺
-
numpy.tile(A, reps)
Construct an array by repeating A the number of times given by reps.tile
是瓷砖的意思,顾名思义,这个函数就是把数组像瓷砖一样铺展开来。- 可以理解为把原矩阵A当成新的元素构建新的矩阵
-
numpy.repeat(a, repeats, axis=None)
Repeat elements of an array.axis=0
,沿着y轴复制,实际上增加了行数。axis=1
,沿着x轴复制,实际上增加了列数。repeats
,可以为一个数,也可以为一个矩阵。axis=None
时就会flatten当前矩阵,实际上就是变成了一个行向量。
添加和删除元素
numpy.unique(ar, return_index=False, return_inverse=False,return_counts=False, axis=None)
Find the unique elements of an array.- return_index:the indices of the input array that give the unique values
- return_inverse:the indices of the unique array that reconstruct the input array
- return_counts:the number of times each unique value comes up in the input array