Trusted answers to developer questions

Maria Elijah

The Python library `Numpy`

provides us with a method called `subtract()`

. We use this to subtract two arrays.

`numpy.subtract()`

methodThe ** numpy.subtract() method** returns the element-wise (element by element) difference between two arrays.

We can create a two-dimensional (2D) array using a list of lists in Python.

```
numpy.subtract(A, B, dtype=None, out=None)
```

: This is the first input array.`A`

: This is the second input array.`B`

: This is an optional parameter. It represents the return type of the array.`dtype`

: This is an optional parameter. It represents the alternative output array where the result is to be placed.`out`

Note: If`A`

and`B`

have distinct shapes, they must be able to be broadcasted to a common shape for output representation.

The `numpy.subtract()`

method returns the difference between two input arrays, element-wise.

If the `out`

parameter is specified, this method returns an array reference to `out`

.

The following code shows how to use `np.subtract()`

for 2D arrays.

# Import numpy. import numpy as np # Create two 2D arrays. A = np.array([[2,6,5],[3,4,8]]) B = np.array([[1,7,2],[10,9,4]]) # Find the difference between the 2D arrays. # Store the result in arr_diff. arr_diff = np.subtract(A, B) print(arr_diff)

Using np.subtract() for 2D arrays in Python

- Line 2: We import the
`numpy`

library. - Line 4–5: We create two 2D arrays,
`A`

and`B`

. - Line 9: We use the
`np.subtract()`

method to find the difference between the`x1`

and`x2`

arrays. The result is stored in a new variable called`arr_diff`

. - Line 11: We display the result to the console.

RELATED TAGS

python

numpy

CONTRIBUTOR

Maria Elijah

RELATED COURSES

View all Courses

Keep Exploring

Related Courses