Numpy信号处理:有效地汇总连续非零元素的子数组

z5btuh9x  于 11个月前  发布在  其他
关注(0)|答案(1)|浏览(74)

因此,我正在处理FFT数据,当彻底清理时,这些数据看起来应该像很多很多零和偶尔的大数。我现在拥有的是很多零和偶尔的小数字子数组。作为一个例子,
ydata=np.array([0,0,0,0,1,2,3,0,0,9,3, 1, 0, 2, 9, 0])xdata=np.array([0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15])
我对扩展数据使用了一个连续整数数组,但是这些值可以是任何严格递增的数字序列。
我想做的是将所有当前y值设置为0,并添加对应于非零子数组的值。对于每个子数组,y值应该是子数组中元素的总和,并且它应该是最接近子数组索引的加权总和的索引。
例如,ydata中连续非零元素的第一个子数组是[1,2,3],对应的x值是[4,5,6]。y值的和是6,x值的加权和是(4+10+18)/6,四舍五入到5。
ydata=np.array([0,0,0,0,0,6,0,0,0,13,0, 0, 0, 0, 11, 0])xdata=np.array([0,1,2,3,4,5,6,7,8,9, 10,11,12,13,14,15])
如果我们有ydata=np.array([1,2,3,0,1,2,3,0,0,9,3, 1, 0, 2, 9, 0])xdata=np.array([.1,.4,.6,3,4.1,4.2,4.3,7,8,9,10,11,12,13,14,15])
那么ydata应该是ydata=np.array([6,0,0,0,6,0,0,0,0,13,0, 0, 0, 0, 11, 0])
我可以使用non-numpy迭代来实现这一点,但是对于我正在处理的数据大小来说,这是不切实际的。有人知道通过numpythonic方法来实现这一点的好方法吗?

xcitsw88

xcitsw881#

你需要在这里计算几件事:
首先,获取整个数组的累积和:

cs = np.cumsum(ydata)

字符串
接下来,查找当前元素为非零、下一个元素为零且累积和不为零的位置:

filter_locs = (ydata != 0) & (cs != 0)
filter_locs[:-1] = filter_locs[:-1] & (ydata[1:] == 0)


新值可以从这些位置的累积和中导出:

new_values = cs[filter_locs]
new_values[1:] -= new_values[:-1]


我们可以在xdata * ydata上做类似的操作来获得索引:

cs_x = np.cumsum(xdata * ydata)
weighted_totals = cs_x[filter_locs]
weighted_totals[1:] -= weighted_totals[:-1]

new_indices = np.round(weighted_totals / new_values).astype(int)


最后,在一个零数组中设置索引:

new_data = np.zeros_like(ydata)
new_data[new_indices] = new_values


这给了我们想要的数组:

array([ 0,  0,  0,  0,  0,  6,  0,  0,  0, 13,  0,  0,  0,  0, 11,  0])


如果xdata不是一个索引数组,那么输出数组中的最大可能索引是xdata,所以不使用new_data = np.zeros_like(ydata),而使用:

max_possible_index = int(np.round(xdata.max()))
new_data = np.zeros((max_possible_index+1,))

相关问题