Log Transformations in Python

It is very simple to do a log transformation in Python. Log transformations are sometimes performed on a set of numbers to smooth out the data (make it look more “Normal”), which can help in performing certain statistical analyses.

The default in Python is the natural log. So for demonstration purposes, I will first find e^10. Then I will convert it back to 10 by taking the natural log.

1
2
3
4
5
6
import math
x = math.exp(10)
print x
// 22026.465794806718
print math.log(x)
// 10.0

But you can also do log transformations in other bases. The following example does a base-2 log transformation.

1
2
3
4
5
6
import math
x = 2**3
print x
// 8.0
print math.log(x, 2)
// 2.0

For base-10 logarithms, it can be done in two different ways (passing a base parameter to the log function or invoking a custom function built into Python).

1
2
3
4
5
6
7
8
import math
x = 10**5
print x
// 100000
print math.log(x, 10)
// 5.0
print math.log10(x)
// 5.0

Leave a Reply