NumPy ufunc Logs
NumPy's log ufuncs compute natural, base-2, and base-10 logarithms across whole arrays, and frompyfunc lets you wrap a custom-base logarithm into a ufunc of your own.
Logarithms as NumPy ufuncs
Logarithms show up constantly in data work: measuring information content, scaling wide-ranging data, or analyzing algorithmic growth. NumPy exposes them as ufuncs so they apply to an entire array at once, without a Python-level loop.
Natural, Base-2, and Base-10 Logs
np.log() computes the natural logarithm (base e). np.log2() computes the base-2 logarithm, common in computer science and information theory. np.log10() computes the base-10 logarithm, useful for orders of magnitude such as decibels or the Richter scale.
Example
import numpy as np
values = np.array([1, 2, 8, 100, np.e])
print(np.log(values)) # natural log (base e)
print(np.log2(values)) # base-2 log
print(np.log10(values)) # base-10 logBuilding a Custom Base Logarithm
NumPy has no built-in ufunc for an arbitrary base, but np.frompyfunc(function, nin, nout) can turn any plain Python function into a NumPy ufunc that broadcasts over arrays element-wise, complete with automatic support for arrays of any shape.
Example
import numpy as np
import math
def log_base(x, base):
return math.log(x, base)
# frompyfunc(function, number_of_inputs, number_of_outputs)
custom_log = np.frompyfunc(log_base, 2, 1)
values = np.array([8, 27, 625])
bases = np.array([2, 3, 5])
result = custom_log(values, bases)
print(result)
# [3.0 3.0 4.0]- frompyfunc always returns an array with dtype=object, even when every result happens to be numeric.
- Because it calls back into Python for every element, it is much slower than native ufuncs like np.log for large arrays.
- You specify the number of inputs (nin) and outputs (nout) explicitly, so frompyfunc can wrap functions that take more than one argument, like a value and a base.
- It is best used for prototyping a custom operation before writing a faster fully-vectorized version.
Example
import numpy as np
def log_any_base(x, base):
# Change-of-base formula: log_b(x) = ln(x) / ln(b)
return np.log(x) / np.log(base)
values = np.array([8, 27, 625, 1024])
print(log_any_base(values, 2))
print(log_any_base(values, 5))Exercise: NumPy ufunc Logs
Which function computes the natural logarithm (base e) of array elements?