Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
208 views
in Technique[技术] by (71.8m points)

python - 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...