numpy数组的元素明智测试是数值 [英] element wise test of numpy array is numeric
本文介绍了numpy数组的元素明智测试是数值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个如下数组:
In [1]: x = array(['1.2', '2.3', '1.2.3'])
我想测试数组中的每个元素是否可以转换为数值.也就是说,函数:is_numeric(x)将返回True/False数组,如下所示:
I want to test if each element in the array can be converted into numerical value. That is, a function: is_numeric(x) will return a True/False array as following:
In [2]: is_numeric(x)
Out[2]: array([True, True, False])
该怎么做?
推荐答案
import numpy as np
def is_float(val):
try:
float(val)
except ValueError:
return False
else:
return True
a = np.array(['1.2', '2.3', '1.2.3'])
is_numeric_1 = lambda x: map(is_float, x) # return python list
is_numeric_2 = lambda x: np.array(map(is_float, x)) # return numpy array
is_numeric_3 = np.vectorize(is_float, otypes = [bool]) # return numpy array
根据 a 数组的大小和返回值的类型,这些函数的速度不同.
Depend on the size of a array and the type of the returned values, these functions have different speed.
In [26]: %timeit is_numeric_1(a)
100000 loops, best of 3: 2.34 µs per loop
In [27]: %timeit is_numeric_2(a)
100000 loops, best of 3: 3.13 µs per loop
In [28]: %timeit is_numeric_3(a)
100000 loops, best of 3: 6.7 µs per loop
In [29]: a = np.array(['1.2', '2.3', '1.2.3']*1000)
In [30]: %timeit is_numeric_1(a)
1000 loops, best of 3: 1.53 ms per loop
In [31]: %timeit is_numeric_2(a)
1000 loops, best of 3: 1.6 ms per loop
In [32]: %timeit is_numeric_3(a)
1000 loops, best of 3: 1.58 ms per loop
如果list
没问题,请使用is_numeric_1
.
如果需要numpy array
,并且 a 的大小较小,请使用is_numeric_2
.
If you want a numpy array
, and size of a is small, use is_numeric_2
.
否则,请使用is_numeric_3
这篇关于numpy数组的元素明智测试是数值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文