Search code examples
pythonpython-3.xnumpypython-3.7

Adding a flat list from a list of list into a fixed length numpy array


I'm trying to add a flat list from a list of list into a fixed length numpy array.

import numpy as np

def extract_foo(x):
    return x.size


def extract_foo_of_foo(x):
    return [x.size for _ in range(18)]


def extract_feats():
    input_array = np.ones((36,))
    output_matrix = np.empty((36, 22))

    for x_idx, x_val in enumerate(input_array):
        output_matrix[x_idx] = [
            extract_foo(x_val),
            extract_foo(x_val),
            extract_foo(x_val),
            extract_foo(x_val),

            # this is where I want to flatten my list
            # that one is a list of list containing 22 - 4 = 18 lists
            extract_foo_of_foo(x_val)
        ]

    return output_matrix

I have tried a list comprehension as follow :

[y for y in extract_foo_of_foo(x_val)]

And with reduce function :

reduce(lambda y: y, extract_foo_of_foo(x_val))

I am using numpy 1.17.4 and python 3.7.5. Is there a pythonic way to handle this ?


Solution

  • If I understand your question correctly, I believe you can use slice indexing on the second axis like this:

    def extract_feats():
        input_array = np.ones((36,))
        output_matrix = np.empty((36, 22))
        for x_idx, x_val in enumerate(input_array):
            output_matrix[x_idx, 0:4] = [
                extract_foo(x_val),
                extract_foo(x_val),
                extract_foo(x_val),
                extract_foo(x_val)
            ]
            output_matrix[x_idx, 4:22] = extract_foo_of_foo(x_val)
        return output_matrix
    

    Here's the shape of the output:

    >>> extract_feats().shape
    (36, 22)