Convert list or numpy array of single element to float in python
np.asscalar(a)
is deprecated since NumPy v1.16, use a.item()
instead.
For example:
a = np.array([[0.6813]])
print(a.item())
gives:
0.6813
Use numpy.asscalar to convert a numpy array / matrix a scalar value:
>>> a=numpy.array([[[[42]]]])
>>> numpy.asscalar(a)
42
The output data type is the same type returned by the input’s
item
method.
It has built in error-checking if there is more than an single element:
>>> a=numpy.array([1, 2])
>>> numpy.asscalar(a)
gives:
ValueError: can only convert an array of size 1 to a Python scalar
Note: the object passed to asscalar
must respond to item
, so passing a list or tuple won't work.
You may want to use the ndarray.item
method, as in a.item()
. This is also equivalent to (the now deprecated) np.asscalar(a)
. This has the benefit of working in situations with views and superfluous axes, while the above solutions will currently break. For example,
>>> a = np.asarray(1).view()
>>> a.item() # correct
1
>>> a[0] # breaks
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: too many indices for array
>>> a = np.asarray([[2]])
>>> a.item() # correct
2
>>> a[0] # bad result
array([2])
This also has the benefit of throwing an exception if the array is not actually a scalar, while the a[0]
approach will silently proceed (which may lead to bugs sneaking through undetected).
>>> a = np.asarray([1, 2])
>>> a[0] # silently proceeds
1
>>> a.item() # detects incorrect size
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: can only convert an array of size 1 to a Python scalar
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