103

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?

eyllanesc
  • 235,170
  • 19
  • 170
  • 241
Shan
  • 18,563
  • 39
  • 97
  • 132
  • @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. – Shan Oct 11 '11 at 00:39

4 Answers4

115

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=...)
unutbu
  • 842,883
  • 184
  • 1,785
  • 1,677
  • 174
    this solution doesn't work. you'll get a numpy array of python lists. – user1816847 Dec 01 '16 at 00:47
  • 66
    @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. – compie Jan 27 '17 at 22:41
  • 13
    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. – Amir Jul 22 '17 at 01:48
  • Thank you from September 2017 (Ubuntu 16.04 LTS). This is what I needed. Much simpler than anticipated. – SDsolar Sep 12 '17 at 22:58
  • 1
    Thanks for the important answer, @compie – iedmrc Mar 03 '19 at 09:01
  • 1
    Use np.concatenate(YOUR_LIST) if you have a list of an array and you want a single array. – Pritesh Gohil Nov 19 '20 at 19:28
3

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.

Clock ZHONG
  • 875
  • 9
  • 23
2

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

1

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])
gboffi
  • 22,939
  • 8
  • 54
  • 85
PeterB
  • 37
  • 1