Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to convert 2d list to 2d numpy array?

Tags:

python

numpy

I have a 2D list something like

a = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]  

and I want to convert it to a 2d numpy array. Can we do it without allocating memory like

numpy.zeros((3,3)) 

and then storing values to it?

like image 629
Shan Avatar asked Oct 10 '11 19:10

Shan


People also ask

Can we convert list to NumPy array?

The similarity between an array and a list is that the elements of both array and a list can be identified by its index value. In Python lists can be converted to arrays by using two methods from the NumPy library: Using numpy. array()

How do you make a NumPy 2D array?

In Python to declare a new 2-dimensional array we can easily use the combination of arange and reshape() method. The reshape() method is used to shape a numpy array without updating its data and arange() function is used to create a new array.


2 Answers

Just pass the list to np.array:

a = np.array(a) 

You can also take this opportunity to set the dtype if the default is not what you desire.

a = np.array(a, dtype=...) 
like image 84
unutbu Avatar answered Oct 13 '22 06:10

unutbu


just use following code

c = np.matrix([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) matrix([[1, 2, 3],     [4, 5, 6],     [7, 8, 9]]) 

Then it will give you

you can check shape and dimension of matrix by using following code

c.shape

c.ndim

like image 24
sandeep sharma Avatar answered Oct 13 '22 05:10

sandeep sharma