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

Susan Sarandon
Release: 2024-10-31 20:38:02
Original
234 people have browsed it

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]]
Copy after login

To convert this array to a list:

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

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>, ... ]
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!