[英]Filter integers in numpy float array
Is there any built in function to discard integer and keep only float number in numpy
.是否有任何内置函数可以丢弃整数并在
numpy
仅保留浮点数。
import numpy as np
input = np.array([0.0, 0.01, 1.0, 2.0, 2.001, 2.002])
desired_ouput = some_function(input)
# Expected ouput
# desired_output = np.array([0.01, 2.001, 2.002])
Mask with whether each element is equal to it as an integer. 掩码每个元素是否等于整数。
arr = np.array([0.0, 0.01, 1.0, 2.0, 2.001, 2.002])
out = arr[arr != arr.astype(int)]
#np.array([0.01, 2.001, 2.002])
I don't think so. 我不这么认为。 My approach would be
我的方法是
import numpy as np
a = np.array([0.0, 0.01, 1.0, 2.0, 2.001, 2.002])
mask = np.isclose(a, a.astype(int))
print(a[~mask])
#[ 0.01 2.001 2.002]
I know of no in-built function. 我知道没有内置功能。 But you can create one yourself:
但你可以自己创建一个:
import numpy as np
A = np.array([0.0, 0.01, 1.0, 2.0, 2.001, 2.002])
def remove_ints(arr):
return arr[~(arr == arr.astype(int))]
res = remove_ints(A)
array([ 0.01 , 2.001, 2.002])
Aside, you should not use a built-in class such as input
as a variable name. 除此之外,您不应该使用
input
等内置类作为变量名。
I've always used np.equal
with np.mod
: 我一直使用
np.equal
与np.mod
:
>>> A[~np.equal(np.mod(A, 1), 0)]
array([0.01 , 2.001, 2.002])
If you do not have to much data (short list), maybe do not need numpy
: 如果您没有太多数据(短名单),可能不需要
numpy
:
>>> i = [0.0, 0.01, 1.0, 2.0, 2.001, 2.002]
>>> a=[j for j in i if not j.is_integer()]
>>> a
['0.01', '2.001', '2.002']
Otherwise see Joe Iddon answer 否则请看Joe Iddon回答
I don't know any builtin for this but you can filter those floats using: 我不知道任何内置功能,但您可以使用以下方法过滤这些浮动:
filter(lambda x: int(str(x).split('.')[1]) != 0, input)
The lambda expression here checks if the decimal places are zero which I interpret as the number being an int. 这里的lambda表达式检查小数位是否为零,我将其解释为数字为int。
I had a similar question a while back: Numpy: Check if float array contains whole numbers .不久前我有一个类似的问题: Numpy: Check if float array contains entire numbers 。 The simplest way to mask fractions that I am currently aware of is
我目前知道的屏蔽分数的最简单方法是
mask = ((input % 1) != 0)
You can then apply the mask directly with然后您可以直接使用面膜
output = input[mask]
It bothered me that there is no built-in function to determine the integerness of a float quickly, so I wrote a ufunc that you can download from github and compile if you're interested:困扰我的是没有内置函数来快速确定浮点数的整数,所以我写了一个 ufunc ,你可以从github下载并编译,如果你有兴趣:
from isint_ufunc import isint
output = input[~isint(input)]
I'll see if the numpy community wants to consider adding something like that to the core library.我会看看 numpy 社区是否想要考虑将类似的东西添加到核心库中。 The question seems to come up often enough to justify it.
这个问题似乎经常出现,足以证明它的合理性。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.