2015-03-03 22 views
1

我有一個選擇來自實驗的值,我想刪除其他行的某些行。含義:我測量一個場,一個極化和一個極化的誤差。現在,執行此測量的機器有時不會在某些行中寫入數值。所以,我可能會得到: 場=數據[0]刪除np.array中的選定行

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] =價值楠。和所有數組的[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功能只是做了一些單位換算或寫「南」如果值是「」。我試圖做類似的事情:

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

但是後來我找回一個數組,事情變得混亂。我的下一個方法是對元素進行計數,從所有數組中刪除相同的元素......等等。工程,但它很醜。那麼最好的解決方案是什麼?

回答

0

可以遍歷行和創建行的面膜,然後用布爾索引來獲取通過行的看法:

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) 
0

嘗試使用mask_where命令。

A(非常基本的)例子:

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,然後在所有其他陣列上應用該掩碼。希望有所幫助。

0

我結合另一個線程和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的條目並刪除它們。