我有3247 197x10维矩阵。我需要扫描它们,如果值大于1,则将其设置为1。如果一个值小于或等于1,我想把它设为零。然后,我要把这个修正矩阵加到其他3246个集合的修正矩阵中。到目前为止,我掌握的情况如下:
for i in range(LOWER, UPPER + 1):
fname = file_name+str(i)+".txt"
cur_resfile = np.genfromtxt(fname, delimiter = ",", skiprows = 1)
m_cur = cur_resfile
m_cur[m_cur <= 1] = 0
m_cur[m_cur > 1 ] = 1
m_ongoing = m_ongoing + m_cur
我希望mïu ungoning保存正在运行的总和,以便我可以将其保存到一个文件中。但是,它没有工作,似乎只是在写循环中的最后一个m\u cur。如果我总共运行3次循环,那么有些单元格都有1,所以我希望有几个3。我当然希望有很多2,但我只看到1和0
做我想做的事最好的方法是什么?你知道吗
-根据条件更改值
—获取大量矩阵并逐个元素添加所有元素,为每个单元格创建运行和。你知道吗
正如@RootTwo所建议的,clip()是一个很好的numpy内置程序。但出于性能原因,可以对数据的三维“堆栈”使用矢量化操作。你知道吗
示例:
编辑:添加计时结果并更改我的答案
因此,我的建议似乎是创建一个深度堆栈并使用clip和sum函数的单个应用程序,这是不明智的。我运行了一些计时测试,发现增量方法更快,这很可能是由于分配大的3D数组的分配时间开销造成的。你知道吗
下面是测试,我将数据加载方面分解出来,因为这两种方式都是一样的。下面是ipython中使用
%timeit
宏比较这两种方法的结果。你知道吗因此,这是一个3.7倍的加速通过做这个过程的增量,而不是作为一个单一的操作后,堆叠的数据。你知道吗
你可以用
numpy.clip()
编辑回答提问:
相关问题 更多 >
编程相关推荐