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

21 投票
1 回答
14376 浏览
提问于 2025-04-18 02:30

我有一个长度为10的向量:

foo = np.arange(2,12)

为了把它转换成一个二维数组,比如说有2列,我使用了一个叫做 reshape 的命令,参数是:

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

我在想有没有更简洁的写法来做到这一点,比如说像 foo.reshape(,2) 这样的。

1 个回答

37

你差一点就对了!你可以用 -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.

撰写回答