通过仅指定列大小将数组重新整形为2-D

时间:2014-04-12 16:31:11

标签: python numpy python-2.x

我有一个长度的矢量,比方说10:

foo = np.arange(2,12)

为了将它转换为2-D数组,让我们说2列,我使用命令reshape和以下参数:

foo.reshape(len(foo)/2, 2)

我想知道是否有更优雅的方法/语法(可能像foo.reshape(,2)

1 个答案:

答案 0 :(得分:20)

你几乎拥有它!您可以使用-1

>>> foo.reshape(-1, 2)
array([[ 2,  3],
       [ 4,  5],
       [ 6,  7],
       [ 8,  9],
       [10, 11]])

正如reshape文档所说:

newshape : int or tuple of ints
    The new shape should be compatible with the original shape. If
    an integer, then the result will be a 1-D array of that length.
    One shape dimension can be -1. In this case, the value is inferred
    from the length of the array and remaining dimensions.