如何制作具有2D形状的numpy数组

时间:2018-02-02 15:25:01

标签: python numpy numpy-ndarray

我有像这样的简单数组

x = np.array([1,2,3,4])

In [3]: x.shape
Out[3]: (4,)

但我不希望形状返回(4,),但是(4, 1 )。我怎样才能做到这一点?

5 个答案:

答案 0 :(得分:3)

通常在Numpy中,您可以使用two square brackets声明矩阵或向量。将单方括号用于单维矩阵或向量是一种常见的误解。

以下是一个例子:

a = np.array([[1,2,3,4], [5,6,7,8]])
a.shape # (2,4) -> Multi-Dimensional Matrix

以类似的方式,如果我想要单维矩阵,那么只需删除不是外square bracket的数据。

a = np.array([[1,2,3,4]])
a.shape # (1,4) -> Row Matrix

b = np.array([[1], [2], [3], [4]])
b.shape # (4, 1) -> Column Matrix

当您使用单方括号时,它可能会给出一些奇怪的尺寸。

始终将您的数据包含在另一个方括号中,用于这样的单维矩阵(就像您输入多维矩阵的数据一样),而不包含这些额外维度的数据。

另外: 您也可以随时重塑

x = np.array([1,2,3,4])
x = x.reshape(4,1)
x.shape # (4,1)

一行:

x = np.array([1,2,3,4]).reshape(4,1)
x.shape # (4,1)

答案 1 :(得分:2)

如果要使用列矢量

%d{yyyy-MM, aux}

答案 2 :(得分:2)

或者,您可以自己重塑阵列:

arr1.resize((4, 1))

当然,您可以在创建阵列时重塑阵列:

Update

如果您想根据评论中的@FHTMitchell建议更改数组:

Insert Into

答案 3 :(得分:1)

以下达到你想要的效果。但是,我强烈建议你看看为什么你需要x = np.array([1,2,3,4]) y = np.matrix(x) z = y.T x.shape # (4,) y.shape # (1, 4) z.shape # (4, 1) 返回(4,1)。如果没有这种明确的转换,大多数矩阵类型的操作都是可能的。

import sys
numbers= sys.argv[1:]
for i in range(0,len(numbers)): 
  numbers[i]= numbers[i].split(',')

答案 4 :(得分:0)

您可以使用zip在python(非numpy)级别进行转置:

>>> a = [1, 2, 3, 4]
>>> 
>>> *zip(a),
((1,), (2,), (3,), (4,))
>>> 
>>> import numpy as np
>>> np.array([*zip(a)])
array([[1],
       [2],
       [3],
       [4]])

请注意,虽然这在键击方面很方便,但是由于必须为每个列表元素构造元组对象,所以有点浪费,而重新整形数组基本上是免费的。所以不要在长列表中使用它。