[Python] What is this numpy array [[], :] syntax and what does it do?

Discussão em 'Python' iniciado por Stack, Julho 3, 2025.

  1. Stack

    Stack Membro Participativo

    A = numpy.array([[0.1, 0.2, 0.3],
    [0.4, 0.5, 0.6],
    [0.7,0.8,0.9]]) # Shape: (3,3)
    B = numpy.array([2,1,0,1,2,0,2,0,1]) # SHape (9,)
    C = A[B, :]


    The array C has shape (9,3) and contains:

    [[0.7 0.8 0.9]
    [0.4 0.5 0.6]
    [0.1 0.2 0.3]
    [0.4 0.5 0.6]
    [0.7 0.8 0.9]
    [0.1 0.2 0.3]
    [0.7 0.8 0.9]
    [0.1 0.2 0.3]
    [0.4 0.5 0.6]]


    What is this numpy syntax C = A[B, :] called and what does it do? It seems to automagically use B as index into A, take the value and add it into C

    Continue reading...

Compartilhe esta Página