python - 在 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]]
解决方案
您可以一次处理一排,这似乎更方便。检查 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)
推荐阅读
- android - 如何使用微调器在 Firebase 和 Android Studio 中显示数据
- javascript - React-highcharts:当某个道具发生变化时,如何阻止图表重新动画?
- python - 新人学习knn算法,希望能帮助解决一个小问题
- spring - 使用 Thymeleaf 和 Spring boot 动态更改 html 标题值
- sql - 在没有 OR 条件的情况下高效加入 hive
- android - 获取“缺口”的高度,这样内容就不会被切断
- python - tkinter 条目小部件未更新
- python - SublimeText3 在 Python 2 中构建,但我想使用 Python 3。如何更改版本(Ubuntu 18.04)?
- tensorflow - tensorflowjs_converter:SavedModel 文件不存在于:
- visual-studio-code - 关闭 > 在新行中