I have an array
x = [1500, 1049.8, 34, 351, etc]
How can I take log_10() of the entire array?
numpy will do that for you.
import numpy
numpy.log10(mat)
Note
mat
does not have to be a numpy array for this to work, and numpy
should be faster than using a list comprehension as other answers suggest.
from math import log
[log(y,10) for y in x]
The simpliest way is to use a list comprehension
Example:
>>> x = [1500, 1049.8, 34, 351]
>>> import math
>>> [math.log10(i) for i in x]
[3.1760912590556813, 3.021106568432122, 1.5314789170422551, 2.545307116465824]
>>>
Another way is to use the map function
Example:
>>> map(math.log10, x)
[3.1760912590556813, 3.021106568432122, 1.5314789170422551, 2.545307116465824]
>>>
You could also use the map
builtin function:
import math
new_list = map(math.log10, old_list)
This will probably be insignificantly faster than the list comprehension. I add it here mainly to show the similarity between the two.
EDIT (in response to the comment by @HankGay)
To prove that map is slightly faster in this case, I've written a small benchmark:
import timeit
for i in range(10):
t=timeit.timeit("map(math.log10,a)",setup="import math; a=range(1,100)")
print "map",t
t=timeit.timeit("[math.log10(x) for x in a]",setup="import math; a=range(1,100)")
print "list-comp",t
Here are the results on my laptop (OS-X 10.5.8, CPython 2.6):
map 24.5870189667
list-comp 32.556563139
map 23.2616219521
list-comp 32.0040669441
map 23.9995992184
list-comp 33.2653431892
map 24.1171340942
list-comp 33.0399811268
map 24.3114480972
list-comp 33.5015368462
map 24.296754837
list-comp 33.5107491016
map 24.0294749737
list-comp 33.5332789421
map 23.7013399601
list-comp 33.1543111801
map 24.41685009
list-comp 32.9259850979
map 24.1111209393
list-comp 32.9298729897
It is important to realize that speed isn't everything though. "readability matters". If map
creates something that is harder to read, definitely go for a list comprehension.
import math
x = [1500, 1049.8, 34, 351]
y = [math.log10(num) for num in x]
This is called a list comprehension. What it is doing is creating a new list whose elements are the results of applying math.log10
to the corresponding element in the original list
, which is not an array
, btw.