Let’s learn how to to convert list to Numpy array. We will use Numpy asarray method and a clever trick.
There are 3 different ways to convert Python list to Numpy array.
How to convert list to Numpy array using array method?
The easiest way to cast list to array is to use array method and set list as a single parameter.
import numpy as np my_list = [1, 2, 3, 4, 5, 6] my_array = np.array(my_list) print(f"Numpy array converted " f"from Python list: {my_list}")
How to convert list to Numpy array using asarray method?
The other way to cast list to array is to use asarray method and also set list as a single parameter.
import numpy as np my_list = [1, 2, 3, 4, 5, 6] my_array = np.asarray(my_list) print(f"Numpy array converted " f"from Python list: {my_list}")
How to convert list of lists to Numpy array using concatenate method?
Let’s check more difficult task.
To convert list of lists to Numpy array you need to use Python concatenate method. The parameter you need to use to cast it properly is axis=0.
import numpy as np my_list = [[1, 2, 3], [4, 5], [6, 7, 8, 9]] my_array = np.concatenate(my_list, axis=0) print(f"Numpy array converted " f"from Python list of lists: {my_list}")