在numpy float数组中过滤整数

Oli*_*Oli 27 python 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])
Run Code Online (Sandbox Code Playgroud)

Joe*_*don 16

掩码每个元素是否等于整数.

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])
Run Code Online (Sandbox Code Playgroud)


Spg*_*tCd 14

我不这么认为.我的方法是

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]
Run Code Online (Sandbox Code Playgroud)

  • 作为一般规则,在比较浮点数时总是使用`isclose`.我不确定这里是否有必要,但是为了良好的实践而受到赞扬. (3认同)

jpp*_*jpp 6

我知道没有内置功能.但你可以自己创建一个:

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])
Run Code Online (Sandbox Code Playgroud)

除此之外,您不应该使用内置类,例如input变量名.


use*_*203 5

我一直np.equalnp.mod

>>> A[~np.equal(np.mod(A, 1), 0)]
array([0.01 , 2.001, 2.002])
Run Code Online (Sandbox Code Playgroud)