我有2个numpy阵列,如下所示:
#[ 3 5 6 8 8 9 9 9 10 10 10 11 11 12 13 14] #rows
#[11 7 11 4 7 2 4 7 2 4 7 4 7 7 11 11] #cols
我要查找所有匹配集,例如:
3 6 13 14行与第11行匹配
5 8 9 10 11 12从行匹配2 4 7在cols中
有没有直接的方法可以做到这一点?没有空白值,行和列大小将相同
我尝试过的(循环,但不是最有效的):
#first get array of indices, sorted by unique element
idx_sort = np.argsort(cols)
# sorts records array so all unique elements are together
sorted_records_array = cols[idx_sort]
# returns the unique values, the index of the first occurrence of a value, and the count for each element
vals, idx_start, count = np.unique(sorted_records_array, return_counts=True, return_index=True)
# splits the indices into separate arrays
res = np.split(idx_sort, idx_start[1:])
#Using looping I use intersections and concatenate to group sets:
for cntr,itm in enumerate(res):
idx = rows[itm]
for cntr2,itm2 in enumerate(res):
if cntr != cntr2:
intersectItems = np.intersect1d(rows[itm], rows[itm2])
if intersectItems.size > 0:
#print('intersectItems',intersectItems)
res[cntr] = np.unique(np.concatenate((res[cntr], res[cntr2]), axis=0))
我还需要找到并删除重复项,因为我在这里的输出是[3 6 13 14]、[11 11 11]
IIUC,你可以这样做:
输出
也许通过查看反向字典更容易理解:
输出反向字典
正如您可以从上面看到的
14,13,6,3
匹配到11
和12,5,11,8,10,9
匹配到7,4,2
您可以使用字典理解(嵌入列表理解):
相关问题 更多 >
编程相关推荐