Numpy:独特后的一组ID

Numpy: Group of ids after unique

我正在寻找使用独特的 numpy 函数后组数据的解决方案。 我认为举个例子更好:

>>> t
[[0, 3, 4], [1, 2, 8], [1, 2, 8]] #array of multiples values
>>> ids = ['A', 'B', 'C'] #Ids associated with previous values
>>> np.unique(t, axis=0)
array([[0, 3, 4],
       [1, 2, 8]]) #Result of unique (so 2 rows ofc)
>>> array([['A'],
           ['B', 'C']]) #What i want to got (and generated with numpy ideally)

非常感谢您的帮助。

也许你可以创建一个字典,其中键是来自 t 元素的元组,值是来自 ids

的字母
d = {}
for i in range(len(ids)):
    d.setdefault(tuple(t[i]), []).append(ids[i])
d
# {(0, 3, 4): ['A'], (1, 2, 8): ['B', 'C']}

一位朋友找到了一个很好的方法。 (仅在数据已排序时有效)

import numpy as np

t = np.array([[0, 3, 4], [1, 2, 8], [1, 2, 8]])
ids = np.array(['A', 'B', 'C'])
print(t)
res = np.split(ids, np.unique(t, return_index=True, axis=0)[1][1:])
print(res) # [array(['A'], dtype='<U1'), array(['B', 'C'], dtype='<U1')]