将单个元素的列表或 numpy 数组转换为在 python 中浮动

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/30311172/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 08:12:57  来源:igfitidea点击:

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

pythonarrayslistnumpyfloating-point

提问by denvar

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

我有一个可以接受列表或 numpy 数组的函数。

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:

或 numpy 数组:

array_ = array([4])

And I should return

我应该回来

 4.0

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

所以,自然地(我会说),我在 list_ 上使用 float(...) 并得到:

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.

我对 array_ 做同样的事情,这次它通过响应“4.0”来工作。由此,我了解到 Python 的列表不能以这种方式转换为浮点数。

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

基于 numpy 数组转换为 float 的成功,这使我采用了以下方法:

float(np.asarray(list_))

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

这在 list_ 既是 Python 列表又是 numpy 数组时有效。

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?

但似乎这种方法首先将列表转换为 numpy 数组,然后再转换为浮点数。基本上:有没有更好的方法来做到这一点?

采纳答案by poke

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

只需使用索引访问和索引 0 访问列表/数组的第一项:

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

This will be an intsince 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:

这将是一个int因为那是您首先插入的内容。如果您出于某种原因需要它是一个浮点数,那么您可以调用float()它:

>>> float(list_[0])
4.0

回答by rth

I would simply use,

我会简单地使用,

np.asarray(input, dtype=np.float)[0]
  • If inputis an ndarrayof the right dtype, there is no overhead, since np.asarraydoes nothing in this case.
  • if inputis a list, np.asarraymakes sure the output is of the right type.
  • 如果inputndarray正确的 dtype,则没有开销,因为np.asarray在这种情况下什么都不做。
  • 如果input是 a listnp.asarray确保输出是正确的类型。

回答by Aaron Voelker

You may want to use the ndarray.itemmethod, as in a.item(). This is also equivalent to 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,

您可能想要使用该ndarray.item方法,如a.item(). 这也等价于np.asscalar(a). 这有利于在具有视图和多余轴的情况下工作,而上述解决方案目前将失效。例如,

>>> 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 a singleton, while the a[0]approach will silently proceed (which may lead to bugs sneaking through undetected).

如果数组不是单例,这也有抛出异常的好处,而该a[0]方法将默默地进行(这可能会导致错误潜入而未被发现)。

>>> 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

回答by Tom Hale

Use numpy.asscalarto convert a numpy array / matrix a scalar value:

使用numpy.asscalar将 numpy 数组/矩阵转换为标量值:

>>> a=numpy.array([[[[42]]]])
>>> numpy.asscalar(a)
42

The output data type is the same type returned by the input's itemmethod.

输出数据类型与输入item方法返回的类型相同。

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 asscalarmust respond to item, so passing a list or tuple won't work.

注意:传递给的对象asscalar必须响应item,因此传递列表或元组将不起作用。