【问题标题】:Find index corresponding between two different sized array lists with same total elements查找具有相同总元素的两个不同大小的数组列表之间对应的索引
【发布时间】:2019-05-22 22:42:13
【问题描述】:

如何在大小相同的两个不同形状的数组中找到对应的数组索引?

例如,大小为 36 的数组 x 被拆分为 11 个数组。另一个大小为 36 的数组 y 被拆分为 4 个数组。然后对组成y 的4 个数组进行一些修改。

N  = 6 #some size param
x = np.zeros(N*N,dtype=np.int) #make empty array
s1 = np.array_split(x,11) #split array into arbitrary parts

y = np.random.randint(5, size=(N, N)) #make another same size array (and modify it)
s2 = np.array_split(y,4) #split array into different number of parts

然后遍历y的4个数组,我需要找到s1的第一个数组(array_num)的开始索引,到s1的最后一个数组的结束索引,即值在s2 对应。

for sub_s2 in s2:
    array_num = ?
    s_idx = ?
    e_idx = ?

    s2_idx = ?
    e2_idx = ?

    #put the array into the correct ordered indexes of the other array
    s1[array_num][s_idx,e_idx] = sub_s2[s2_idx,e2_idx]

res = np.concatenate(s1)

我制作了这张图片来尝试说明问题。在这种情况下,“数据”表示开始的 x 和 y 的大小。然后 s1 和 s2 被分成不同的块,问题是在每个块中找到 s2 中的数组对应的索引。

【问题讨论】:

    标签: arrays numpy chunks


    【解决方案1】:

    这里是如何找到正确的索引:

    # create example use same data for both splits for easy validation
    a = np.arange(36)
    
    s1 = np.array_split(a, 11)
    s2 = np.array_split(a, 4)
    
    # recover absolute offsets of bit boundaries 
    l1 = np.cumsum([0, *map(len,s1)])
    l2 = np.cumsum([0, *map(len,s2)])
    
    # find bits in s1 into which the first ...
    start_n = l1[1:].searchsorted(l2[:-1], 'right')
    # ... and last elements of bits of s2 fall
    end_n = l1[1:].searchsorted(l2[1:]-1, 'right')
    
    # find the corresponding indices into bits of s1
    start_idx = l2[:-1] - l1[start_n]
    end_idx = l2[1:]-1 - l1[end_n]
    
    # check
    [s[0] for s in s2]
    # [0, 9, 18, 27]
    [s1[n][i] for n, i in zip(start_n, start_idx)]
    # [0, 9, 18, 27]
    [s[-1] for s in s2]
    # [8, 17, 26, 35]
    [s1[n][i] for n, i in zip(end_n, end_idx)]
    # [8, 17, 26, 35]
    

    【讨论】:

      猜你喜欢
      • 2018-03-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-02-15
      • 1970-01-01
      • 1970-01-01
      • 2018-01-17
      • 1970-01-01
      相关资源
      最近更新 更多