Skip to content Skip to sidebar Skip to footer

2d List To Numpy Array, And Fill Remaining Values Of Shorter Sublists With -1

I have a 2-D list of sublists of different lengths, I need to covert the list to a numpy array such that all the remaining values of shorter sublists are filled with -1, and I am l

Solution 1:

Some speed improvements to your original solution:

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 inenumerate(x):
    for j, ele inenumerate(row):
        new_array[i, j] = ele

Timings:

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

deff1(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)) * -1for i, row inenumerate(x):
        for j, ele inenumerate(row):
            new_array[i, j] = ele
    return new_array

deff2(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 inenumerate(x):
        for j, ele inenumerate(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

Post a Comment for "2d List To Numpy Array, And Fill Remaining Values Of Shorter Sublists With -1"