在 Python 中创建垂直 NumPy 数组
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/29658567/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Create vertical NumPy arrays in Python
提问by Eghbal
I'm using NumPy in Python to work with arrays. This is the way I'm using to create a vertical array:
我在 Python 中使用 NumPy 来处理数组。这是我用来创建垂直数组的方式:
import numpy as np
a = np.array([[1],[2],[3]])
Is there a simple and more direct way to create vertical arrays?
有没有更简单更直接的方法来创建垂直阵列?
采纳答案by Kasramvd
You can use reshape
or vstack
:
您可以使用reshape
或vstack
:
>>> a=np.arange(1,4)
>>> a
array([1, 2, 3])
>>> a.reshape(3,1)
array([[1],
[2],
[3]])
>>> np.vstack(a)
array([[1],
[2],
[3]])
Also, you can use broadcastingin order to reshape your array:
此外,您可以使用广播来重塑您的数组:
In [32]: a = np.arange(10)
In [33]: a
Out[33]: array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
In [34]: a[:,None]
Out[34]:
array([[0],
[1],
[2],
[3],
[4],
[5],
[6],
[7],
[8],
[9]])
回答by Bhargav Rao
You can also use np.newaxis
(See Examples here)
您也可以使用np.newaxis
(请参阅此处的示例)
>>> import numpy as np
>>> np.arange(3)[:, np.newaxis]
array([[0],
[1],
[2]])
As a side note
作为旁注
I just realized that you have used, from numpy import *
. Do not do so as many functions from the Python generic library overlap with numpy
(for e.g. sum
). When you import *
from numpy
you lose the functionality of those functions. Hence always use :
我刚刚意识到你已经使用了,from numpy import *
. 不要这样做,因为 Python 通用库中的许多函数与numpy
(例如sum
)重叠。当你import *
从numpy
你失去这些功能的功能。因此总是使用:
import numpy as np
which is also easy to type.
这也很容易打字。
回答by hpaulj
Simplicity and directness is in the eye of the beholder.
旁观者眼中的简单和直接。
In [35]: a = np.array([[1],[2],[3]])
In [36]: a.flags
Out[36]:
C_CONTIGUOUS : True
F_CONTIGUOUS : False
OWNDATA : True
WRITEABLE : True
ALIGNED : True
UPDATEIFCOPY : False
In [37]: b=np.array([1,2,3]).reshape(3,1)
In [38]: b.flags
Out[38]:
C_CONTIGUOUS : True
F_CONTIGUOUS : False
OWNDATA : False
WRITEABLE : True
ALIGNED : True
UPDATEIFCOPY : False
The first is shorter and owns its data. So in a sense the extra brackets are a pain, but it's a rather subjective one.
第一个较短并拥有其数据。所以从某种意义上说,额外的括号是一种痛苦,但它是一个相当主观的。
Or if you want something more like MATLAB you could use the np.matrix
string format:
或者,如果您想要更像 MATLAB 的东西,您可以使用np.matrix
字符串格式:
c=np.array(np.matrix('1;2;3'))
c=np.mat('1;2;3').A
But I usually don't worry about the OWNDATA flag. One of my favorite sample arrays is:
但我通常不担心 OWNDATA 标志。我最喜欢的示例数组之一是:
np.arange(12).reshape(3,4)
Other ways:
其他方法:
np.atleast_2d([1,2,3]).T
np.array([1,2,3],ndmin=2).T
a=np.empty((3,1),int);a[:,0]=[1,2,3] # OWNDATA