将锯齿状列表转换为numpy数组



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

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

如何做到这一点?

您可能会认为,您的输入是一个元组列表。然而,它是一个整数和元组的列表。(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]]

最新更新