在NumPy中,可以使用不同的函数和方法来处理数据的维度。
numpy.array()
函数来创建数组,可以是一维、二维、多维数组。import numpy as np
# 一维数组
a = np.array([1, 2, 3])
# 二维数组
b = np.array([[1, 2, 3],
[4, 5, 6]])
# 多维数组
c = np.array([[[1, 2, 3],
[4, 5, 6]],
[[7, 8, 9],
[10, 11, 12]]])
shape
属性来获取数组的形状。# 一维数组形状
print(a.shape) # 输出: (3,)
# 二维数组形状
print(b.shape) # 输出: (2, 3)
# 多维数组形状
print(c.shape) # 输出: (2, 2, 3)
reshape()
方法来改变数组的形状,参数为新的形状。# 改变二维数组的形状
b_reshaped = b.reshape(3, 2)
print(b_reshaped.shape) # 输出: (3, 2)
# 改变多维数组的形状
c_reshaped = c.reshape(4, 3)
print(c_reshaped.shape) # 输出: (4, 3)
np.expand_dims()
函数来扩展数组的维度。# 扩展一维数组的维度
a_expanded = np.expand_dims(a, axis=0)
print(a_expanded.shape) # 输出: (1, 3)
# 扩展二维数组的维度
b_expanded = np.expand_dims(b, axis=2)
print(b_expanded.shape) # 输出: (2, 3, 1)
np.squeeze()
函数来降低数组的维度,可以指定降低的维度。# 降低二维数组的维度
b_squeezed = np.squeeze(b, axis=0)
print(b_squeezed.shape) # 输出: (2, 3)
# 降低多维数组的维度
c_squeezed = np.squeeze(c, axis=(0, 2))
print(c_squeezed.shape) # 输出: (2, 2)
import numpy as np
# 创建一个形状为 (1, 3, 1) 的数组
arr = np.zeros((1, 3, 1))
print("原始数组形状:", arr.shape) # 输出 (1, 3, 1)
# 使用 np.squeeze() 函数降维
arr_squeezed = np.squeeze(arr)
print("降维后的数组形状:", arr_squeezed.shape) # 输出 (3,)
6、在numpy中,可以使用transpose()函数来交换数组的维度。transpose()函数可以接受一个包含轴编号的元组作为参数,指定需要交换的维度。
import numpy as np
arr = np.array([[1, 2, 3],
[4, 5, 6]])#(2,3)
arr_transposed = arr.transpose((1, 0)) #(3,2)
print(arr_transposed)