Skip to content Skip to sidebar Skip to footer

Convert And Pad A List To Numpy Array

I have an arbitrarily deeply nested list, with varying length of elements my_list = [[[1,2],[4]],[[4,4,3]],[[1,2,1],[4,3,4,5],[4,1]]] I want to convert this to a valid numeric (no

Solution 1:

This works on your sample, not sure it can handle all the corner cases properly:

from itertools import izip_longest

def find_shape(seq):
    try:
        len_ = len(seq)
    except TypeError:
        return ()
    shapes = [find_shape(subseq) for subseq in seq]
    return (len_,) + tuple(max(sizes) for sizes in izip_longest(*shapes,
                                                                fillvalue=1))

def fill_array(arr, seq):
    if arr.ndim == 1:
        try:
            len_ = len(seq)
        except TypeError:
            len_ = 0
        arr[:len_] = seq
        arr[len_:] = np.nan
    else:
        for subarr, subseq in izip_longest(arr, seq, fillvalue=()):
            fill_array(subarr, subseq)

And now:

>>> arr = np.empty(find_shape(my_list))
>>> fill_array(arr, my_list)
>>> arr
array([[[  1.,   2.,  nan,  nan],
        [  4.,  nan,  nan,  nan],
        [ nan,  nan,  nan,  nan]],

       [[  4.,   4.,   3.,  nan],
        [ nan,  nan,  nan,  nan],
        [ nan,  nan,  nan,  nan]],

       [[  1.,   2.,   1.,  nan],
        [  4.,   3.,   4.,   5.],
        [  4.,   1.,  nan,  nan]]])

I think this is roughly what the shape discovery routines of numpy do. Since there are lots of Python function calls involved anyway, it probably won't compare that badly against the C implementation.


Solution 2:

First of all, count the lengths of a column and row:

len1 = max((len(el) for el in my_list))
len2 = max(len(el) for el in list(chain(*my_list)))

Second, append missing nans:

for el1 in my_list:
    el1.extend([[]]*(len1-len(el1)))
    for el2 in el1:
        el2.extend([numpy.nan] * (len2-len(el2)))

Post a Comment for "Convert And Pad A List To Numpy Array"