我有一个名字列表,比如说
m=['l','l','k','j','h','k']
以及与它们对应的值数组:
n = np.array([[1,2,3,4,5,6],[7,8,9,1,2,3]])
我想收缩 m 以便仅包含唯一元素(我可以使用 np.unique 来做到这一点),然后添加数组 n 中两行的相应元素。
我应该如何有效地做到这一点?目前我只能想到迭代m的元素来找到m中所有其他相同的元素,然后收缩n的这些列。效率很低!
编辑:
预期输出:
m=array(['h', 'j', 'k', 'l'], dtype='<U1')
n=np.array([[5,4,9,3],[2,1,12,15]])
最佳答案
您可以使用稀疏矩阵的矩阵乘法来提高效率:
import numpy as np
from scipy import sparse
m=['l','l','k','j','h','k']
n = np.array([[1,2,3,4,5,6],[7,8,9,1,2,3]])
unq, idx = np.unique(m, return_inverse=True)
res = n@sparse.csr_matrix((np.ones_like(idx),idx,np.arange(idx.size+1)))
unq
# array(['h', 'j', 'k', 'l'], dtype='<U1')
res
# array([[ 5, 4, 9, 3],
# [ 2, 1, 12, 15]], dtype=int64)
关于python - 通过 Python 列表收缩类似元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57411181/