循环通过字典中的2d数组

时间:2018-03-02 12:52:54

标签: arrays python-2.7 dictionary for-loop multidimensional-array

我循环遍历2d数组中的所有值,该数组使用键Band_1

保存在字典中
{'Band_1': array([[0, 0, 0, ..., 0, 0, 0],
   [0, 0, 0, ..., 0, 0, 0],
   [0, 0, 0, ..., 0, 0, 0],
   ...,
   [0, 0, 0, ..., 0, 0, 0],
   [0, 0, 0, ..., 0, 0, 0],
   [0, 0, 0, ..., 0, 0, 0]], dtype=uint16)}

代码运行,但是数组是2650 x 2650,我在每一步都要处理150多个字典,所以它非常慢。

注意:对于此示例,每个字典只有一个键,但情况并非总是如此。

我尝试了3种不同的方法来遍历数组:

方法1:

for key, bands in img.iteritems():
    for pixel in bands:
        for x in pixel:
            if x != noDataVal:
                x = x - dark_val
            else:
                x = noDataVal

方法2:

for key, bands in img.iteritems():
    for pixel in bands.flat:
        if pixel != noDataVal:
            pixel = pixel - dark_val
        else:
            pixel = noDataVal

方法3:

img = {k:[[i-dark_val for i in line if i != noDataVal] for line in data] for k, data in img.items()}

方法4:

for key, band in image.iteritems():
    band = image[key]
    band_m = np.ma.masked_array(band, mask=noDataVal)
    band_m = band_m - dark_val

其中:

dark_val = 75
noDataVal = 0

timeit值超过5个循环,如下所示:

This is the first method: 18.446967368
This is the second method: 18.6967543083
This is the third method: 19.0136934398
This is the fourth method: 0.6860613911

在速度/效率方面对这些方法有何改进?

0 个答案:

没有答案