Skip to content

Array Operations

Array Operations

Mathematical operations can be completed using NumPy arrays.

Scalar Addition

Scalars can be added and subtracted from arrays and arrays can be added and subtracted from each other:

In [1]:
import numpy as np

a = np.array([1, 2, 3]) b = a + 2 print(b)

[3 4 5]

In [2]:
a = np.array([1, 2, 3])
b = np.array([2, 4, 6])
c = a + b
print(c)

[3 6 9]

Scalar Multiplication

NumPy arrays can be multiplied and divided by scalar integers and floats:

In [3]:
a = np.array([1,2,3])
b = 3*a
print(b)

[3 6 9]

In [4]:
a = np.array([10,20,30])
b = a/2
print(b)

[ 5. 10. 15.]

Array Multiplication

NumPy array can be multiplied by each other using matrix multiplication. These matrix multiplication methods include element-wise multiplication, the dot product, and the cross product.

Element-wise Multiplication

The standard multiplication sign in Python * produces element-wise multiplication on NumPy arrays.

In [5]:
a = np.array([1, 2, 3])
b = np.array([4, 5, 6])
a * b

Out[5]:
array([ 4, 10, 18])

Dot Product

In [6]:
a = np.array([1, 2, 3])
b = np.array([4, 5, 6])
np.dot(a,b)

Out[6]:
32

Cross Product

In [7]:
a = np.array([1, 2, 3])
b = np.array([4, 5, 6])
np.cross(a, b)

Out[7]:
array([-3,  6, -3])

Exponents and Logarithms

np.exp()

NumPy's np.exp() function produces element-wise e^x exponentiation.

In [8]:
a = np.array([1, 2, 3])
np.exp(a)

Out[8]:
array([ 2.71828183,  7.3890561 , 20.08553692])

Logarithms

NumPy has three logarithmic functions.

  • np.log() - natural logarithm (log base e)
  • np.log2() - logarithm base 2
  • np.log10() - logarithm base 10
In [9]:
np.log(np.e)
Out[9]:
1.0
In [10]:
np.log2(16)
Out[10]:
4.0
In [11]:
np.log10(1000)
Out[11]:
3.0

Trigonometry

NumPy also contains all of the standard trigonometry functions which operate on arrays.

  • np.sin() - sin
  • np.cos() - cosine
  • np.tan() - tangent
  • np.asin() - arc sine
  • np.acos() - arc cosine
  • np.atan() - arc tangent
  • np.hypot() - given sides of a triangle, returns hypotenuse
In [12]:
import numpy as np
np.set_printoptions(4)

a = np.array([0, np.pi/4, np.pi/3, np.pi/2])
print(np.sin(a))
print(np.cos(a))
print(np.tan(a))
print(f"Sides 3 and 4, hypotenuse {np.hypot(3,4)}")
[0.     0.7071 0.866  1.    ]
[1.0000e+00 7.0711e-01 5.0000e-01 6.1232e-17]
[0.0000e+00 1.0000e+00 1.7321e+00 1.6331e+16]
Sides 3 and 4, hypotenuse 5.0

NumPy contains functions to convert arrays of angles between degrees and radians.

  • deg2rad() - convert from degrees to radians
  • rad2deg() - convert from radians to degrees
In [13]:
a = np.array([np.pi,2*np.pi])
np.rad2deg(a)
Out[13]:
array([180., 360.])
In [14]:
a = np.array([0,90, 180, 270])
np.deg2rad(a)
Out[14]:
array([0.    , 1.5708, 3.1416, 4.7124])