How can I create a dense NumPy array with a specific data type and filled-in missing values from a sequence of variable-length lists?

Susan Sarandon
Release: 2024-11-04 03:58:01
Original
591 people have browsed it

How can I create a dense NumPy array with a specific data type and filled-in missing values from a sequence of variable-length lists?

Filling Missing Values in NumPy Array Conversion

When converting a Python sequence of variable-length lists to a NumPy array, the resulting array often assumes an object data type due to the varying lengths of the lists. Enforcing a specific data type, such as int32, can lead to errors.

To efficiently obtain a dense NumPy array with a specific data type and filled-in missing values, the itertools module can be employed. Specifically, the zip_longest function can be used to pad the lists with a placeholder value.

For example, given a sequence v:

To create a dense int32 array with zeros as the placeholder:

This code produces:

where the missing values in the original sequence are filled with zeros. Notably, for Python 2, the function to use is itertools.izip_longest.

The above is the detailed content of How can I create a dense NumPy array with a specific data type and filled-in missing values from a sequence of 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!