How to Create a Dense NumPy Array from Variable-Length Lists?

Susan Sarandon
Release: 2024-11-04 08:32:01
Original
903 people have browsed it

How to Create a Dense NumPy Array from Variable-Length Lists?

Generating Dense NumPy Array from Variable-Length Lists

The standard conversion of a Python sequence containing variable-length lists into a NumPy array creates an object-type array. Enforcing another data type raises a ValueError. This article demonstrates an efficient method to generate a dense NumPy array of type int32 by filling missing values with a placeholder.

To convert a variable-length list-sequence into a NumPy array, one can utilize the itertools.zip_longest function from the itertools module. This function iterates through the lists, stopping when the shortest list is exhausted. It fills missing values in longer lists with a placeholder value specified by the fillvalue argument.

For instance, consider the following sequence of variable-length lists:

v = [[1], [1, 2]]
Copy after login

To generate a dense NumPy array from this sequence, with a placeholder value of 0, one can use the following code:

<code class="python">import itertools
np.array(list(itertools.zip_longest(*v, fillvalue=0))).T</code>
Copy after login

The output of this code will be a NumPy array of type int32, with missing values replaced by 0:

array([[1, 0],
       [1, 2]])
Copy after login

This method provides an efficient way to handle variable-length lists when converting them to NumPy arrays, ensuring data type consistency and filling missing values with desired placeholders.

The above is the detailed content of How to Create a Dense NumPy Array from Variable-Length Lists?. 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!