数组操作
数组操作.png更改形状
通过修改shape属性改变数组形状
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]]
flat方法将数组转换为一维的迭代器
x = np.arange(12).reshape(3, 4)
x
array([[ 0, 1, 2, 3],
[ 4, 5, 6, 7],
[ 8, 9, 10, 11]])
y = x.flat
print(y)
for i in y:
print(i, end=' ')
<numpy.flatiter object at 0x00000257A2BE29E0>
0 1 2 3 4 5 6 7 8 9 10 11
print(x)
[[ 0 1 2 3]
[ 4 5 6 7]
[ 8 9 10 11]]
flatten方法将数组的副本转换为一维数组
x
array([[ 0, 1, 2, 3],
[ 4, 5, 6, 7],
[ 8, 9, 10, 11]])
y = x.flatten()
print(y)
print(x)
[ 0 1 2 3 4 5 6 7 8 9 10 11]
[[ 0 1 2 3]
[ 4 5 6 7]
[ 8 9 10 11]]
ravel方法返回的是多维数组展平后的视图
x
array([[ 0, 1, 2, 3],
[ 4, 5, 6, 7],
[ 8, 9, 10, 11]])
y = np.ravel(x)
print(y)
[ 0 1 2 3 4 5 6 7 8 9 10 11]
y[3] = 5
print(x)
[[ 0 1 2 5]
[ 4 5 6 7]
[ 8 9 10 11]]
reshape方法也可以跟更改shape属性一样改变数组形状
x = np.arange(12).reshape(3, -1)
x
array([[ 0, 1, 2, 3],
[ 4, 5, 6, 7],
[ 8, 9, 10, 11]])
数组转置
x
array([[ 0, 1, 2, 3],
[ 4, 5, 6, 7],
[ 8, 9, 10, 11]])
x.T
array([[ 0, 4, 8],
[ 1, 5, 9],
[ 2, 6, 10],
[ 3, 7, 11]])
x.transpose()
array([[ 0, 4, 8],
[ 1, 5, 9],
[ 2, 6, 10],
[ 3, 7, 11]])
更改维度
np.newaxis增加一个维度
x = np.array([1, 2, 9, 4, 5, 6, 7, 8])
print(x.shape)
print(x)
(8,)
[1 2 9 4 5 6 7 8]
y = x[np.newaxis, :]
print(y.shape)
print(y)
(1, 8)
[[1 2 9 4 5 6 7 8]]
np.squeeze函数可以通过删除单维度的条目来降低数组一个维度
print(y, y.ndim)
[[1 2 9 4 5 6 7 8]] 2
z = np.squeeze(y)
print(z.shape)
(8,)
数组合并
np.concatenate
x = np.array([1, 2, 3])
y = np.array([7, 8, 9])
z = np.concatenate([x, y])
print(z)
[1 2 3 7 8 9]
z = np.concatenate([x, y], axis=0)
z
array([1, 2, 3, 7, 8, 9])
np.vstack
a = np.vstack([x, y])
a
array([[1, 2, 3],
[7, 8, 9]])
a = np.vstack(a*3)
a
array([[ 3, 6, 9],
[21, 24, 27]])
np.hstack
a = np.hstack([x, y])
a
array([1, 2, 3, 7, 8, 9])
数组分割
np.split
x = np.array([[11, 12, 13, 14],
[16, 17, 18, 19],
[21, 22, 23, 24]])
y = np.vsplit(x, 3)
print(y)
[array([[11, 12, 13, 14]]), array([[16, 17, 18, 19]]), array([[21, 22, 23, 24]])]
np.vsplit
y = np.vsplit(x, [1])
print(y)
[array([[11, 12, 13, 14]]), array([[16, 17, 18, 19],
[21, 22, 23, 24]])]
np.hsplit
x = np.array([[11, 12, 13, 14],
[16, 17, 18, 19],
[21, 22, 23, 24]])
y = np.hsplit(x, 2)
print(y)
[array([[11, 12],
[16, 17],
[21, 22]]), array([[13, 14],
[18, 19],
[23, 24]])]
数组平铺
np.tile
a = np.arange(6).reshape(2, -1)
np.tile(a, (2, 1)) # 在行方向上堆叠2次,列方向上堆叠1次
array([[0, 1, 2],
[3, 4, 5],
[0, 1, 2],
[3, 4, 5]])
np.repeat
a = np.array([1, 2, 3])
np.repeat(a, 3) # 将数组 a 的每个元素重复3次
array([1, 1, 1, 2, 2, 2, 3, 3, 3])
数组去重
a = np.array([2, 1, 3, 3, 4, 1, 2])
np.unique(a) # 计算数组a中的唯一值,并排序
array([1, 2, 3, 4])
网友评论