方法一
我们可以使用 np.unique
和 np.bincount
的组合 -
In [48]: unq, ids = np.unique(A, return_inverse=True)
In [49]: dict(zip(unq, np.bincount(ids, b)))
Out[49]:
{'a-1': 11.210000000000001,
'b-1': 4.4400000000000004,
'c-2': 11.199999999999999}
因此,
np.unique
为
A
中的每个字符串提供了唯一的整数映射,然后将这些整数作为箱子用于基于权重的加权求和,其中权重来源于
b
。
方法2(特定情况)
假设 A
中的字符串始终是3
个字符,则更快的方法是将这些字符串转换为数字,并将其用作 np.unique
的输入。 这种方法的想法是,np.unique
在数字上的工作比在字符串上的工作快。
因此,实现如下 -
In [141]: n = A.view(np.uint8).reshape(-1,3).dot(256**np.arange(3))
In [142]: unq, st, ids = np.unique(n, return_index=1, return_inverse=1)
In [143]: dict(zip(A[st], np.bincount(ids, b)))
Out[143]:
{'a-1': 11.210000000000001,
'b-1': 4.4400000000000004,
'c-2': 11.199999999999999}
神奇的是,重塑后的 viewing
仍然保持为视图,因此应该非常高效:
In [150]: np.shares_memory(A,A.view(np.uint8).reshape(-1,3))
Out[150]: True
我们可以使用np.unique
的axis
参数(在1.13.0
中添加的功能)
In [160]: A2D = A.view(np.uint8).reshape(-1,3)
In [161]: unq, st, ids = np.unique(A2D, axis=0, return_index=1, return_inverse=1)
In [162]: dict(zip(A[st], np.bincount(ids, b)))
Out[162]:
{'a-1': 11.210000000000001,
'b-1': 4.4400000000000004,
'c-2': 11.199999999999999}