Python 从numpy浮点数数组中过滤出整数

Python 从numpy浮点数数组中过滤出整数

给定一个numpy数组,任务是将整数从包含浮点数和整数的数组中过滤出来。让我们来看看解决给定任务的几个方法。
方法#1:使用astype(int)

# Python code to demonstrate
# filtering integers from numpy array
# containing integers and float
 
import numpy as np
 
# initialising array
ini_array = np.array([1.0, 1.2, 2.2, 2.0, 3.0, 2.0])
 
# printing initial array
print ("initial array : ", str(ini_array))
 
# filtering integers
result = ini_array[ini_array != ini_array.astype(int)]
 
# printing resultant
print ("final array", result)

输出:

initial array :  [ 1.   1.2  2.2  2.   3.   2. ]
final array [ 1.2  2.2]

方法二:使用np.equal()和np.mod()

# Python code to demonstrate
# filtering integers from numpy array
# containing integers and float
 
import numpy as np
 
# initialising array
ini_array = np.array([1.0, 1.2, 2.2, 2.0, 3.0, 2.0])
 
# printing initial array
print ("initial array : ", str(ini_array))
 
# filtering integers
result = ini_array[~np.equal(np.mod(ini_array, 1), 0)]
 
# printing resultant
print ("final array : ", str(result))

输出:

initial array :  [ 1.   1.2  2.2  2.   3.   2. ]
final array :  [ 1.2  2.2]

方法#3:使用np.isclose()

# Python code to demonstrate
# filtering integers from numpy array
# containing integers and float
 
import numpy as np
 
# initialising array
ini_array = np.array([1.0, 1.2, 2.2, 2.0, 3.0, 2.0])
 
# printing initial array
print ("initial array : ", str(ini_array))
 
# filtering integers
mask = np.isclose(ini_array, ini_array.astype(int))
result = ini_array[~mask]
 
# printing resultant
print ("final array : ", str(result))

输出:

initial array :  [ 1.   1.2  2.2  2.   3.   2. ]
final array :  [ 1.2  2.2]

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程

Numpy 示例