Python 将一维数组转换为numpy矩阵
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16235564/
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
Convert 1D array into numpy matrix
提问by user2323596
I have a simple, one dimensional Python array with random numbers. What I want to do is convert it into a numpy Matrix of a specific shape. My current attempt looks like this:
我有一个带有随机数的简单的一维 Python 数组。我想要做的是将其转换为特定形状的 numpy 矩阵。我目前的尝试是这样的:
randomWeights = []
for i in range(80):
randomWeights.append(random.uniform(-1, 1))
W = np.mat(randomWeights)
W.reshape(8,10)
Unfortunately it always creates a matrix of the form:
不幸的是,它总是创建一个如下形式的矩阵:
[[random1, random2, random3, ...]]
[[随机1,随机2,随机3,...]]
So only the first element of one dimension gets used and the reshape command has no effect. Is there a way to convert the 1D array to a matrix so that the first x items will be row 1 of the matrix, the next x items will be row 2 and so on?
所以只有一个维度的第一个元素被使用并且 reshape 命令不起作用。有没有办法将一维数组转换为矩阵,以便前 x 项将是矩阵的第 1 行,接下来的 x 项将是第 2 行,依此类推?
Basically this would be the intended shape:
基本上这将是预期的形状:
[[1, 2, 3, 4, 5, 6, 7, 8],
[9, 10, 11, ... , 16],
[..., 800]]
I suppose I can always build a new matrix in the desired form manually by parsing through the input array. But I'd like to know if there is a simpler, more eleganz solution with built-in functions I'm not seeing. If I have to build those matrices manually I'll have a ton of extra work in other areas of the code since all my source data comes in simple 1D arrays but will be computed as matrices.
我想我总是可以通过解析输入数组来手动构建所需形式的新矩阵。但我想知道是否有一个更简单、更优雅的解决方案,其中包含我没有看到的内置函数。如果我必须手动构建这些矩阵,我将在代码的其他区域进行大量额外工作,因为我的所有源数据都来自简单的一维数组,但将作为矩阵进行计算。
采纳答案by Junuxx
reshape()doesn't reshape in place, you need to assign the result:
reshape()不会就地重塑,您需要分配结果:
>>> W = W.reshape(8,10)
>>> W.shape
(8,10)
回答by Han Qiu
You can use W.resize(), ndarray.resize()
您可以使用W.resize(), ndarray.resize()

