转置一维 NumPy 数组

发布于 2024-11-05 22:32:32 字数 252 浏览 2 评论 0原文

我使用 Python 和 NumPy,并且在“转置”方面遇到一些问题:

import numpy as np
a = np.array([5,4])
print(a)
print(a.T)

调用 aT 不会转置数组。例如,如果 a[[],[]] 那么它会正确转置,但我需要 [...,..., 的转置。 ..]

I use Python and NumPy and have some problems with "transpose":

import numpy as np
a = np.array([5,4])
print(a)
print(a.T)

Invoking a.T is not transposing the array. If a is for example [[],[]] then it transposes correctly, but I need the transpose of [...,...,...].

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(15

记忆で 2024-11-12 22:32:33

而是使用 arr[:,None] 创建列向量

instead use arr[:,None] to create column vector

小糖芽 2024-11-12 22:32:33

您只能转置二维数组。您可以使用 numpy.matrix 创建二维数组。这已经晚了三年,但我只是添加了可能的解决方案:

import numpy as np
m = np.matrix([2, 3])
m.T

You can only transpose a 2D array. You can use numpy.matrix to create a 2D array. This is three years late, but I am just adding to the possible set of solutions:

import numpy as np
m = np.matrix([2, 3])
m.T
你的背包 2024-11-12 22:32:33

有一种方法没有在答案中描述,但在 numpy.ndarray.transpose 方法的文档

对于一维数组,这没有效果,因为转置向量只是相同的向量。要将一维数组转换为二维列向量,必须添加额外的维度。 np.atleast2d(a).T 实现了这一点,a[:, np.newaxis] 也是如此。

人们可以做:

import numpy as np
a = np.array([5,4])
print(a)
print(np.atleast_2d(a).T)

哪个(我认为)比使用 newaxis 更好。

There is a method not described in the answers but described in the documentation for the numpy.ndarray.transpose method:

For a 1-D array this has no effect, as a transposed vector is simply the same vector. To convert a 1-D array into a 2D column vector, an additional dimension must be added. np.atleast2d(a).T achieves this, as does a[:, np.newaxis].

One can do:

import numpy as np
a = np.array([5,4])
print(a)
print(np.atleast_2d(a).T)

Which (imo) is nicer than using newaxis.

君勿笑 2024-11-12 22:32:33

基本上,转置函数的作用是交换数组的形状和步长:

>>> a = np.ones((1,2,3))

>>> a.shape
(1, 2, 3)

>>> a.T.shape
(3, 2, 1)

>>> a.strides
(48, 24, 8)

>>> a.T.strides
(8, 24, 48)

对于 1D numpy 数组(rank-1 数组),形状和步长是 1 元素元组,不能交换,并且这种 1D 的转置数组返回它不变。相反,您可以将“行向量”(形状为 (1, n) 的 numpy 数组)转置为“列向量”(形状为 (n, 1)< 的 numpy 数组) /代码>)。为了实现这一点,你必须首先将一维 numpy 数组转换为行向量,然后交换形状和步幅(转置它)。下面是一个执行此操作的函数:

from numpy.lib.stride_tricks import as_strided

def transpose(a):
    a = np.atleast_2d(a)
    return as_strided(a, shape=a.shape[::-1], strides=a.strides[::-1])

示例:

>>> a = np.arange(3)
>>> a
array([0, 1, 2])

>>> transpose(a)
array([[0],
       [1],
       [2]])

>>> a = np.arange(1, 7).reshape(2,3)
>>> a     
array([[1, 2, 3],
       [4, 5, 6]])

>>> transpose(a)
array([[1, 4],
       [2, 5],
       [3, 6]])

当然您不必这样做,因为您有一个一维数组,您可以通过 < 直接将其重塑为 (n, 1) 数组代码>a.reshape((-1, 1)) 或a[:, None]。我只是想演示转置数组的工作原理。

Basically what the transpose function does is to swap the shape and strides of the array:

>>> a = np.ones((1,2,3))

>>> a.shape
(1, 2, 3)

>>> a.T.shape
(3, 2, 1)

>>> a.strides
(48, 24, 8)

>>> a.T.strides
(8, 24, 48)

In case of 1D numpy array (rank-1 array) the shape and strides are 1-element tuples and cannot be swapped, and the transpose of such an 1D array returns it unchanged. Instead, you can transpose a "row-vector" (numpy array of shape (1, n)) into a "column-vector" (numpy array of shape (n, 1)). To achieve this you have to first convert your 1D numpy array into row-vector and then swap the shape and strides (transpose it). Below is a function that does it:

from numpy.lib.stride_tricks import as_strided

def transpose(a):
    a = np.atleast_2d(a)
    return as_strided(a, shape=a.shape[::-1], strides=a.strides[::-1])

Example:

>>> a = np.arange(3)
>>> a
array([0, 1, 2])

>>> transpose(a)
array([[0],
       [1],
       [2]])

>>> a = np.arange(1, 7).reshape(2,3)
>>> a     
array([[1, 2, 3],
       [4, 5, 6]])

>>> transpose(a)
array([[1, 4],
       [2, 5],
       [3, 6]])

Of course you don't have to do it this way since you have a 1D array and you can directly reshape it into (n, 1) array by a.reshape((-1, 1)) or a[:, None]. I just wanted to demonstrate how transposing an array works.

感情洁癖 2024-11-12 22:32:33

另一个解决方案......:-)

import numpy as np

a = [1,2,4]

[1,2,4]

b = np.array([a]).T

数组([[1],
[2],
[4]])

Another solution.... :-)

import numpy as np

a = [1,2,4]

[1, 2, 4]

b = np.array([a]).T

array([[1],
[2],
[4]])

秋意浓 2024-11-12 22:32:33

numpy 中的函数名称为 column_stack

>>>a=np.array([5,4])
>>>np.column_stack(a)
array([[5, 4]])

The name of the function in numpy is column_stack.

>>>a=np.array([5,4])
>>>np.column_stack(a)
array([[5, 4]])
遗失的美好 2024-11-12 22:32:33

我只是在巩固上面的帖子,希望它能帮助其他人节省一些时间:

下面的数组有(2, )维度,它是一个一维数组,

b_new = np.array([2j, 3j])  

有有两种转置一维数组的方法:


使用“np.newaxis”对其进行切片或不进行切片。!

print(b_new[np.newaxis].T.shape)
print(b_new[None].T.shape)

其他书写方式,上面没有 T< /code> 操作。!

print(b_new[:, np.newaxis].shape)
print(b_new[:, None].shape)

包裹 [ ] 或使用 np.matrix,意味着添加新维度。!

print(np.array([b_new]).T.shape)
print(np.matrix(b_new).T.shape)

I am just consolidating the above post, hope it will help others to save some time:

The below array has (2, )dimension, it's a 1-D array,

b_new = np.array([2j, 3j])  

There are two ways to transpose a 1-D array:


slice it with "np.newaxis" or none.!

print(b_new[np.newaxis].T.shape)
print(b_new[None].T.shape)

other way of writing, the above without T operation.!

print(b_new[:, np.newaxis].shape)
print(b_new[:, None].shape)

Wrapping [ ] or using np.matrix, means adding a new dimension.!

print(np.array([b_new]).T.shape)
print(np.matrix(b_new).T.shape)
奈何桥上唱咆哮 2024-11-12 22:32:33

要像示例中那样转置一维数组(平面数组),可以使用 np.expand_dims() 函数:

>>> a = np.expand_dims(np.array([5, 4]), axis=1)
array([[5],
       [4]])

np.expand_dims() 将添加所选轴的尺寸。在本例中,我们使用 axis=1,它添加了列维度,从而有效地转置原始平面数组。

To transpose a 1-D array (flat array) as you have in your example, you can use the np.expand_dims() function:

>>> a = np.expand_dims(np.array([5, 4]), axis=1)
array([[5],
       [4]])

np.expand_dims() will add a dimension to the chosen axis. In this case, we use axis=1, which adds a column dimension, effectively transposing your original flat array.

独自←快乐 2024-11-12 22:32:33

正如上面提到的一些评论,一维数组的转置是一维数组,因此转置一维数组的一种方法是将数组转换为矩阵,如下所示:

np.transpose(a.reshape(len(a), 1))

As some of the comments above mentioned, the transpose of 1D arrays are 1D arrays, so one way to transpose a 1D array would be to convert the array to a matrix like so:

np.transpose(a.reshape(len(a), 1))
第几種人 2024-11-12 22:32:32

它完全按照预期工作。 1D 数组的转置仍然是 1D 数组! (如果你习惯了 matlab,它根本上没有一维数组的概念。Matlab 的“一维”数组是二维的。)

如果你想将一维向量转换为二维数组,然后转置它,只需切片它与np.newaxis(或None,它们是相同的,newaxis只是更具可读性)。

import numpy as np
a = np.array([5,4])[np.newaxis]
print(a)
print(a.T)

但一般来说,您无需担心这一点。如果您只是出于习惯,添加额外的维度通常不是您想要的。 Numpy 在进行各种计算时会自动广播一维数组。当您只需要一个向量时,通常不需要区分行向量和列向量(它们都不是向量。它们都是二维的!)。

It's working exactly as it's supposed to. The transpose of a 1D array is still a 1D array! (If you're used to matlab, it fundamentally doesn't have a concept of a 1D array. Matlab's "1D" arrays are 2D.)

If you want to turn your 1D vector into a 2D array and then transpose it, just slice it with np.newaxis (or None, they're the same, newaxis is just more readable).

import numpy as np
a = np.array([5,4])[np.newaxis]
print(a)
print(a.T)

Generally speaking though, you don't ever need to worry about this. Adding the extra dimension is usually not what you want, if you're just doing it out of habit. Numpy will automatically broadcast a 1D array when doing various calculations. There's usually no need to distinguish between a row vector and a column vector (neither of which are vectors. They're both 2D!) when you just want a vector.

放肆 2024-11-12 22:32:32

使用两对括号而不是一对。这将创建一个可以转置的 2D 数组,这与使用一对括号时创建的 1D 数组不同。

import numpy as np    
a = np.array([[5, 4]])
a.T

更彻底的示例:

>>> a = [3,6,9]
>>> b = np.array(a)
>>> b.T
array([3, 6, 9])         #Here it didn't transpose because 'a' is 1 dimensional
>>> b = np.array([a])
>>> b.T
array([[3],              #Here it did transpose because a is 2 dimensional
       [6],
       [9]])

使用 numpy 的 shape 方法来查看这里发生了什么:

>>> b = np.array([10,20,30])
>>> b.shape
(3,)
>>> b = np.array([[10,20,30]])
>>> b.shape
(1, 3)

Use two bracket pairs instead of one. This creates a 2D array, which can be transposed, unlike the 1D array you create if you use one bracket pair.

import numpy as np    
a = np.array([[5, 4]])
a.T

More thorough example:

>>> a = [3,6,9]
>>> b = np.array(a)
>>> b.T
array([3, 6, 9])         #Here it didn't transpose because 'a' is 1 dimensional
>>> b = np.array([a])
>>> b.T
array([[3],              #Here it did transpose because a is 2 dimensional
       [6],
       [9]])

Use numpy's shape method to see what is going on here:

>>> b = np.array([10,20,30])
>>> b.shape
(3,)
>>> b = np.array([[10,20,30]])
>>> b.shape
(1, 3)
橘亓 2024-11-12 22:32:32

对于一维数组

a = np.array([1, 2, 3, 4])
a = a.reshape((-1, 1)) # <--- THIS IS IT

print a
array([[1],
       [2],
       [3],
       [4]])

一旦你理解了这里的 -1 意味着“需要多少行”,我发现这是“转置”数组的最易读的方式。如果您的数组具有更高的维数,只需使用aT

For 1D arrays:

a = np.array([1, 2, 3, 4])
a = a.reshape((-1, 1)) # <--- THIS IS IT

print a
array([[1],
       [2],
       [3],
       [4]])

Once you understand that -1 here means "as many rows as needed", I find this to be the most readable way of "transposing" an array. If your array is of higher dimensionality simply use a.T.

夏末染殇 2024-11-12 22:32:32

您可以通过将现有向量括在一组额外的方括号中将其转换为矩阵...

from numpy import *
v=array([5,4]) ## create a numpy vector
array([v]).T ## transpose a vector into a matrix

numpy 还有一个 matrix 类(请参阅数组与矩阵)...

matrix(v).T ## transpose a vector into a matrix

You can convert an existing vector into a matrix by wrapping it in an extra set of square brackets...

from numpy import *
v=array([5,4]) ## create a numpy vector
array([v]).T ## transpose a vector into a matrix

numpy also has a matrix class (see array vs. matrix)...

matrix(v).T ## transpose a vector into a matrix
红玫瑰 2024-11-12 22:32:32

numpy 一维数组 -->列/行矩阵:

>>> a=np.array([1,2,4])
>>> a[:, None]    # col
array([[1],
       [2],
       [4]])
>>> a[None, :]    # row, or faster `a[None]`
array([[1, 2, 4]])

正如 @joe-kington 所说,您可以将 None 替换为 np.newaxis 以提高可读性。

numpy 1D array --> column/row matrix:

>>> a=np.array([1,2,4])
>>> a[:, None]    # col
array([[1],
       [2],
       [4]])
>>> a[None, :]    # row, or faster `a[None]`
array([[1, 2, 4]])

And as @joe-kington said, you can replace None with np.newaxis for readability.

她说她爱他 2024-11-12 22:32:32

要将一维数组“转置”为二维列,可以使用 numpy.vstack

>>> numpy.vstack(numpy.array([1,2,3]))
array([[1],
       [2],
       [3]])

它也适用于普通列表:

>>> numpy.vstack([1,2,3])
array([[1],
       [2],
       [3]])

To 'transpose' a 1d array to a 2d column, you can use numpy.vstack:

>>> numpy.vstack(numpy.array([1,2,3]))
array([[1],
       [2],
       [3]])

It also works for vanilla lists:

>>> numpy.vstack([1,2,3])
array([[1],
       [2],
       [3]])
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文