Home > OS >  Efficient way to do math operation between Numpy rows
Efficient way to do math operation between Numpy rows

Time:09-17

The idea is to substract between rows in Numpy array.

Here,list comprehension is proposed. But, I wonder whether there is more efficient and fast.

Currently, the proposed solution is slow when given a large arr

import numpy as np
nfreq=500
arr=np.array([[11850,0,1],
[12310,0,3],
[13924,0,4],
[16690,0,1],
[17082,0,3],
[18746,0,4],
[21956,0,2],
[22324,0,3],
[23694,0,4],
[25382,0,1],
[25776,0,3],
[28592,0,4],
[31676,0,2],
[32028,0,3],
[33498,0,4]])
trange = np.where(arr == 3)[0]
val=[(arr[x,0],(arr[x,0]-arr[x-1,0])/nfreq,(arr[x 1,0]-arr[x,0])/nfreq) for x in trange]
val=np.array(val)

CodePudding user response:

You can try the vectorial equivalent, however as there are 3 separate operation, there is still a bottleneck in merging them into the final array. Efficiency will depend on the number of rows.

np.array([arr[trange, 0],
          (arr[trange, 0]-arr[trange-1, 0])/nfreq,
          (arr[trange 1, 0]-arr[trange, 0])/nfreq]).T

output:

array([[1.2310e 04, 9.2000e-01, 3.2280e 00],
       [1.7082e 04, 7.8400e-01, 3.3280e 00],
       [2.2324e 04, 7.3600e-01, 2.7400e 00],
       [2.5776e 04, 7.8800e-01, 5.6320e 00],
       [3.2028e 04, 7.0400e-01, 2.9400e 00]])

CodePudding user response:

You can try

a = arr[trange, 0]
b = (arr[trange, 0] - arr[trange-1, 0])/nfreq
c = (arr[trange 1, 0] - arr[trange, 0])/nfreq

output = np.stack((a,b,c), axis=1)

# array([[1.2310e 04, 9.2000e-01, 3.2280e 00],
#        [1.7082e 04, 7.8400e-01, 3.3280e 00],
#        [2.2324e 04, 7.3600e-01, 2.7400e 00],
#        [2.5776e 04, 7.8800e-01, 5.6320e 00],
#        [3.2028e 04, 7.0400e-01, 2.9400e 00]])
  • Related