Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert list or numpy array of single element to float in python

I have a function which can accept either a list or a numpy array.

In either case, the list/array has a single element (always). I just need to return a float.

So, e.g., I could receive:

list_ = [4] 

or the numpy array:

array_ = array([4]) 

And I should return

 4.0 

So, naturally (I would say), I employ float(...) on list_ and get:

TypeError: float() argument must be a string or a number 

I do the same to array_ and this time it works by responding with "4.0". From this, I learn that Python's list cannot be converted to float this way.

Based on the success with the numpy array conversion to float this lead me to the approach:

float(np.asarray(list_)) 

And this works when list_ is both a Python list and when it is a numpy array.

Question

But it seems like this approach has an overhead first converting the list to a numpy array and then to float. Basically: Is there a better way of doing this?

like image 590
jesperk.eth Avatar asked May 18 '15 19:05

jesperk.eth


People also ask

Can you convert NumPy array to list in Python?

We can use NumPy np. array tolist() function to convert an array to a list. If the array is multi-dimensional, a nested list is returned. For a one-dimensional array, a list with the array elements is returned.

How do you convert to float in Python?

We can convert a string to float in Python using the float() function. This is a built-in function used to convert an object to a floating point number. Internally, the float() function calls specified object __float__() function.

How do I convert a NumPy array to a list?

We can convert the Numpy array to the list by tolist() method, we can have a list of data element which is converted from an array using this method. Returns: The possibly nested list of array elements.


1 Answers

Just access the first item of the list/array, using the index access and the index 0:

>>> list_ = [4] >>> list_[0] 4 >>> array_ = np.array([4]) >>> array_[0] 4 

This will be an int since that was what you inserted in the first place. If you need it to be a float for some reason, you can call float() on it then:

>>> float(list_[0]) 4.0 
like image 156
poke Avatar answered Sep 20 '22 16:09

poke