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?
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()
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.
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=...)
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With