问题描述
在Python中,可以使用 n.is_integer()
来检查 float
是否包含整数值。 ,基于这个质量保证:。
numpy是否有类似的操作可以应用于数组?有些东西会允许以下内容:
>>> x = np.array([1.0 2.1 3.0 3.9])
>>> mask = np.is_integer(x)
>>> mask
array([True,False,True,False],dtype = bool)
有可能做一些类似的事情,例如:
>>> mask =(x == np.floor(x))
或
>>>掩码=(x == np.round(x))
但它们涉及调用额外的方法并创建
numpy是否有一个向量化的函数来检查浮点数的小数部分,类似于Python的 float.is_integer
?
从我可以告诉,没有这样的函数返回指示浮点数是否有小数部分的布尔数组。我能找到的最接近的是 np.modf
,它返回小数部分和整数部分,但是它创建了两个浮点数组(至少是暂时的),所以它可能不是最好的内存 - 明智的。
如果你很高兴在这里工作,你可以尝试一下:
>>> np.mod(x,1,out = x)
>>> mask =(x == 0)
保持 x
左右),但是当然你会失去原来的 x
。
另一个选择是要求它在Numpy中实现,或者自己实现它。
In Python, it is possible to check if a float
contains an integer value using n.is_integer()
, based on this QA: How to check if a float value is a whole number.
Does numpy have a similar operation that can be applied to arrays? Something that would allow the following:
>>> x = np.array([1.0 2.1 3.0 3.9])
>>> mask = np.is_integer(x)
>>> mask
array([True, False, True, False], dtype=bool)
It is possible to do something like
>>> mask = (x == np.floor(x))
or
>>> mask = (x == np.round(x))
but they involve calling extra methods and creating a bunch of temp arrays that could be potentially avoided.
Does numpy have a vectorized function that checks for fractional parts of floats in a way similar to Python's float.is_integer
?
From what I can tell, there is no such function that returns a boolean array indicating whether floats have a fractional part or not. The closest I can find is np.modf
which returns the fractional and integer parts, but that creates two float arrays (at least temporarily), so it might not be best memory-wise.
If you're happy working in place, you can try something like:
>>> np.mod(x, 1, out=x)
>>> mask = (x == 0)
This should save memory versus using round or floor (where you have to keep x
around), but of course you lose the original x
.
The other option is to ask for it to be implemented in Numpy, or implement it yourself.
这篇关于Numpy:检查float数组是否包含整数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!