Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert 1D array into numpy matrix

Tags:

python

numpy

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:

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, ...]]

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?

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.

like image 291
user2323596 Avatar asked Apr 26 '13 11:04

user2323596


People also ask

How do you convert a 1D array to a 2D array in Python?

Use reshape() Function to Transform 1d Array to 2d Array The number of components within every dimension defines the form of the array. We may add or delete parameters or adjust the number of items within every dimension by using reshaping. To modify the layout of a NumPy ndarray, we will be using the reshape() method.

How do you convert a 1D array of tuples to a 2D NumPy array?

How to convert a 1d array of tuples to a 2d numpy array? Yes it is possible to convert a 1 dimensional numpy array to a 2 dimensional numpy array, by using "np. reshape()" this function we can achiev this.


1 Answers

reshape() doesn't reshape in place, you need to assign the result:

>>> W = W.reshape(8,10)
>>> W.shape
(8,10)    
like image 192
Junuxx Avatar answered Sep 20 '22 03:09

Junuxx