2017-06-15 113 views
2

我有一個分組的空間表,並且想循環遍歷各個組,並分別在每個組上執行剪輯均值。將列值分配給循環內的分組的空間表

下面的MWE說明了我正在嘗試做什麼。當代碼運行時,它不會拋出錯誤,而'c'列的值只會保持爲0.0。我覺得我可能從根本上誤解了桌面環境的工作原理,但我不確定究竟是什麼。

import numpy as np 
from astropy.table import Table 
from astropy.stats import sigma_clip 

a = np.array([5.7, 5.9, 5.1, 5.3, 5.7, 5.4, 6.0, 8.6, 6.4, 5.2]) 
b = np.array([0, 0, 0, 0, 1, 1, 1, 1, 1, 1]) 
c = np.zeros(len(a)) 

tab = Table((a,b,c), names=('a','b','c'), masked=True) 

tabGrp = tab.group_by('b') 

for x in tabGrp.groups: 
    clipped = sigma_clip(x['a'], sigma=2) 
    x['c'] = clipped 

回答

0

當你組表tab,新groups財產is added

您可以在每個tabGrp組申請sigma_clip(),商店只有在列表中的值,創建一個新的MaskedColumn這個存儲的值(正確屏蔽值),並用新的剪裁替換舊c列。

這不是很優雅,但似乎是做你所需要的。

import numpy as np 
from astropy.table import Table 
from astropy.stats import sigma_clip 
from astropy.table import MaskedColumn 

a = np.array([5.7, 4.2, 5.1, 5.3, 5.7, 5.4, 6.0, 8.6, 6.4, 5.2]) 
b = np.array([0, 0, 0, 0, 1, 1, 1, 1, 1, 1]) 
c = np.zeros(len(a)) 

tab = Table((a, b, c), names=('a', 'b', 'c'), masked=True) 

tabGrp = tab.group_by('b') 
clipped = sigma_clip(tabGrp['a'], sigma=2) 

col = [] 
for x in tabGrp.groups: 
    clipped = sigma_clip(x['a'], sigma=2) 
    # Save values only. 
    col += clipped.tolist() 

# Create new masked column. 
c_clipped = MaskedColumn(col, mask=[True if _ is None else False for _ in col]) 
# Replace old c column 
tab['c'] = c_clipped 

導致:

a b c 
--- --- --- 
5.7 0 5.7 
4.2 0 4.2 
5.1 0 5.1 
5.3 0 5.3 
5.7 1 5.7 
5.4 1 5.4 
6.0 1 6.0 
8.6 1 -- 
6.4 1 6.4 
5.2 1 5.2 

這是你所追求的?

+0

不是我在找什麼 - 如果我們改爲設置一個[2] = 4.2,它應該更好地說明我想要的。然後,如果我們要在整個數組a上執行sigma剪輯,那麼[2]將被屏蔽。但是,如果我們分別在兩個組上執行sigma剪輯(這是我想要的),那麼a [2]不會被屏蔽。 –

+0

好的,所以'4.2'不應該被第1組屏蔽,8.6「應該被第2組屏蔽?這個剪輯組應該合併成一個列,並在表格中存儲爲「c」(從而替換現有的「c」列)? – Gabriel