转换和垫清单,numpy的数组 [英] Convert and pad a list to numpy array

查看:156
本文介绍了转换和垫清单,numpy的数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个任意深度嵌套的列表中,用不同的元素的长度

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]]]

我想将其转换为有效的数字(不反对)numpy的阵列,通过浸轧出与NaN的每个轴。所以结果应该看起来像

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?

推荐答案

这适用于你的样品,不知道它能够妥善处理所有的角落情况:

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)

和现在:

>>> 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]]])

我想这大概是什么numpy的形状发现程序做的。由于有大量涉及Python函数调用,无论如何,它可能不会是比较严重对抗C实现。

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.

这篇关于转换和垫清单,numpy的数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆