首页 > 解决方案 > 在 for 循环中附加 2d numpy 数组

问题描述

我有以下代码:

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)

我试图让代码计算我的amplitude_split 数组中的每一行是否近似恒定。如果是,我想将该行附加到fastpulse数组中,如果不是,我想将它附加到slowpulse数组中。

我已经使用 np.diff 操作来计算每行中的值之间的差异,并对它们进行平均。我正在使用 for 循环进行附加。即,如果平均差小于 1,则将amplitude_split 行附加到新数组。我认为这是我的问题发生的地方。

我目前的输出fast pulse是:

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

我的预期输出是:

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

标签: pythonarraysnumpy

解决方案


您可以一次处理一排,这似乎更方便。检查 diff 的平均值是否在阈值内。您可以根据需要设置阈值。

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)

推荐阅读