Arithmetic Operations with arrays and Individual Numeric Values

7.7 array Operators

  • array operators perform operations on entire arrays.
  • Can perform arithmetic between arrays and scalar numeric values, and between arrays of the same shape.
In [1]:
import numpy as np
In [2]:
numbers = np.arange(1, 6)
In [3]:
numbers
Out[3]:
array([1, 2, 3, 4, 5])
In [4]:
numbers * 2
Out[4]:
array([ 2,  4,  6,  8, 10])
In [5]:
numbers ** 3
Out[5]:
array([  1,   8,  27,  64, 125])
In [6]:
numbers  # numbers is unchanged by the arithmetic operators
Out[6]:
array([1, 2, 3, 4, 5])
In [7]:
numbers += 10
In [8]:
numbers
Out[8]:
array([11, 12, 13, 14, 15])

Broadcasting

  • Arithmetic operations require as operands two arrays of the same size and shape.
  • numbers * 2 is equivalent to numbers * [2, 2, 2, 2, 2] for a 5-element array.
  • Applying the operation to every element is called broadcasting.
  • Also can be applied between arrays of different sizes and shapes, enabling some concise and powerful manipulations.

Arithmetic Operations Between arrays

  • Can perform arithmetic operations and augmented assignments between arrays of the same shape
In [9]:
numbers2 = np.linspace(1.1, 5.5, 5)
In [10]:
numbers2
Out[10]:
array([1.1, 2.2, 3.3, 4.4, 5.5])
In [11]:
numbers * numbers2
Out[11]:
array([12.1, 26.4, 42.9, 61.6, 82.5])

Comparing arrays

  • Can compare arrays with individual values and with other arrays
  • Comparisons performed element-wise
  • Produce arrays of Boolean values in which each element’s True or False value indicates the comparison result
In [12]:
numbers
Out[12]:
array([11, 12, 13, 14, 15])
In [13]:
numbers >= 13
Out[13]:
array([False, False,  True,  True,  True])
In [14]:
numbers2
Out[14]:
array([1.1, 2.2, 3.3, 4.4, 5.5])
In [15]:
numbers2 < numbers
Out[15]:
array([ True,  True,  True,  True,  True])
In [16]:
numbers == numbers2
Out[16]:
array([False, False, False, False, False])
In [17]:
numbers == numbers
Out[17]:
array([ True,  True,  True,  True,  True])

©1992–2020 by Pearson Education, Inc. All Rights Reserved. This content is based on Chapter 5 of the book Intro to Python for Computer Science and Data Science: Learning to Program with AI, Big Data and the Cloud.

DISCLAIMER: The authors and publisher of this book have used their best efforts in preparing the book. These efforts include the development, research, and testing of the theories and programs to determine their effectiveness. The authors and publisher make no warranty of any kind, expressed or implied, with regard to these programs or to the documentation contained in these books. The authors and publisher shall not be liable in any event for incidental or consequential damages in connection with, or arising out of, the furnishing, performance, or use of these programs.