在Numpy中转置一维数组而不转换为矩阵 [英] Transpose a 1-dimensional array in Numpy without casting to matrix
问题描述
我的目标是将行向量变成列向量,反之亦然. numpy.ndarray.transpose
说:
My goal is to to turn a row vector into a column vector and vice versa. The documentation for numpy.ndarray.transpose
says:
对于一维数组,这无效. (要在列向量和行向量之间切换,请先将一维数组转换为矩阵对象.)
For a 1-D array, this has no effect. (To change between column and row vectors, first cast the 1-D array into a matrix object.)
但是,当我尝试此操作时:
However, when I try this:
my_array = np.array([1,2,3])
my_array_T = np.transpose(np.matrix(myArray))
我确实得到了所需的结果,尽管是矩阵形式(matrix([[66],[640],[44]])
),但我也得到了这个警告:
I do get the wanted result, albeit in matrix form (matrix([[66],[640],[44]])
), but I also get this warning:
PendingDeprecationWarning: the matrix subclass is not the recommended way to represent matrices or deal with linear algebra (see https://docs.scipy.org/doc/numpy/user/numpy-for-matlab-users.html). Please adjust your code to use regular ndarray.
my_array_T = np.transpose(np.matrix(my_array))
那我该如何正确换位ndarray
?
推荐答案
1D数组本身一旦转置,与Matlab相反,在Matlab中,一维数组不存在且至少为2D.
A 1D array is itself once transposed, contrary to Matlab where a 1D array doesn't exist and is at least 2D.
您要重塑它:
my_array.reshape(-1, 1)
或者:
my_array.reshape(1, -1)
取决于要使用的向量类型(列向量还是行向量).
Depending on what kind of vector you want (column or row vector).
-1
类似于广播,使用了所有可能的元素,并且1
创建了第二个所需的尺寸.
The -1
is a broadcast-like, using all possible elements, and the 1
creates the second required dimension.
这篇关于在Numpy中转置一维数组而不转换为矩阵的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!