如何将二维列表转换为二维数组?

我有一个2D 列表

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

我想把它转换成一个二维的数字数组。我们能不能不分配内存

numpy.zeros((3,3))

然后存储它的值?

204258 次浏览

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=...)

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])

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.

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