Home  >  Article  >  Backend Development  >  How to Convert a Python Sequence to a NumPy Array with Missing Values Filled?

How to Convert a Python Sequence to a NumPy Array with Missing Values Filled?

Linda Hamilton
Linda HamiltonOriginal
2024-11-04 11:37:30677browse

How to Convert a Python Sequence to a NumPy Array with Missing Values Filled?

Convert Python Sequence to NumPy Array with Missing Values Filled

When converting a Python sequence of variable-length lists to a NumPy array, an implicit conversion to an object type array occurs.

<code class="python">v = [[1], [1, 2]]
np.array(v)</code>

Output:

array([[1], [1, 2]], dtype=object)

Enforcing a specific data type, such as int32, will result in an exception:

<code class="python">np.array(v, dtype=np.int32)</code>

Exception:

ValueError: setting an array element with a sequence.

To obtain a dense NumPy array of int32 type with missing values filled with a placeholder, you can utilize itertools.zip_longest:

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

Output:

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

Note that in Python 2, itertools.izip_longest should be used instead.

The above is the detailed content of How to Convert a Python Sequence to a NumPy Array with Missing Values Filled?. 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