我想用另一个数组 reshape 一个数组。
假设我有 array_1
,其 shape
是 (5, 1)
,例如:
>>> array_1
array([[ 0.33333333],
[ 0.36666667],
[ 0.16666667],
[ 0.06666667],
[ 0.06666667]]
和array_2
,其形状为(1, 5)
。我想 reshape array_1
使其成为 array_2
的形状。每次运行代码时,array_2
的形状都会发生变化。
最佳答案
假设 numpy
数组,只需使用 array_1.reshape(array_2.shape)
:
>>> import numpy as np
>>> arr1 = np.arange(5).reshape(5, 1)
>>> arr2 = np.arange(5, 10).reshape(1, 5)
>>> arr1
array([[0],
[1],
[2],
[3],
[4]])
>>> arr2
array([[5, 6, 7, 8, 9]])
>>> arr1.reshape(arr2.shape)
array([[0, 1, 2, 3, 4]])
>>> arr2.reshape(arr1.shape)
array([[5],
[6],
[7],
[8],
[9]])
请注意,这不是原地;它会创建一个新数组,因此您需要分配例如array_1 = array_1.reshape(...)
。
关于python - 使用另一个数组更改数组的形状,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31535674/