How do I convert a NumPy array to a Python List (for example [[1,2,3],[4,5,6]] ), and do it reasonably fast?
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
Use tolist():
import numpy as np >>> np.array([[1,2,3],[4,5,6]]).tolist() [[1, 2, 3], [4, 5, 6]]
Note that this converts the values from whatever numpy type they may have (e.g. np.int32 or np.float32) to the “nearest compatible Python type” (in a list). If you want to preserve the numpy data types, you could call list() on your array instead, and you’ll end up with a list of numpy scalars. (Thanks to Mr_and_Mrs_D for pointing that out in a comment.)
Method 2
The numpy .tolist method produces nested lists if the numpy array shape is 2D.
if flat lists are desired, the method below works.
import numpy as np from itertools import chain a = [1,2,3,4,5,6,7,8,9] print type(a), len(a), a npa = np.asarray(a) print type(npa), npa.shape, "n", npa npa = npa.reshape((3, 3)) print type(npa), npa.shape, "n", npa a = list(chain.from_iterable(npa)) print type(a), len(a), a`
Method 3
c = np.array([[1,2,3],[4,5,6]])
list(c.flatten())
Method 4
tolist() works fine even if encountered a nested array, say a pandas DataFrame;
my_list = [0,1,2,3,4,5,4,3,2,1,0] my_dt = pd.DataFrame(my_list) new_list = [i[0] for i in my_dt.values.tolist()] print(type(my_list),type(my_dt),type(new_list))
Method 5
Another option
c.ravel() # or c.ravel().tolist()
also works.
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0