Home  >  Article  >  Backend Development  >  How do I convert NumPy arrays to Python lists while preserving their data types?

How do I convert NumPy arrays to Python lists while preserving their data types?

Susan Sarandon
Susan SarandonOriginal
2024-10-31 20:38:02225browse

How do I convert NumPy arrays to Python lists while preserving their data types?

Converting NumPy Arrays to Python Lists

NumPy arrays offer a powerful and efficient way to represent numerical data in Python. However, certain scenarios may necessitate the conversion of these arrays into Python lists.

Converting to Lists

To seamlessly transform a NumPy array into a Python list, you can leverage the tolist() method. This convenient function effortlessly creates a list by extracting the array's elements and casting them to Python's compatible data types.

For instance, consider the following NumPy array:

[[1, 2, 3], [4, 5, 6]]

To convert this array to a list:

tolist() returns [ [1, 2, 3], [4, 5, 6] ]

Preserving Numpy Data Types

While tolist() is generally sufficient for most use cases, it's important to note that it converts the array's elements to their corresponding Python types. If you wish to maintain the NumPy data types, you can employ the list() function instead. This alternative approach will result in a list of NumPy scalars:

list() returns [ <numpy.int32 1>, <numpy.int32 2>, ... ]

In conclusion, both tolist() and list() offer effective means of converting NumPy arrays to Python lists, catering to different data type requirements.

The above is the detailed content of How do I convert NumPy arrays to Python lists while preserving their data types?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn