删除 np.array 中的选定行

Remove chosen lines in an np.array

我有一些来自实验的值,我想相对于其他行删除一些行。意思:我测量场,偏振和偏振误差。现在进行这种测量的机器有时不会在其中一些行中写入值。所以我可能会得到: 字段 = 数据[0]

field = [1,2,3,3,2,1,nan,4,1,2]
polarization = [nan, 10,230,13,123,50,102,90,45]
error = [0.1, 0.1, 0.2, 0.1, 0.1, 0.3, 0.1, 0.1, 0.4, 0.2]

现在我要删除第一个元素field,polarization和error,因为polarization[0] value = nan。以及所有数组的 [6] 值,因为 field[6] = nan.

这是我获取数据的方式:

class DataFile(object):
    def __init__(self, filename):
        self._filename = filename


    def read_dat_file(self):
        data = np.genfromtxt(self._filename, delimiter=',', \
        usecols=(3,4,5,), skip_header=23, skip_footer=3, unpack=True, converters={\
        3: lambda x: self._conv(x), \
        4: lambda x: self._conv(x), \
        5: lambda x: self._2_conv(x)})
        return data

a = DataFile("DATFILE.DAT")
print a

_conv 函数只是进行一些单位转换或写入 'nan' 如果值是 " "。我尝试做类似的事情:

data = data[~np.isnan(data).any(axis=1)]

但后来我取回了一个数组,事情变得一团糟。我的下一个方法是对元素进行计数,从所有数组中删除相同的元素……等等。有效,但它很难看。那么最好的解决方案是什么?

尝试使用 mask_where 命令。

一个(非常基本的)例子:

y = np.array([2,1,5,2])                         # y axis
x = np.array([1,2,3,4])                         # x axis
m = np.ma.masked_where(y>5, y)                  # filter out values larger than 5
new_x = np.ma.masked_where(np.ma.getmask(m), x) # applies the mask of m on x

好消息是您现在可以将此掩码应用到更多阵列,而无需对每个阵列进行掩码处理。而且不会像数元素那样丑

在您的情况下,您可能需要遍历每个数组,检查 nan,然后将该掩码应用于所有其他数组。希望对您有所帮助。

您可以遍历行并为行创建掩码,然后使用布尔索引获取通过的行的视图:

import numpy as np

field = [1,2,3,3,2,1,-1,4,1,2]
polarization = [-1, 10,230,13,123,50,102,90,45,1337]
error = [0.1, 0.1, 0.2, 0.1, 0.1, 0.3, 0.1, 0.1, 0.4, 0.2]

#transposition is needed to get expected row-col format
array = np.array([field, polarization, error]).T
print(array)

#create your filter function
filter = lambda row : row[0] > 0 and row[1] > 0 and row[2] > 0

#create boolean mask by applying filter
mask = np.apply_along_axis(filter, 1, array)
print(mask)

new_array = array[mask]
print(new_array)

我结合了另一个主题和 red_tigers 答案,我想与您分享: 只是 运行 这个函数在你的数组上,里面有数据:

data = np.array([field, polarization, error]).T

def delete_NaN_rows(self, data):
    filter = lambda row: ~np.isnan(row[0]) and ~np.isnan(row[1]) and ~np.isnan(row[2])
    mask = np.apply_along_axis(filter, 1, data)
    clean_data = data[mask]
    return clean_data.T

我使用了 np.isnan(#element) 的逆运算 (~) 确实用 NaN 条目识别我的行并删除它们。