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])
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. 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) .
To convert a list to a string, use Python List Comprehension and the join() function. The list comprehension will traverse the elements one by one, and the join() method will concatenate the list's elements into a new string and return it as output.
Python frozenset object is an immutable unordered collection of data elements. Therefore, you cannot modify the elements of the frozenset. To convert this set into a list, you have to use the list function and pass the set as a parameter to get the list object as an output.
The most Pythonic way to convert a list of strings to a list of floats is to use the list comprehension floats = [float(x) for x in strings] . It iterates over all elements in the list and converts each list element x to a float value using the float(x) built-in function.
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]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With