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!