【问题标题】:Convert jagged lists into numpy array [duplicate]将锯齿状列表转换为numpy数组[重复]
【发布时间】:2021-08-02 02:16:34
【问题描述】:

我有由不同长度组成的列表(见下文)

[(880),
 (880, 1080),
 (880, 1080, 1080),
 (470, 470, 470, 1250)]

我想将其转换为外观相同的 numpy.array,即使我必须用零填充空格。

例如,它应该如下所示:

[(880, 0, 0, 0),
 (880, 1080, 0, 0),
 (880, 1080, 1080, 0),
 (470, 470, 470, 1250)]

怎么做?

【问题讨论】:

    标签: python arrays list numpy


    【解决方案1】:

    您可能会认为,您的输入是一个元组列表。但是,它是整数和元组的列表。 (880) 将被解释为整数,而不是元组。所以你必须处理这两种数据类型。

    首先,我建议将您的输入数据转换为列表列表。该列表中包含的每个列表都应具有相同的长度,因为数组仅支持常量维度。因此,我会将元素转换为列表并用零填充缺失值(以使所有元素的长度相等)。

    如果我们对输入列表中给定的所有元素执行此操作,我们将创建一个包含等长列表的新列表,该列表可以转换为数组。

    一个非常基本(且容易出错)的方法如下所示:

    import numpy as np
    
    
    original_list = [
        (880),
        (880, 1080),
        (880, 1080, 1080),
        (470, 470, 470, 1250),
    ]
    
    
    def get_len(item):
        try:
            return len(item)
        except TypeError:
            # `(880)` will be interpreted as an int instead of a tuple
            # so we need to handle tuples and integers
            # as integers do not support len(), a TypeError will be raised
            return 1
    
    
    def to_list(item):
        try:
            return list(item)
        except TypeError:
            # `(880)` will be interpreted as an int instead of a tuple
            # so we need to handle tuples and integers
            # as integers do not support __iter__(), a TypeError will be raised
            return [item]
    
    
    def fill_zeros(item, max_len):
        item_len = get_len(item)
        to_fill = [0] * (max_len - item_len)
        as_list = to_list(item) + to_fill
        return as_list
    
    
    max_len = max([get_len(item) for item in original_list])
    filled = [fill_zeros(item, max_len) for item in original_list]
    
    arr = np.array(filled)
    print(arr)
    

    印刷:

    [[ 880    0    0    0]
    [ 880 1080    0    0]
    [ 880 1080 1080    0]
    [ 470  470  470 1250]]
    

    【讨论】:

      猜你喜欢
      • 2013-09-17
      • 2013-06-21
      • 2018-11-05
      • 2018-07-26
      • 2020-12-09
      • 1970-01-01
      • 2021-05-04
      • 1970-01-01
      相关资源
      最近更新 更多