7.9 Universal Functions

  • Standalone universal functions (ufuncs) perform element-wise operations using one or two array or array-like arguments (like lists)
  • Each returns a new array containing the results
  • Some ufuncs are called when you use array operators like + and *
  • Create an array and calculate the square root of its values, using the sqrt universal function
In [1]:
import numpy as np
In [2]:
numbers = np.array([1, 4, 9, 16, 25, 36])
In [3]:
np.sqrt(numbers)
Out[3]:
array([1., 2., 3., 4., 5., 6.])
  • Add two arrays with the same shape, using the add universal function
  • Equivalent to:
    numbers + numbers2
    
In [4]:
numbers2 = np.arange(1, 7) * 10
In [5]:
numbers2
Out[5]:
array([10, 20, 30, 40, 50, 60])
In [6]:
np.add(numbers, numbers2)
Out[6]:
array([11, 24, 39, 56, 75, 96])

Broadcasting with Universal Functions

  • Universal functions can use broadcasting, just like NumPy array operators
In [7]:
np.multiply(numbers2, 5)
Out[7]:
array([ 50, 100, 150, 200, 250, 300])
In [8]:
numbers3 = numbers2.reshape(2, 3)
In [9]:
numbers3
Out[9]:
array([[10, 20, 30],
       [40, 50, 60]])
In [10]:
numbers4 = np.array([2, 4, 6])
In [11]:
np.multiply(numbers3, numbers4)
Out[11]:
array([[ 20,  80, 180],
       [ 80, 200, 360]])

Other Universal Functions

NumPy universal functions
Mathadd, subtract, multiply, divide, remainder, exp, log, sqrt, power, and more.
Trigonometrysin, cos, tan, hypot, arcsin, arccos, arctan, and more.
Bit manipulationbitwise_and, bitwise_or, bitwise_xor, invert, left_shift and right_shift.
Comparisongreater, greater_equal, less, less_equal, equal, not_equal, logical_and, logical_or, logical_xor, logical_not, minimum, maximum, and more.
Floating pointfloor, ceil, isinf, isnan, fabs, trunc, and more.

©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.