numpy中是否存在一个函数,告诉我一个值是数值类型还是numpy数组?我正在编写一些数据处理代码,需要处理几种不同表示中的数字("数字"我指的是数字量的任何表示,可以使用标准算术运算符来操作,+, - ,*,/,**).
我正在寻找的行为的一些例子
>>> is_numeric(5)
True
>>> is_numeric(123.345)
True
>>> is_numeric('123.345')
False
>>> is_numeric(decimal.Decimal('123.345'))
True
>>> is_numeric(True)
False
>>> is_numeric([1, 2, 3])
False
>>> is_numeric([1, '2', 3])
False
>>> a = numpy.array([1, 2.3, 4.5, 6.7, 8.9])
>>> is_numeric(a)
True
>>> is_numeric(a[0])
True
>>> is_numeric(a[1])
True
>>> is_numeric(numpy.array([numpy.array([1]), numpy.array([2])])
True
>>> is_numeric(numpy.array(['1'])
False
Run Code Online (Sandbox Code Playgroud)
如果不存在这样的函数,我知道编写一个函数应该不难
isinstance(n, (int, float, decimal.Decimal, numpy.number, numpy.ndarray))
Run Code Online (Sandbox Code Playgroud)
但是我应该在列表中包含其他数字类型吗?
dF.*_*dF. 18
正如其他人已经回答的那样,除了你提到的那些之外,还有其他数字类型.一种方法是明确检查您想要的功能,例如
# Python 2
def is_numeric(obj):
attrs = ['__add__', '__sub__', '__mul__', '__div__', '__pow__']
return all(hasattr(obj, attr) for attr in attrs)
# Python 3
def is_numeric(obj):
attrs = ['__add__', '__sub__', '__mul__', '__truediv__', '__pow__']
return all(hasattr(obj, attr) for attr in attrs)
Run Code Online (Sandbox Code Playgroud)
这适用于除最后一个之外的所有示例numpy.array(['1']).这是因为numpy.ndarray有数字操作的特殊方法,但如果你试图不恰当地使用字符串或对象数组,则会引发TypeError.你可以为此添加一个明确的检查
... and not (isinstance(obj, ndarray) and obj.dtype.kind in 'OSU')
Run Code Online (Sandbox Code Playgroud)
这可能足够好了.
但是......你永远不能100%确定有人不会定义具有相同行为的另一种类型,所以更简单的方法是实际尝试进行计算并捕获异常,类似于
def is_numeric_paranoid(obj):
try:
obj+obj, obj-obj, obj*obj, obj**obj, obj/obj
except ZeroDivisionError:
return True
except Exception:
return False
else:
return True
Run Code Online (Sandbox Code Playgroud)
但是,根据您计划调用的频率使用它以及使用什么参数,这可能不实际(它可能很慢,例如使用大型数组).
通常,处理未知类型的灵活,快速和pythonic方法是只对它们执行一些操作并捕获无效类型的异常.
try:
a = 5+'5'
except TypeError:
print "Oops"
Run Code Online (Sandbox Code Playgroud)
在我看来,这种方法比特殊的方法容易一些,以确定绝对类型的确定性.
小智 6
此外,numpy 具有numpy.isreal和其他类似的功能(numpy.is+ Tab 应该列出它们)。
他们都有自己有趣的角落案例,但其中一个可能有用。
| 归档时间: |
|
| 查看次数: |
26203 次 |
| 最近记录: |