Home  >  Article  >  Backend Development  >  How to Efficiently Convert Variable-Length Python Sequences to Dense NumPy Arrays?

How to Efficiently Convert Variable-Length Python Sequences to Dense NumPy Arrays?

Susan Sarandon
Susan SarandonOriginal
2024-11-06 02:59:021068browse

How to Efficiently Convert Variable-Length Python Sequences to Dense NumPy Arrays?

Efficiently Converting Variable-Length Python Sequences to Dense NumPy Arrays

Converting Python sequences into NumPy arrays is straightforward. However, when dealing with variable-length lists, the implicit conversion results in arrays of type object, which may not be optimal. Moreover, enforcing a specific data type can lead to exceptions.

One efficient solution to this problem is to use the itertools.zip_longest function. By utilizing zip_longest, one can easily create a sequence of tuples with missing values filled using a placeholder value. By transposing the resulting list, a dense NumPy array of the desired data type can be obtained.

For example, consider the sequence v = [[1], [1, 2]].

<code class="python">import itertools
np.array(list(itertools.zip_longest(*v, fillvalue=0))).T
Out:
array([[1, 0],
       [1, 2]])</code>

Here, the fillvalue of 0 is used to fill the missing values in the shorter list.

For Python 2 compatibility, use itertools.izip_longest instead. This approach is efficient and provides a simple way to convert variable-length Python sequences into dense NumPy arrays, ensuring type safety and optimal performance.

The above is the detailed content of How to Efficiently Convert Variable-Length Python Sequences to Dense NumPy Arrays?. 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