如何删除 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, np.nan],
[41, 52.5, np.nan]])
print("Given array:")
print(n_arr)
print("\nRemove all columns containing non-numeric elements ")
print(n_arr[:, ~np.isnan(n_arr).any(axis=0)])
Python3
# Importing Numpy module
import numpy as np
# Creating 3X3 2-D Numpy array
n_arr = np.array([[10.5, 22.5, 10.5],
[41, 52.5, 25],
[100, np.nan, 41]])
print("Given array:")
print(n_arr)
print("\nRemove all columns containing non-numeric elements ")
print(n_arr[:, ~np.isnan(n_arr).any(axis=0)])
Python3
# Importing Numpy module
import numpy as np
# Creating 5X3 2-D Numpy array
n_arr = np.array([[10.5, 22.5, 3.8],
[23.45, 50, 78.7],
[41, np.nan, np.nan],
[20, 50.20, np.nan],
[18.8, 50.60, 8.8]])
print("Given array:")
print(n_arr)
print("\nRemove all columns containing non-numeric elements ")
print(n_arr[:, ~np.isnan(n_arr).any(axis=0)])
输出:
在上面的示例中,我们从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, 10.5],
[41, 52.5, 25],
[100, np.nan, 41]])
print("Given array:")
print(n_arr)
print("\nRemove all columns containing non-numeric elements ")
print(n_arr[:, ~np.isnan(n_arr).any(axis=0)])
输出:
在上面的示例中,我们从3X3 Numpy 数组中删除包含非数字值的列。
示例 3:
蟒蛇3
# Importing Numpy module
import numpy as np
# Creating 5X3 2-D Numpy array
n_arr = np.array([[10.5, 22.5, 3.8],
[23.45, 50, 78.7],
[41, np.nan, np.nan],
[20, 50.20, np.nan],
[18.8, 50.60, 8.8]])
print("Given array:")
print(n_arr)
print("\nRemove all columns containing non-numeric elements ")
print(n_arr[:, ~np.isnan(n_arr).any(axis=0)])
输出:
在上面的示例中,我们从5X3 Numpy 数组中删除了包含非数字值的列。