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

Linda Hamilton
Release: 2024-11-04 11:37:30
Original
676 people have browsed it

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>
Copy after login

Output:

array([[1], [1, 2]], dtype=object)
Copy after login

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

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

Exception:

ValueError: setting an array element with a sequence.
Copy after login

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>
Copy after login

Output:

array([[1, 0],
       [1, 2]])
Copy after login

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!

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!