9 数组操作
9.1更改形状
numpy.ndarray.shape
表示数组的维度,返回一个元组,这个元组的长度就是维度的数目,即 ndim 属性(秩)。
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’ – 元素在内存中的出现顺序。(简记)
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.flatten()
print(y)
# [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(x)
# [[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]]
9.2 数组
numpy.ndarray.T self.transpose()
9.3 更改维度
numpy.newaxis = None
None 的别名,对索引数组很有用。
numpy.squeeze(a, axis=None)
从数组的形状中删除单维度条目,即把shape中为1的维度去掉。
a. a 表示输入的数组;
b. axis 用于指定需要删除的维度,但是指定的维度必须为单维度,否则将会报错;
import numpy as np
x = np.arange(10)
print(x.shape)
# (10,)
x = x[np.newaxis, :]
print(x.shape)
# (1, 10)
y = np.squeeze(x)
print(y.shape)
# (10,)
9.4 数组组合
numpy.concatenate((a1, a2, …), axis=0, out=None)
import numpy as np
x = np.array([[1, 2, 3], [4, 5, 6]])
y = np.array([[7, 8, 9], [10, 11, 12]])
z = np.concatenate([x, y])
print(z)
# [[ 1 2 3]
# [ 4 5 6]
# [ 7 8 9]
# [10 11 12]]
z = np.concatenate([x, y], axis=0)
print(z)
# [[ 1 2 3]
# [ 4 5 6]
# [ 7 8 9]
# [10 11 12]]
z = np.concatenate([x, y], axis=1)
print(z)
# [[ 1 2 3 7 8 9]
# [ 4 5 6 10 11 12]]
numpy.stack(arrays, axis=0, out=None) numpy.vstack(tup) numpy.hstack(tup)
import numpy as np
x = np.array([[1, 2, 3], [4, 5, 6]])
y = np.array([[7, 8, 9], [10, 11, 12]])
z = np.stack([x, y])
print(z.shape)
# (2, 2, 3) print(z)
# [[[ 1 2 3] # [ 4 5 6]]
#
# [[ 7 8 9]
# [10 11 12]]]
z = np.stack([x, y], axis=1)
print(z.shape)
# (2, 2, 3) print(z)
# [[[ 1 2 3]
# [ 7 8 9]]
#
# [[ 4 5 6]
# [10 11 12]]]
z = np.stack([x, y], axis=2) print(z.shape)
# (2, 3, 2) print(z)
# [[[ 1 7]
# [ 2 8]
# [ 3 9]]
#
# [[ 4 10]
# [ 5 11]
# [ 6 12]]]
9.5 数组拆分
numpy.split(ary, indices_or_sections, axis=0)
import numpy as np
x = np.array([[11, 12, 13, 14],
[16, 17, 18, 19],
[21, 22, 23, 24]])
y = np.split(x, [1, 3])
print(y)
# [array([[11, 12, 13, 14]]), array([[16, 17, 18, 19],
# [21, 22, 23, 24]]), array([], shape=(0, 4), dtype=int32)]
y = np.split(x, [1, 3], axis=1)
print(y)
# [array([[11],
# [16],
# [21]]), array([[12, 13],
# [17, 18],
# [22, 23]]), array([[14],
# [19],
# [24]])]