In mathematics, logarithmic functions are widely used to analyze and interpret data that vary exponentially over time or space. NumPy is a popular library that provides efficient tools for working with multidimensional arrays in Python. In this article, we will explore how to apply logarithmic functions to all elements of a 2D NumPy array using various methods which are mentioned below:
1. Using “np.power()” function:
- imports the NumPy library and creates a 2D NumPy array.
- then sets the base value to 2 and applies the logarithmic function with base 2 to the array using the
np.power()
function. - The resulting array is printed to the console.
- This code calculates the exponentiation of base 2 to the elements of the input array.
2. Using a “for loop”:
- imports the NumPy library and creates a 2D NumPy array.
- then creates an empty NumPy array with the same shape as the input array.
- code loops through every element in the input array and applies the natural logarithm using the
np.log()
function, and stores the result in the empty array. - Finally, the resulting array is printed to the console.
- can also use
np.log2()
andnp.log10()
forlogarithm with base 2 and 10
respectively. - This code calculates the natural logarithm of the elements of the input array using a
for loop
.
3. Using “np.vectorize()” function:
- imports the NumPy library and creates a 2D NumPy array.
- then creates a “log base 10 function using lambda functions” with the
np.vectorize()
function. - code applies the lambda function to the input array using the created function and stores the result in the same array.
- Finally, the resulting array is printed to the console.
- can also use
np.log() (natural log)
ornp.log2() (log base 2)
as well. - This code calculates the
logarithm base 10
of the elements of the input array using alambda
function and thenp.vectorize()
function.