【问题标题】:Remove chosen lines in an np.array删除 np.array 中的选定行
【发布时间】:2015-05-03 20:05:46
【问题描述】:

我有一些来自实验的值,我想删除一些相对于其他行的行。意思:测量场,偏光以及偏光的误差。现在进行此测量的机器有时不会在其中一些行中写入值。所以我可能会得到: 字段 = 数据[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]

现在我要删除场、极化和误差的第一个元素,因为极化[0] 值 = 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)]

但后来我拿回了一个数组,事情变得一团糟。我的下一个方法是计算元素,从所有数组中删除相同的元素......等等。工作,但它是丑陋的。那么这里最好的解决方案是什么?

【问题讨论】:

    标签: python arrays numpy nan genfromtxt


    【解决方案1】:

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

    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)
    

    【讨论】:

      【解决方案2】:

      尝试使用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,然后将该掩码应用于所有其他数组。希望对您有所帮助。

      【讨论】:

        【解决方案3】:

        我结合了另一个线程和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 条目识别我的行并删除它们。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2017-09-04
          • 2016-10-02
          • 2013-03-27
          • 2013-08-01
          相关资源
          最近更新 更多