Skip to main content
 首页 » 编程设计

python之Numpy,如何将向量 reshape 为多列数组

2025年05月04日10zlslch

我想知道如何在不给出行号的情况下使用 np.reshape 将长向量 reshape 为 n 列数组。

通常我可以通过 len(a)//n 找到行号:

a = np.arange(0, 10) 
n = 2 
b = a.reshape(len(a)//n,n) 

有没有不用len(a)//n的更直接的方法呢?

请您参考如下方法:

你可以在一维上使用 -1,numpy 会计算出这个数字应该是多少:

a = np.arange(0, 10) 
n = 2 
b = a.reshape(-1, n) 

文档对此功能非常清楚:https://docs.scipy.org/doc/numpy/reference/generated/numpy.reshape.html

One shape dimension can be -1. In this case, the value is inferred from the length of the array and remaining dimensions.