Home >Backend Development >Python Tutorial >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?

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
Susan SarandonOriginal
2024-11-04 03:58:01683browse

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!

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