109

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?

1
  • @Donkopotamus, It was a mistake by me... I was giving a sequence... I was doing the same but getting the error. After I got the same code from here I checked where the prob is... So it helps... offcourse I do check the documentation before posting here... Thanks for the friendly reminder. Commented Oct 11, 2011 at 0:39

4 Answers 4

119

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=...)
Sign up to request clarification or add additional context in comments.

5 Comments

this solution doesn't work. you'll get a numpy array of python lists.
@user1816847 That only happens when the 'sub' lists differ in length (eg: [[1,2], [1,2], [1,2,3]]. It does work with the example given in the question.
If the sub-arrays do not have the same length, this solution will only give you a numpy array of lists (i.e. the inner lists won't be converted to numpy arrays). Which totally makes sense as you cannot have a 2D array (matrix) with variable 2nd dimension.
Thank you from September 2017 (Ubuntu 16.04 LTS). This is what I needed. Much simpler than anticipated.
Use np.concatenate(YOUR_LIST) if you have a list of an array and you want a single array.
4

np.array() is even more powerful than what unutbu said above. You also could use it to convert a list of np arrays to a higher dimention array, the following is a simple example:

aArray=np.array([1,1,1])

bArray=np.array([2,2,2])

aList=[aArray, bArray]

xArray=np.array(aList)

xArray's shape is (2,3), it's a standard np array. This operation avoids a loop programming.

Comments

3

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

Comments

2

I am using large data sets exported to a python file in the form

XVals1 = [.........] 
XVals2 = [.........] 

Each list is of identical length. I use

>>> a1 = np.array(SV.XVals1)

>>> a2 = np.array(SV.XVals2)

Then

>>> A = np.matrix([a1,a2])

1 Comment

What is 'SV' here

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.