okvoyce
okvoyce

Reputation: 153

Appending 2d numpy array in for loop

I have the following code:

import numpy as np 

#make amplitude array
amplitude=[0,1,2,3, 5.5, 6,5,2,2, 4, 2,3,1,6.5,5,7,1,2,2,3,8,4,9,2,3,4,8,4,9,3]

#split arrays up into a line for each sample
traceno=5                  #number of traces in file
samplesno=6                #number of samples in each trace. This wont change.

amplitude_split=np.array(amplitude, dtype=np.double).reshape((traceno,samplesno))

#Create two new arrays full of zeros, which has row=traceno, and column=samplesno. we can append to this later
fastpulse=np.zeros([traceno,samplesno])
slowpulse=np.zeros([traceno,samplesno])

testsamples=samplesno-1

diff_amp = np.diff(amplitude_split) #calculates the difference between each value in array
ave_dif=np.array(np.sum(diff_amp,1)/testsamples).reshape((testsamples,1)) #calculates the average difference for each line/trace
abs_ave_dif=np.absolute(ave_dif).reshape(testsamples,1)


for row in abs_ave_dif:
    for col in row:
        if col<1:
            np.append(fastpulse,row in amplitude_split) 
        else:
            np.append(slowpulse, row in amplitude_split)
            print(fastpulse)

I am trying to get the code to compute whether each line in my amplitude_split array is approximately constant. If it is, I want to append the line to the fastpulse array, if not I want to append it to the slowpulse array.

I have used the np.diff operation to calculate the difference between the values in each line, and averaged them. I am using a for loop to do the appending. I.e. if the average difference is less than 1 then append amplitude_split row to new array. I think this is where my problem is occurring.

My current output for fast pulse is:

[[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.]]

My expected output is:

[[5 2 2 4 2 3]
 [1 6 5 7 1 2]
 [2 3 8 4 9 2]
 [3 4 8 4 9 3]]

Upvotes: 0

Views: 673

Answers (1)

Zabir Al Nazi Nabil
Zabir Al Nazi Nabil

Reputation: 11198

You can handle one row at a time which seems more convenient. Check if the average value of diff is within a threshold or not. You can set the threshold based on your needs.

import numpy as np 

#make amplitude array
amplitude=[0,1,2,3, 5.5, 6,5,2,2, 4, 2,3,1,6.5,5,7,1,2,2,3,8,4,9,2,3,4,8,4,9,3]

#split arrays up into a line for each sample
traceno=5                  #number of traces in file
samplesno=6                #number of samples in each trace. This wont change.

amplitude_split=np.array(amplitude, dtype=np.double).reshape((traceno,samplesno))

print(amplitude_split)

fastpulse = []

for row in amplitude_split:
  mean_diff = np.mean(np.diff(row))
  print(mean_diff)
  if mean_diff < 0.5:
    fastpulse.append(row)

print(fastpulse)

Upvotes: 1

Related Questions