[Python] numpy element-by-element subtract

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

  1. Stack

    Stack Membro Participativo

    I have two numpy 'arrays': 1st is a 2D array with shape (N, 2) 2nd is a 3D "matrix" with shape (N, M, 2) where M can be different from 0 to N-1

    Code example

    import numpy as np

    a = np.array([[1, 2], [3, 4]]) # (N=2,2) shape
    b = np.array([np.array([[1, 2]]), np.array([[1, 2], [3, 4]])], dtype=object) # (N=2,(1,2), 2) shape

    diff = [_ - b for i, _ in enumerate(a)] # <-- this is an expected behavior
    diff1 = a - b

    print(diff) # <-- [array([[0, 0]]), array([[2, 2], [0, 0]])]
    print(diff1) # <-- [[array([[ 0, -1]]) array([[ 1, 0], [-1, -2]])]
    # [array([[ 2, 1]]) array([[ 3, 2], [ 1, 0]])]] ???


    Is it possible to perform element-by-element subtraction in numpy (without loop or list comprehension)?

    It looks like I need something like np.subtract(a, b, axis=0) but np.subtract doesn't understand axis argument.

    Continue reading...

Compartilhe esta Página