我该如何计算阵列数据

时间:2017-03-15 08:27:01

标签: python numpy

我的问题是

data = [[-10,-2,-10,2,3],[0,20,3,2,-10]]   
data = np.array(data)   
for i in range(0,data.shape[0]):   
   for j in range(0,data.shape[1]):    
        if data[i][j] >= 0:
             data[i][j] = data[i][j] * 1.02* data[i][j]    
        elif data[i][j] <0:    
             data[i][j] = data[i][j] * 1.98*data[i][j]    
        else:    
             data[i][j] = -999999999999999

我想比循环@

更快

helpme ..

1 个答案:

答案 0 :(得分:1)

可能有更好的方法,但使用蒙版会将执行时间缩短一半(至少在我的笔记本电脑上,使用timeit模块)

import numpy as np

# as Divakar pointed out, number of elements should be the same in each row
data = np.asarray([[-10,-2,-10,2,3,4],[0,20,3,2,-10,4]], dtype=np.float)
mask = (data>=0)
mask2 = 1 - mask

# For ndarray, * is element-wise multiplication
data2 = np.square(data)*(mask*1.02 + mask2*1.98)

# Your loop for comparison
for i in range(0,data.shape[0]):   
   for j in range(0,data.shape[1]):    
        if data[i][j] >= 0:
             data[i][j] = data[i][j] * 1.02* data[i][j]    
        elif data[i][j] <0:    
             data[i][j] = data[i][j] * 1.98*data[i][j]    
        else:    
             data[i][j] = -999999999999999

# Output should be the same
print data2
print data