[Python] Numpy array of array into array of length (vectorization)

Discussão em 'Python' iniciado por Stack, Dezembro 7, 2024.

  1. Stack

    Stack Membro Participativo

    I have a numpy array of arrays, where each sub-array represents a group of elements. I want to compute the length of each sub-array and store the result as a new numpy array.

    Currently, I use a standard for loop, but I would like to vectorize this operation for better performance using only numpy.

    Example

    import numpy as np

    indices = np.array([np.array([1, 2, 3]), np.array([4, 5]), np.array([6, 7, 8, 9])], dtype=object)
    group_lengths = np.array([len(group) for group in indices])

    print(group_lengths)


    Expected output

    [3 2 4]

    I am looking for a fully vectorized solution that avoids the explicit loop. How can this be achieved with numpy?

    Update

    Thank you all for your insights and clarifications! I now understand that fully vectorizing my use case isn't possible. I'll stick with my current solution, as it seems to be the most efficient approach given the circumstances.

    Continue reading...

Compartilhe esta Página