簡體   English   中英

在一維上添加numpy 3D數組

[英]Adding numpy 3D array across one dimension

我有一個具有以下形狀的numpy數組:

(365L, 280L, 300L)

我想對第一個維度(365)上的數組求和,以便得到365個值。

我可以做np.sum() ,但是如何指定哪個軸呢?

- 編輯:

答案應為:(365,)

NumPy版本> = 1.7

np.sum允許使用tuple of integer作為axis參數來一次計算沿多個軸的和:

import numpy as np
arr = ... # somearray

np.sum(arr, axis=(1, 2)) # along axis 1 and 2 (remember the first axis has index 0)
np.sum(arr, axis=(2, 1)) # the order doesn't matter

或直接使用數組的sum方法:

arr.sum(axis=(1, 2))

僅當arr已經是一個numpy數組時,后者才有效。 np.sum工程,即使你的arr是python- list

NumPy版本<1.7:

使用元組作為axis參數的選項尚未實現,但您始終可以嵌套多個np.sum.sum調用:

np.sum(np.sum(arr, axis=1), axis=1)  # Nested sums
arr.sum(axis=2).sum(axis=1)          # identical but more "sequential" than "nested"

嘗試這個:

import numpy

a = numpy.random.random((365L, 280L, 300L)) # just an example

s = numpy.sum(a, axis=(1,2))

print s.shape

> (365,)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM