根据分组列值对表元素进行分组

2 投票
1 回答
621 浏览
提问于 2025-04-18 15:36

我有这样一个表格,里面记录了每个能量通道的光子计数。

第三列是通道的分组:所有标记为-1的通道会被归为一个单独的通道,这个通道的起点是前一个1的分组值。也就是说,在这个例子中,从0到39的所有通道都被归为一个通道。

我该如何创建一个数组或列表,里面的计数是根据group列定义的分组来整理的呢?在这个例子中,我得到的数组会有两个元素,一个是从通道0到39的计数总和,另一个是第40个通道的计数。

抱歉我无法提供任何起始代码,因为我真的不知道该从哪里开始。任何建议都非常感谢。

编辑:这个表格是一个FITS文件的一部分。我是通过使用pyfits来读取它的:

import pyfits
data = pyfits.open('./file.fits')
chan    = data[1].data.field('channel')
counts    = data[1].data.field('counts')
groups    = data[1].data.field('grouping')
data.close()

print type(chan)返回<type 'numpy.ndarray'>。其他数组也是一样。

1 个回答

2

试试这个,

chan = np.array( [0,1,2,3,4,5,6,7,8,9] )
counts = np.array( [0.,0.,5.,2.,0.,0.,1.,1.,1.,0.] )
groups = np.array( [1,-1,-1,-1,-1,1,-1,-1,-1,-1] )

indx = np.where( groups==1 )
# indx is a tuple with one entry for each dimension of the array groups
# in the next statement I just grab the first (and only) element of the tuple 
indx = indx[0]  

# next we split the array based on those indices
counts = np.split( counts, indx )
# counts is now a list of arrays 
# [array([], dtype=float64), array([ 0.,  0.,  5.,  0.,  0.]),array([ 0.,  1.,  1.,  1.,  0.])]
# I use the if statement in the list comprehension to get rid of the first empty array

totals = np.array( [sum(c) for c in counts if len(c)>0] )
tchnls = np.split( chan, indx )[1:]

这样一来,totals 就会是每个组的计数总和,

>>> totals
array([ 7.,  3.])

tchnls 则是对每个组有贡献的渠道,

>>> tchnls
[array([0, 1, 2, 3, 4]), array([5, 6, 7, 8, 9])]

撰写回答