从一个数组映射到另一个数组的最快方法?

时间:2016-09-19 02:41:17

标签: python arrays numpy

我正在尝试将值从一个数组映射到另一个不同大小的数组,使用第三个数组来提供索引。我已经使用for循环成功实现了这个,但我希望找到一个使用Numpy的更快的方法。到目前为止,我一直在努力找到任何可行的方法。我能找到的最接近的是numpy.put(http://docs.scipy.org/doc/numpy/reference/generated/numpy.put.html)函数,但由于我从一个大数组映射到一个小数组,因此会有许多具有相同索引的值。我想对这些值求和(+ =在索引处),但是numpy.put函数只是覆盖指定索引处的值。

以下是我尝试做的一个例子:

# Create the arrays for this example
import numpy as np

lattice1 = np.zeros(20)
lattice2 = np.zeros(20)

index = [0,4,7,8,9]*40

data = np.array(range(200))

# Make a for-loop to move the data onto the correct position of the lattice
counter=0
for item in data:
    lattice1[index[counter]]+=item
    counter+=1

# Trying to find a faster implementation using Numpy
np.put(lattice2,index,data)

和输出(打印语句从上面的代码中排除,以便于查看):

  

lattice1:

     
    
      

[0. 0 0. 0 0. 0 0. 0 0. 0 0. 0 0. 0 0. 0 0。       0。         0. 0.]

    
  
     

指数:

     
    
      

[0,4,7,8,9,0,4,7,8,9,0,4,7,8,9,0,4,7,8,9,0,4,7,       8,9,7,4,7,8,9,0,4,7,8,9,0,4,7,8,9,8,4,7,8,9,0,       4,7,8,9,8,4,7,8,9,0,4,7,8,9,8,4,7,8,9,0,4,7,8,       9,0,4,7,8,9,0,4,7,8,9,8,4,7,8,9,0,4,7,8,9,0,4,       7,8,9,0,4,7,8,9,0,4,7,8,9,0,4,7,8,9,8,4,7,9,9,       0,4,7,8,9,8,4,7,8,9,0,4,7,8,9,0,4,7,8,9,0,4,7,       8,9,7,4,7,8,9,0,4,7,8,9,0,4,7,8,9,8,4,7,8,9,0,       4,7,8,9,8,4,7,8,9,0,4,7,8,9,8,4,7,8,9,0,4,7,8,       9,0,4,7,8,9,0,4,7,8,9,8,4,7,8,9]

    
  
     

数据:

     
    
      

[0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16       17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33       34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50       51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67       68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84       85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101       102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118       119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135       136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152       153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169       170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186       187 188 189 190 191 192 193 194 195 196 197 198 199]

    
  
     

for循环在正确的晶格上累积具有相同索引的数据   点:

     
    
      

[3900. 0. 0. 0。3940. 0. 0。3980。       4020. 4060            0. 0 0. 0 0. 0 0. 0 0 0. 0。]

    
  
     来自numpy.put的

输出已覆盖具有相同索引的值:

     
    
      

[195. 0. 0 0. 196. 0. 0。197. 198. 199. 0。       0. 0-0.0.0.0.0.0。]

    
  

我的动机是加快这个过程,因为这个for循环比我的其余代码(我能够使用Numpy)慢得多。我操作的阵列大约有6,000,000个元素,我必须在数百个阵列上运行它。因此,速度的小幅增加(5倍?)不仅仅是努力的合理性。

也许我坚持错误的解决方案并且有更好的解决方法,如果所有其他方法都失败了,我可以坚持使用for循环。尽管如此,我们将非常感谢任何见解!

0 个答案:

没有答案
相关问题