2

長さの異なるサブリストの 2 次元リストがあり、リストを numpy 配列に変換して、短いサブリストの残りのすべての値が -1 で満たされるようにする必要があります。これを行う効率的な方法を探しています。

たとえば、2 次元リスト x があります。

x = [
    [0,2,3],
    [],
    [4],
    [5,6]]

次のようなnumpy配列を取得したい:

>>> array_x
array([[ 0,  2,  3],
       [-1, -1, -1],
       [ 4, -1, -1],
       [ 5,  6, -1]]) 

これを行う基本的な方法は、次のように、-1 の配列を作成し、2D リストをループして残りの値を埋めることです。

n_rows = len(x)
n_cols = max(len(ele) for ele in x)

new_array = np.ones((n_rows, n_cols)) * -1

for i, row in enumerate(x):
    for j, ele in enumerate(row):
        new_array[i, j] = ele

しかし、より効率的な解決策はありますか?

4

1 に答える 1

3

元のソリューションに対する速度の改善:

n_rows = len(x)
n_cols = max(map(len, x))

new_array = np.empty((n_rows, n_cols))
new_array.fill(-1)
for i, row in enumerate(x):
    for j, ele in enumerate(row):
        new_array[i, j] = ele

タイミング:

import numpy as np
from timeit import timeit
from itertools import izip_longest

def f1(x, enumerate=enumerate, max=max, len=len):
    n_rows = len(x)
    n_cols = max(len(ele) for ele in x)

    new_array = np.ones((n_rows, n_cols)) * -1
    for i, row in enumerate(x):
        for j, ele in enumerate(row):
            new_array[i, j] = ele
    return new_array

def f2(x, enumerate=enumerate, max=max, len=len, map=map):
    n_rows = len(x)
    n_cols = max(map(len, x))

    new_array = np.empty((n_rows, n_cols))
    new_array.fill(-1)
    for i, row in enumerate(x):
        for j, ele in enumerate(row):
            new_array[i, j] = ele

    return new_array

setup = '''x = [[0,2,3],
    [],
    [4],
    [5,6]]
from __main__ import f1, f2'''

print timeit(stmt='f1(x)', setup=setup, number=100000)
print timeit(stmt='f2(x)', setup=setup, number=100000)

>>> 
2.01299285889
0.966173887253
于 2013-05-17T02:45:40.193 に答える