RobinCook
RobinCook

Reputation: 43

Python: Take the Log of all elements in a 2D array

I have a 2D numpy array:

>>> arr = np.arange(1,10).reshape((3,3))
array([[0, 1, 2],
       [3, 4, 5],
       [6, 7, 8]])

I wish to take the logarithm of all elements within the array. The following code works but it's a bit clunky

>>> from math import log10 
>>> logArr = np.empty((3,3))
>>> for i in range(3):
...     for j in range(3):
...             logArr[i][j] = log10(arr[i][j])
... 
array([[ 0.        ,  0.30103   ,  0.47712125],
       [ 0.60205999,  0.69897   ,  0.77815125],
       [ 0.84509804,  0.90308999,  0.95424251]])

Does there exist a more efficient/'pythonic' way of doing such an operation?

Upvotes: 2

Views: 5381

Answers (1)

umutto
umutto

Reputation: 7690

There is a numpy function for that, try numpy.log

>>> arr = np.arange(1,10).reshape((3,3))
>>> np.log(arr)
array([[ 0.        ,  0.69314718,  1.09861229],
       [ 1.38629436,  1.60943791,  1.79175947],
       [ 1.94591015,  2.07944154,  2.19722458]])

Or like in your implementation, you can use numpyp.log10 to find the logs in base 10.

>>> np.log10(arr)
array([[ 0.        ,  0.30103   ,  0.47712125],
       [ 0.60205999,  0.69897   ,  0.77815125],
       [ 0.84509804,  0.90308999,  0.95424251]])

Upvotes: 6

Related Questions