9

Suppose I have a list contains un-equal length lists.

a = [ [ 1, 2, 3], [2], [2, 4] ]

What is the best way to obtain a zero padding numpy array with standard shape?

zero_a = [ [1, 2, 3], [2, 0, 0], [2, 4, 0] ]

I know I can use list operation like

n = max( map( len, a ) )
map( lambda x : x.extend( [0] * (n-len(x)) ), a )
zero_a = np.array(zero_a)

but I was wondering is there any easy numpy way to do this work?

4

2 回答 2

7

由于 numpy 必须在初始化之前知道数组的大小,因此最好的解决方案是针对这种情况使用基于 numpy 的构造函数。可悲的是,据我所知,没有。

可能不理想,但稍微快一点的解决方案将是创建带有零的 numpy 数组并填充列表值。

import numpy as np
def pad_list(lst):
    inner_max_len = max(map(len, lst))
    map(lambda x: x.extend([0]*(inner_max_len-len(x))), lst)
    return np.array(lst)

def apply_to_zeros(lst, dtype=np.int64):
    inner_max_len = max(map(len, lst))
    result = np.zeros([len(lst), inner_max_len], dtype)
    for i, row in enumerate(lst):
        for j, val in enumerate(row):
            result[i][j] = val
    return result

测试用例:

>>> pad_list([[ 1, 2, 3], [2], [2, 4]])
array([[1, 2, 3],
       [2, 0, 0],
       [2, 4, 0]])

>>> apply_to_zeros([[ 1, 2, 3], [2], [2, 4]])
array([[1, 2, 3],
       [2, 0, 0],
       [2, 4, 0]])

表现:

>>> timeit.timeit('from __main__ import pad_list as f; f([[ 1, 2, 3], [2], [2, 4]])', number = 10000)
0.3937079906463623
>>> timeit.timeit('from __main__ import apply_to_zeros as f; f([[ 1, 2, 3], [2], [2, 4]])', number = 10000)
0.1344289779663086
于 2013-11-09T17:56:33.793 回答
2

严格来说不是 numpy 的函数,但你可以做这样的事情

from itertools import izip, izip_longest
import numpy
a=[[1,2,3], [4], [5,6]]
res1 = numpy.array(list(izip(*izip_longest(*a, fillvalue=0))))

或者,或者:

res2=numpy.array(list(izip_longest(*a, fillvalue=0))).transpose()

如果您使用 python 3,请使用zipitertools.zip_longest.

于 2013-11-09T18:07:40.207 回答