The standard conversion of a Python sequence containing variable-length lists into a NumPy array creates an object-type array. Enforcing another data type raises a ValueError. This article demonstrates an efficient method to generate a dense NumPy array of type int32 by filling missing values with a placeholder.
To convert a variable-length list-sequence into a NumPy array, one can utilize the itertools.zip_longest function from the itertools module. This function iterates through the lists, stopping when the shortest list is exhausted. It fills missing values in longer lists with a placeholder value specified by the fillvalue argument.
For instance, consider the following sequence of variable-length lists:
v = [[1], [1, 2]]
To generate a dense NumPy array from this sequence, with a placeholder value of 0, one can use the following code:
<code class="python">import itertools np.array(list(itertools.zip_longest(*v, fillvalue=0))).T</code>
The output of this code will be a NumPy array of type int32, with missing values replaced by 0:
array([[1, 0], [1, 2]])
This method provides an efficient way to handle variable-length lists when converting them to NumPy arrays, ensuring data type consistency and filling missing values with desired placeholders.
The above is the detailed content of How to Create a Dense NumPy Array from Variable-Length Lists?. For more information, please follow other related articles on the PHP Chinese website!