How do I convert a NumPy array to a Python List (for example [[1,2,3],[4,5,6]]
), and do it reasonably fast?
相关问题
- how to define constructor for Python's new Nam
- streaming md5sum of contents of a large remote tar
- How to get the background from multiple images by
- Evil ctypes hack in python
- Correctly parse PDF paragraphs with Python
Use
tolist()
: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.)
tolist()
works fine even if encountered a nested array, say a pandasDataFrame
;The numpy .tolist method produces nested arrays if the numpy array shape is 2D.
if flat lists are desired, the method below works.