【问题标题】:Contracting like elements over python lists在 python 列表上收缩类似元素
【发布时间】:2019-08-09 02:54:51
【问题描述】:

我有一个名字列表,比如说

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]])

【问题讨论】:

  • 你说的合同是什么意思?
  • @Chris '合同 m 以便仅包含唯一元素'
  • 那么对应的元素呢?基于m 中已删除元素的索引?我仍然看不到您获得预期输出的逻辑:(
  • 数组 m 最初有 6 个名称/标签。数组 n 是 2x6,每一行对应标签的一个属性,n 中的每一列对应 m 中的第 i 个标签。我需要为相同标签的每条记录添加相同事件的发生。 @克里斯

标签: python arrays numpy


【解决方案1】:

您可以将矩阵乘法与稀疏矩阵一起使用以提高效率:

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)

【讨论】:

    【解决方案2】:

    你可以将np.unique的标志return_index放到True

    import numpy as np
    
    m = np.array(['l','l','k','j','h','k'])
    n = np.array([[1,2,3,4,5,6],[7,8,9,1,2,3]])    
    
    
    unique_elements, unique_indices = np.unique(m, return_index=True)
    
    # you can return the unique elements as well as the corresponding indices        
    print(unique_elements, unique_indices)        
    
    
    # so you get what you want with:
    print(m[unique_indices])
    print(n[:,unique_indices])
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-04-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多