Filter integers in numpy float array
Is there any built in function to discard integer and keep only float number in 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.
I've always used np.equal with 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:
>>> 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
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.
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.
I've always used np.equal with 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:
>>> 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
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.
Comments
Post a Comment