我有一个函数可以执行一些操作并设置一些 protobuf 值。
现在 protobuf 要求设置的值是 python native 值,而不是 numpy 值。
现在,一半的时间使用 native 值调用此函数,一半的时间使用 numpy 值。
我需要一种完全可靠的方法来将 numpy 值转换为 native 值,同时在类型已经是 python native 值的情况下不会导致问题。
我尝试过的:
使用 numpy.asscalar 获取 native 值时会失败 我尝试过将其转换为字符串,然后再转换回来,但这感觉非常慢,而且执行此操作的方式很糟糕。
最佳答案
您可以编写自己的 asscalar()
,它尝试使用 np.asscalar()
如果失败,则恢复为仅按原样返回值:
import numpy as np
def asscalar(v):
"""
Try converting a numpy array of size 1 to a scalar equivalent, or return
the value as is.
Returns:
A scalar value, if a numpy array of size 1 was given, the value itself
otherwise. Note that a python list of size 1 will be returned as is.
Raises:
A ValueError, if v is a numpy array of size larger than 1.
"""
try:
return np.asscalar(v)
except AttributeError:
# Not something numpy understands
return v
关于python - 将 numpy 标量转换为 python 简单 native (稍作改动),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37178905/