【问题标题】:boosting the speed of relating an array and a dictionary提高关联数组和字典的速度
【发布时间】:2021-01-12 14:20:50
【问题描述】:

我有 3 个数组

a = np.array([[1], [4], [5], [11], [7]])
b = np.array([[14], [3], [2], [10], [12]])
c = np.array([[6], [13], [15], [8], [9]])

我想在每一行中合并和排序它们以获得:

[[ 1  6 14]
 [ 3  4 13]
 [ 2  5 15]
 [ 8 10 11]
 [ 7 9 12]]

并查看从哪个初始数组 (a,b,c) 中选取每个值。所以,我使用了这段代码:

combined = np.concatenate([a, b, c], axis=1)
names = np.array(['a','b','c'])
L = names[np.argsort(combined)]

它给了我这个结果:

[['a' 'c' 'b']
 ['b' 'a' 'c']
 ['b' 'a' 'c']
 ['c' 'b' 'a']
 ['a' 'c' 'b']]

我还有一本字典:

Test = np.array(range(101,116)).reshape((5,3), order = 'F')

[[101 106 111]
 [102 107 112]
 [103 108 113]
 [104 109 114]
 [105 110 115]]

Dic = {'a':Test[:,0], 'b':Test[:,1], 'c':Test[:,2]}

现在我希望使用以下方法将 Dic 与 L 关联起来:

new = []
for i in range(0,3):
    for j in range(0,5):
        
        if L[j,i]=='a':
            H = Dic['a'][j]
            
        elif L[j,i]=='b':
            H = Dic['b'][j]
            
        elif L[j,i]=='c':
            H = Dic['c'][j]
            
        new = np.append(new, H)
        
final = new.reshape((5,3), order = 'F')

给我最终的结果:

[[101. 111. 106.]
 [107. 102. 112.]
 [108. 103. 113.]
 [114. 109. 104.]
 [105. 115. 110.]]

但是,对于我非常大的真实数据集,这个过程需要几个小时。我正在寻找一种更好的方法来加速我的代码。

换句话说,我正在根据第一个数组对第二个数组进行排序。

first array:[['a' 'c' 'b']
             ['b' 'a' 'c']
             ['b' 'a' 'c']
             ['c' 'b' 'a']
             ['a' 'c' 'b']]

second array: [[101 106 111]
              [102 107 112]
              [103 108 113]
              [104 109 114]
              [105 110 115]]

第1、2、3列分别对应'a'、'b'、'c'

【问题讨论】:

    标签: python numpy dictionary


    【解决方案1】:

    只需在此处使用整数而不是字母对names 进行编码(这也是 argsort 的结果)。

    names = np.arange(3)
    

    然后take_along_axis:

    np.take_along_axis(Test, L, 1)
    

    array([[101, 111, 106],
           [107, 102, 112],
           [108, 103, 113],
           [114, 109, 104],
           [105, 115, 110]])
    

    【讨论】:

      【解决方案2】:

      字典上的循环总是很慢。您应该尝试避免使用字典,并改用 numpy 广播。例如:

      import numpy as np
      
      a = np.array([[1], [4], [5], [11], [7]])
      b = np.array([[14], [3], [2], [10], [12]])
      c = np.array([[6], [13], [15], [8], [9]])
      
      combined = np.concatenate([a, b, c], axis=1)
      i = np.argsort(combined)
      
      Test = np.array(range(101,116)).reshape((5,3), order = 'F')
      
      print(Test[np.arange(5)[:, None], i])
      # array([[101, 111, 106],
      #        [107, 102, 112],
      #        [108, 103, 113],
      #        [114, 109, 104],
      #        [105, 115, 110]])
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-10-10
        • 1970-01-01
        • 2014-09-16
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-05-18
        • 1970-01-01
        相关资源
        最近更新 更多