[Python] NumPy broadcasting error when trying to add 2D array and 1D array

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

  1. Stack

    Stack Membro Participativo

    I'm trying to perform an element-wise addition between a 2D NumPy array and a 1D array (like adding a row vector to each row of a matrix), but I'm running into a broadcasting error.

    import numpy as np

    # Create a 2D array with shape (3, 4)
    matrix = np.array([
    [1, 2, 3, 4],
    [5, 6, 7, 8],
    [9, 10, 11, 12]
    ])

    # Create a 1D array with shape (3,) – I intended this to be a row vector
    row_vector = np.array([1, 2, 3])

    # Try to add the row vector to each row of the matrix
    result = matrix + row_vector


    When I run, I am getting following error:

    ValueError: operands could not be broadcast together with shapes (3,4) (3,)

    Any Ideas?

    I thought NumPy would automatically broadcast the 1D array across the rows, but it doesn’t work here.

    I tried reshaping the row_vector but not sure what the correct shape should be.

    Looked at the documentation on broadcasting, but still not fully clear.

    Continue reading...

Compartilhe esta Página