Skip to content
Home » numpy Part 13 – Operations on Two numpy Arrays

numpy Part 13 – Operations on Two numpy Arrays

Spread the love

Today we’ll be talking about operations on two numpy arrays.

operations on numpy arrays

It’s pretty easy to perform operations on two numpy arrays. The operations are then performed elementwise, so on elements at the same positions in either array.

Here are some examples:

First let’s define our two arrays:

>>> a = np.array([2, 4, 6, 8, 10])
>>> b = np.array([1, 2, 3, 4, 5])
>>> print(a)
[ 2  4  6  8 10]
>>> print(b)
[1 2 3 4 5]

Let’s start with addition:

>>> c = a + b
>>> print(c)
[ 3  6  9 12 15]

And now let’s see how subtraction works:

>>> d = a - b
>>> print(d)
[1 2 3 4 5]

Here’s multiplication:

>>> e = a * b
>>> print(e)
[ 2  8 18 32 50]

And here’s true division:

>>> f = a / b
>>> print(f)
[2. 2. 2. 2. 2.]

You can also perform the operation of exponentiation:

>>> g = a ** b
>>> print(g)
[     2     16    216   4096 100000]

Your Panda3D Magazine

Make Awesome Games and Other 3D Apps

with Panda3D and Blender using Python.

Cool stuff, easy to follow articles.

Get the magazine here (PDF).

It’s also possible to make complex expressions with both arrays and scalars:

>>> print(5 * a + (b ** 2) - a)
[ 9 20 33 48 65]

Here are some examples with multidimensional arrays:

>>> x = np.array([[2, 4, 6], [3, 6, 9]])
>>> y = np.array([[5, 10, 15], [4, 8, 12]])
>>> print(x)
[[2 4 6]
 [3 6 9]]
>>> print(y)
[[ 5 10 15]
 [ 4  8 12]]
>>> print(x + y)
[[ 7 14 21]
 [ 7 14 21]]
>>> print(x * y)
[[ 10  40  90]
 [ 12  48 108]]

As the operations are performed elementwise, the arrays should have tha same shapes. Otherwise, we get an error:

>>> m = np.array([2, 4, 6, 8])
>>> n = np.array([5, 10])
>>> print(m + n)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: operands could not be broadcast together with shapes (4,) (2,) 

Python Jumpstart Course

Learn the basics of Python, including OOP.

with lots of exercises, easy to follow

The course is available on Udemy.

Blender Jumpstart Course

Learn the basics of 3D modeling in Blender.

step-by-step, easy to follow, visually rich

The course is available on Udemy and on Skillshare.

Here’s the video version of the article:


Spread the love
Tags:

Leave a Reply