我是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