[Python] How to broadcast operation to Numpy array of objects?

Discussão em 'Python' iniciado por Stack, Maio 27, 2025.

  1. Stack

    Stack Membro Participativo

    Say I have a Numpy array of 500 lists with random sizes ranging from 0 to 9:

    import numpy as np
    a = np.array([[i for i in range(np.random.randint(10))] for _ in range(500)], dtype=object)


    Now I want to append a value 100 to indices [0,10,20,30,40,50], I tried to apply a function to each list in the array:

    func = np.vectorize(lambda x: x + [100])
    a[[0,10,20,30,40,50]] = func(a[[0,10,20,30,40,50]])


    but I get ValueError: setting an array element with a sequence.

    Is there any way I can broadcast operations to all objects (with different sizes) in a Numpy array? In my case I usually have up to ~50,000 indices. Using a normal for loop would be too slow. I'm thinking maybe converting the array to a sparse matrix with equal sizes of rows if it's more efficient that way?

    Continue reading...

Compartilhe esta Página