Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 (not object) numpy array, by padding out each axis with NaN. So the result should look like

padded_list = np.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]]])

How do I do this?

like image 405
siamii Avatar asked Jan 11 '15 17:01

siamii


2 Answers

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.

like image 76
Jaime Avatar answered Nov 17 '22 13:11

Jaime


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)))
like image 33
Andrew_Lvov Avatar answered Nov 17 '22 12:11

Andrew_Lvov