[Python] How does numpy handle array and tuple addition?

Discussão em 'Python' iniciado por Stack, Março 1, 2025.

  1. Stack

    Stack Membro Participativo

    The beginning of the problem:

    I am trying to learn about the broadcast mechanism in numpy when adding two arrays. I created two arrays, with a.shape == (4,3) and b.shape == (3,). I wanted to print the shape of the result when adding, but instead of (a + b).shape I wrote a + b.shape, which is equivalent to a + (3,).

    import numpy as np

    a = np.array([[0,0,0],[10,10,10],[20,20,20],[30,30,30]]) # shape=(4,3), ndim=2
    b = np.array([1,2,3]) # shape=(3,), ndim=1

    print("(a+b).shape:", (a + b).shape) # intended output

    print("a + b.shape:\n", a + b.shape) # unintended output


    The output of the above code is:

    (a+b).shape: (4, 3)
    a + b.shape:
    [[ 3 3 3]
    [13 13 13]
    [23 23 23]
    [33 33 33]]


    My thoughts:

    I took a closer look at numpy's documentation based on the suggestions of my friends, Where The add function description "The + operator can be used as a shorthand for np.add on ndarrays. "means that the + operator is actually used in NumPy for ndarray objects np.add function. You can use + directly to perform array addition without explicitly calling the np.add function. Specifically, both sides of the + operator do not have to be ndarray, but when at least one side is ndarray, the other side is automatically converted to ndarray. numpy can compute the array_like of a shape, that is, the Series or DataFrame of ndarray, list, tuple, Pandas, etc. And any other object that can be converted to a NumPy array can be added. So we didn't make a mistake when we incorrectly evaluated the tuple (3,) with a ndarray.

    My question:

    How does numpy handle this operation between an ndarray and a tuple, is there an implicit type conversion or something? I looked it up and it showed that "add in numpy.core.umath is actually executed by ufunc implemented in C" I wanted to know the code So let's take the example of the addition of tuples and ndarray, and I want to know how numpy handles the addition process internally.

    Continue reading...

Compartilhe esta Página