【问题标题】:Python Find indices of data in array/list, but with constraintsPython在数组/列表中查找数据索引,但有约束
【发布时间】:2017-04-27 11:51:03
【问题描述】:

我有三个数组(或列表,或其他):

x - 横坐标。一组不均匀分布的数据。

y - 纵坐标。代表y=f(x)的一组数据。

peaks - 一组数据,其元素包含有序对 (x,y),表示在 y 中找到的峰值。

这是xy 数据的一部分:

2.00   1.5060000000e-07
...
...
5.60   3.4100000000e-08
5.80   1.7450000000e-07
6.00   7.1700000000e-08
6.20   5.2900000000e-08
6.40   2.5570000000e-07
6.50   4.8420000000e-07
6.60   6.1900000000e-08
6.80   2.2700000000e-07
7.00   2.3500000000e-08
7.20   3.6500000000e-08
7.40   1.0158000000e-06
7.50   3.5100000000e-08
7.60   2.0080000000e-07
7.80   1.6585000000e-06 
8.00   2.1190000000e-07
8.20   5.3370000000e-07
8.40   5.7840000000e-07
8.50   4.5230000000e-07
...
...
50.00   1.8200000000e-07

这里是print(peaks)

[(3.7999999999999998, 4.0728000000000002e-06), (5.4000000000000004, 5.4893000000000001e-06), (10.800000000000001, 1.2068e-05), (12.699999999999999, 4.1904799999999999e-05), (14.300000000000001, 8.3118000000000006e-06), (27.699999999999999, 6.5239000000000003e-06)]

我用数据做图,类似这样:

图中的蓝点是峰。红点是山谷。但红点不一定准确。您可以看到最后一个峰的右侧有一个红点。这不是故意的。

使用上面的数据,我试图找到如下的山谷:

遍历peaks 数组(或列表,或其他任何内容),对于每对相邻的峰,在xy 数组(或列表,或其他任何内容)中找到它们的索引,然后在由这些索引绑定的y 数组中搜索最小值。还可以在该索引处找到相应的 x 值。然后将(x,y) 对附加到数组v1(或列表,或其他),类似于peaks。然后将v1 绘制为红点。

代码如下:

for i in xrange(1,len(peaks)):
# Find the indices of the two peaks in the actual arrays
# (e.g. x[j1] and y[j1]) where the peaks occur
  j1=np.where(x==peaks[i-1][0])
  j1=int(j1[0])
  j2=np.where(x==peaks[i][0])
  j2=int(j2[0])
# In the array y[j1:j2], find the index of the minimum value
  j=np.where(y==min(y[j1:j2]))
# What if there are more than one minumum?
  if(len(j[0])>1):
# Use the first one.
# I incorrectly assumed this would be > j1,
# but it could be anywhere in y
    jt=int(j[0][0])
    v1.append((x[jt],y[jt]))
# And the last one.
# I incorrectly assumed this would be < j2,
# but it could be anywhere in y. But we do know at least one of the
# indices found will be between j1 and j2.
    jt=int(j[0][-1])
    v1.append((x[jt],y[jt]))
  else:
# When only 1 index is found, no problem: it has to be j1 < j < j2
    j=int(j[0])
    v1.append((x[j],y[j])) 

问题来了:

当我在这样的特定范围内搜索y 的最小值时:

j=np.where(y==min(y[j1:j2]))

它返回整个y 数据集中的最小值的索引。但我希望j 只包含我搜索过的j1j2 之间的最小值的索引。

如何限制搜索?

我可以检查 j1

一旦我弄清楚这一点,我将添加逻辑来限制索引,如果峰值超过宽度 w 分开。

因此,如果峰值之间的距离大于w,则j1 将不小于j2-w/2,其中j2 是峰值的索引。

【问题讨论】:

    标签: python arrays list find indices


    【解决方案1】:

    您可以在之前对数组进行切片并与切片进行== 比较:

    sliced_y = y[j1:j2]
    j = np.where(sliced_y == min(sliced_y))[0] + j1
    

    你需要+下限,否则你只有切片部分的“索引”。

    【讨论】:

    • ` j=np.where(ys==min(ys))+j1 TypeError: can only concatenate tuple (not "int") to tuple`
    • @Mannix 你好像忘了np.where(...)后面的[0]
    猜你喜欢
    • 2023-03-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-07
    • 2018-04-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多