我是Python和numpy的新手,所以我只是运行示例代码并尝试调整它们以便理解。我遇到了一些关于numpy.sum
的代码,其中axis
参数,但我无法运行。在某段时间(阅读scipy文档,尝试实验)后,我通过使用axis = (1,2,3)
而不是axis = 1
来运行它。具有轴行为的python numpy sum函数
事情是,无论我搜索,他们只写axis = 1
让它工作。
我正在使用Python 3.5.3,numpy 1.12.1 是否有一个numpy/python版本在行为上有很大的差异?或者我只是以某种方式配置它是错误的?
import numpy as np
from past.builtins import xrange
# sample data
X = np.arange(1, 4*4*3*5+1).reshape(5, 4, 4, 3)
Y = np.arange(5, 4*4*3*8+5).reshape(8, 4, 4, 3)
Xlen = X.shape[0]
Ylen = Y.shape[0]
# allocate some space for whatever calculation
rs = np.zeros((Xlen, Ylen))
rs1 = np.zeros((Xlen, Ylen))
# calculate the result with 2 loops
for i in xrange(Xlen):
for j in xrange(Ylen):
rs[i, j] = np.sum(X[i] + Y[j])
# calculate the result with one loop only
for i in xrange(Xlen):
rs1[i, :] = np.sum(Y + X[i], axis=(1,2,3))
print(rs1 == rs) # same result
# also with one loop, as everywhere on the internet:
for i in xrange(Xlen):
rs1[i, :] = np.sum(Y + X[i], axis=1)
# ValueError: could not broadcast input array from shape (8,4,3) into shape (8)
'轴= 1'款项你指定一个维度。结果是一个尺寸为'ndim-1'的数组;在你的情况下,它有三个维度和形状'(8,4,3)'。这与输出数组rs1 [i,:]'不兼容,它只有两个维度。 – MaxPowers