Shan Shan - 2 days ago 4
Python Question

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

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?

Answer

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