在python数组中查找接近数字的值并对其进行索引



这是我迄今为止的代码:

import numpy as np
#make amplitude and sample arrays
amplitude=[0,1,2,3, 5.5, 6,5,2,2, 4, 2,3,1,6.5,5,7,1,2,2,3,8,4,9,2,3,4,8,4,9,3]
#print(amplitude)
#split arrays up into a line for each sample
traceno=5                  #number of traces in file
samplesno=6                #number of samples in each trace. This wont change.
amplitude_split=np.array(amplitude, dtype=np.int).reshape((traceno,samplesno))
print(amplitude_split)
#find max value of trace
max_amp=np.amax(amplitude_split,1)
print(max_amp)
#find index of max value
ind_max_amp=np.argmax(amplitude_split, axis=1, out=None)
#print(ind_max_amp)
#find 90% of max value of trace
amp_90=np.amax(amplitude_split,1)*0.9
print(amp_90)

我想在数组的每一行中找到最接近相应amp_90的值。我也想得到这个数字的索引。请帮忙!

n.b.我知道这很容易用眼睛完成,但在我将其应用于真实数据之前,这是一个测试数据集!

IIUC,您可以执行以下操作:

# find the indices of the min absolute difference 
indices = np.argmin(np.abs(amplitude_split - amp_90[:, None]), axis=1)
# get the values at those positions
result = amplitude_split[np.arange(5), indices]
print(result)

最新更新