Home  >  Article  >  Backend Development  >  How to Convert Variable-Length Python Lists to a Dense NumPy Array with Placeholders?

How to Convert Variable-Length Python Lists to a Dense NumPy Array with Placeholders?

Barbara Streisand
Barbara StreisandOriginal
2024-11-03 22:03:03455browse

How to Convert Variable-Length Python Lists to a Dense NumPy Array with Placeholders?

Efficiently Convert Python Variable-Length Lists to a Dense NumPy Array

The direct conversion of variable-length Python lists into a NumPy array results in an array of type "object," which can be undesirable. Alternatively, attempting to force a specific type using np.array(v, dtype=np.int32) leads to an exception due to the presence of sequences in the array.

Therefore, to create a dense NumPy array of a specific data type (e.g., int32) while filling missing values with a placeholder, you can leverage the itertools.zip_longest function.

For example, considering the input sequence v = [[1], [1, 2]], using itertools.zip_longest with a placeholder of 0, you can efficiently obtain a dense NumPy array as follows:

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

This will produce the desired output:

array([[1, 0],
       [1, 2]])

Note that for Python 2, use itertools.izip_longest instead.

The above is the detailed content of How to Convert Variable-Length Python Lists to a Dense NumPy Array with Placeholders?. 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