如何删除 Numpy 数组中包含非数字值的行?
很多时候我们在 NumPy 数组中有非数字值。需要删除这些值,这样数组就不会包含所有这些不必要的值,并且看起来更体面。可以使用按位非运算符和np.isnan()删除包含 Nan 值的所有行 函数。
示例 1:
Python3
# Importing Numpy module
import numpy as np
# Creating 2X3 2-D Numpy array
n_arr = np.array([[10.5, 22.5, 3.8],
[41, np.nan, np.nan]])
print("Given array:")
print(n_arr)
print("\nRemove all rows containing non-numeric elements")
print(n_arr[~np.isnan(n_arr).any(axis=1)])
Python3
# Importing Numpy module
import numpy as np
# Creating 3X3 2-D Numpy array
n_arr = np.array([[10.5, 22.5, 3.8],
[23.45, 50, 78.7],
[41, np.nan, np.nan]])
print("Given array:")
print(n_arr)
print("\nRemove all rows containing non-numeric elements")
print(n_arr[~np.isnan(n_arr).any(axis=1)])
Python3
# Importing Numpy module
import numpy as np
# Creating 5X4 2-D Numpy array
n_arr = np.array([[10.5, 22.5, 3.8, 5],
[23.45, 50, 78.7, 3.5],
[41, np.nan, np.nan, 0],
[20, 50.20, np.nan, 2.5],
[18.8, 50.60, 8.8, 58.6]])
print("Given array:")
print(n_arr)
print("\nRemove all rows containing non-numeric elements")
print(n_arr[~np.isnan(n_arr).any(axis=1)])
输出:
在上面的示例中,我们从2X3 Numpy 数组中删除包含非数字值的行。
示例 2:
蟒蛇3
# Importing Numpy module
import numpy as np
# Creating 3X3 2-D Numpy array
n_arr = np.array([[10.5, 22.5, 3.8],
[23.45, 50, 78.7],
[41, np.nan, np.nan]])
print("Given array:")
print(n_arr)
print("\nRemove all rows containing non-numeric elements")
print(n_arr[~np.isnan(n_arr).any(axis=1)])
输出:
在上面的示例中,我们从3X3 Numpy 数组中删除包含非数字值的行。
示例 3:
蟒蛇3
# Importing Numpy module
import numpy as np
# Creating 5X4 2-D Numpy array
n_arr = np.array([[10.5, 22.5, 3.8, 5],
[23.45, 50, 78.7, 3.5],
[41, np.nan, np.nan, 0],
[20, 50.20, np.nan, 2.5],
[18.8, 50.60, 8.8, 58.6]])
print("Given array:")
print(n_arr)
print("\nRemove all rows containing non-numeric elements")
print(n_arr[~np.isnan(n_arr).any(axis=1)])
输出:
在上面的示例中,我们从5X4 Numpy array中删除包含非数字值的行。