如何只使用numpy迭代迭代某个轴矩阵?

时间:2017-01-31 13:24:22

标签: python numpy matrix iteration

我想使用numpy函数(特定向量)迭代矩阵内的某个轴。

假设我们有矩阵A,即A.shape(2,3,4)

[[[1,2,3,4],[5,7,8,9-],[1,2,3,4]],[[5,7,8,9-],[1, 2,3,4],[5,7,8,9-]]]

例如,如果我想仅迭代axis = 2 迭代= 6

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

最快的方法是什么?

我尝试使用numpy.nditer,但我完全陷入困境。 我认为确定使用“external_loop”参数但仍然不知道该怎么做。

A_list= np.random.randn(400,400,3)

start_time = time.time()
sum = 0

for i in range(0,400):
    for j in range(0, 400):
        sum += A_list[i][j]

print sum
print("--- %s seconds ---" % (time.time() - start_time))

sum = 0
start_time = time.time()

for x in A_list.reshape(-1,A_list.shape[-1]):
    sum += x


print sum
print("--- %s seconds ---" % (time.time() - start_time))

sum = 0
start_time = time.time()

for x in np.vstack(A_list):
    sum += x


print sum
print("--- %s seconds ---" % (time.time() - start_time))

结果:

[-196.06613179  643.99881703  264.0386004 ]
--- 0.186000108719 seconds ---
[-196.06613179  643.99881703  264.0386004 ]
--- 0.134000062943 seconds ---
[-196.06613179  643.99881703  264.0386004 ]
--- 0.128999948502 seconds ---

0 个答案:

没有答案