可以使用reshape()方法来调整数组的维度,使其变成相同的维度。

对于一维数组,可以使用reshape()方法将其变为二维数组,其中新的数组的行数为1,列数为原数组的长度。

例如:

import numpy as np

arr1 = np.array([1, 2, 3, 4, 5])
arr2 = np.array([[1, 2, 3], [4, 5, 6]])

arr1_reshaped = arr1.reshape(1, arr1.shape[0])
print(arr1_reshaped)

输出:

[[1 2 3 4 5]]

对于二维数组,可以使用reshape()方法将其变为一维数组,其中新的数组的长度为原数组的元素个数。

例如:

import numpy as np

arr1 = np.array([1, 2, 3, 4, 5])
arr2 = np.array([[1, 2, 3], [4, 5, 6]])

arr2_reshaped = arr2.reshape(arr2.shape[0] * arr2.shape[1])
print(arr2_reshaped)

输出:

[1 2 3 4 5 6]

需要注意的是,reshape()方法返回的是一个新的数组,原数组并不会发生改变


原文地址: http://www.cveoy.top/t/topic/hYib 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录