数组python的形状
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15668380/
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
Shape of array python
提问by lord12
Suppose I create a 2 dimensional array
假设我创建了一个二维数组
m = np.random.normal(0, 1, size=(1000, 2))
q = np.zeros(shape=(1000,1))
print m[:,0] -q
When I take m[:,0].shapeI get (1000,)as opposed to (1000,1)which is what I want. How do I coerce m[:,0]to a (1000,1)array?
当我接受时,m[:,0].shape我得到的(1000,)不是(1000,1)我想要的。如何强制m[:,0]使用(1000,1)数组?
采纳答案by DSM
By selecting the 0th column in particular, as you've noticed, you reduce the dimensionality:
正如您所注意到的,通过特别选择第 0 列,您可以降低维度:
>>> m = np.random.normal(0, 1, size=(5, 2))
>>> m[:,0].shape
(5,)
You have a lot of options to get a 5x1 object back out. You can index using a list, rather than an integer:
您有很多选择可以取回 5x1 对象。您可以使用列表而不是整数来索引:
>>> m[:, [0]].shape
(5, 1)
You can ask for "all the columns up to but not including 1":
您可以要求“最多但不包括 1 的所有列”:
>>> m[:,:1].shape
(5, 1)
Or you can use None(or np.newaxis), which is a general trick to extend the dimensions:
或者您可以使用None(or np.newaxis),这是扩展维度的一般技巧:
>>> m[:,0,None].shape
(5, 1)
>>> m[:,0][:,None].shape
(5, 1)
>>> m[:,0, None, None].shape
(5, 1, 1)
Finally, you can reshape:
最后,您可以重塑:
>>> m[:,0].reshape(5,1).shape
(5, 1)
but I'd use one of the other methods for a case like this.
但对于这样的情况,我会使用其他方法之一。

