6

I have a list of values and would like to convert it to the log of that list or pass the log of a list to a function. I'm more familiar with R and you can usually throw some () around anything. When I attempt this in Python I get the error:

TypeError: must be real number, not list

List looks like this:

pressures[:5]
Out[11]: [1009.58, 1009.58, 1009.55, 1009.58, 1009.65]

It doesn't really matter where I try to take the log, I get the same error...in a function:

plt.plot(timestamps, log(pressures))
plt.xlabel('Timestamps')
plt.ylabel('Air Pressure')
plt.show()

Whilst parsing data:

pressures = log([record['air_pressure'] for record in data])
Ani Menon
  • 27,209
  • 16
  • 105
  • 126
user974887
  • 2,309
  • 3
  • 17
  • 18

3 Answers3

6

There are a couple of ways to handle this. Python has some basic, built in functions in the math module. One is log. It takes a float or an int as a parameter and outputs a float:

> from math import log
> log(20)
2.995732273553991

To process a list with this function, you'd need to call it on every item in the list:

> data = [1, 2, 3]
> [log(x) for x in data]
[0.0, 0.6931471805599453, 1.0986122886681098]

On the other hand, and I mention this because it looks like you're already using some related libraries, numpy can process an entire list at once.

> import numpy as np
> np.log([1, 2, 3])
array([ 0.        ,  0.69314718,  1.09861229]) # Notice this is a numpy array

If you want to use numpy and get a list back, you could do this instead:

> list(np.log([1, 2, 3]))
[0.0, 0.69314718055994529, 1.0986122886681098]
cwallenpoole
  • 79,954
  • 26
  • 128
  • 166
3

You can only use log() with a single number. So you'll need to write a loop to iterate over your list and apply log() to each number.

Fortunately, you have already written a loop that, with some modification, will do the trick. Instead of:

pressures = log([record['air_pressure'] for record in data])

Write:

pressures = [log(record['air_pressure']) for record in data]
kindall
  • 178,883
  • 35
  • 278
  • 309
  • 2
    If you have a list of `pressures` you want the `log` of already produced, and given `log()` is the complete operation, I'm partial towards `pressures_log = map(log, pressures)`. But it is equivalent to the above. – TemporalWolf Nov 30 '17 at 20:49
2

If you wanted to do logs and you have a list of integers you can use the math lib for that.

import math

my_data = [1,2,3,4,5,6,7,8,9]

log_my_data = [math.log(x) for x in my_data]

print(log_my_data)
Mike Tung
  • 4,735
  • 1
  • 17
  • 24