In data science and machine learning, using ndarray (multidimensional arrays) of the numpy library is essential. However, sometimes we need to convert these arrays into Python lists for further processing. This article will provide a simple and easy-to-understand conversion method from numpy array to list, and provide specific code examples.
1. Use the tolist() method
ndarray in numpy provides the tolist() method, which can be converted into a Python list. The following is a simple example:
import numpy as np nd_array = np.array([[1, 2, 3], [4, 5, 6]]) lst = nd_array.tolist() print(lst)
Output:
[[1, 2, 3], [4, 5, 6]]
2. Use the flatten() method combined with the tolist() method
In addition to the previously mentioned tolist() method , we can also convert the ndarray to a one-dimensional array and then use the tolist() method to convert it to a Python list. The following is an example:
import numpy as np nd_array = np.array([[1, 2, 3], [4, 5, 6]]) flat_array = nd_array.flatten() lst = flat_array.tolist() print(lst)
Output:
[1, 2, 3, 4, 5, 6]
3. Use the list() method
In addition to the tolist() method in the numpy library, Python also comes with one The list() method that converts an iterable object into a list. We can pass the ndarray object directly to the list() method for conversion. The following is an example:
import numpy as np nd_array = np.array([[1, 2, 3], [4, 5, 6]]) lst = list(nd_array) print(lst)
Output:
[array([1, 2, 3]), array([4, 5, 6])]
It should be noted that using the list() method will create a list containing multiple one-dimensional ndarray objects.
4. Use for loop
Finally, we can use Python’s for loop to convert the ndarray object into a Python list. The following is an example:
import numpy as np nd_array = np.array([[1, 2, 3], [4, 5, 6]]) lst = [] for row in nd_array: for value in row: lst.append(value) print(lst)
Output:
[1, 2, 3, 4, 5, 6]
The above is a simple and easy-to-understand conversion method from numpy array to list, including using the tolist() method, combining the flatten() method and tolist( ) method, use the list() method, and use a for loop. All the above methods can be effectively converted, just choose the method that suits you best according to the actual situation.
The above is the detailed content of From numpy array to list: simple and easy to understand conversion method. For more information, please follow other related articles on the PHP Chinese website!