0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

numpy.sumのaxisは-1を指定した場合はどう言う意味?

Last updated at Posted at 2023-08-02

numpy.sum関数において、axisパラメータに-1を指定すると、最後の次元に沿った和を計算します。

例えば、もし2次元配列(行列)を持っている場合、axis=-1は各行の要素の和を計算します。3次元配列の場合、それぞれの2次元スライスの各行の要素の和を計算します。このように、axis=-1は常に最後の次元に沿って和を取ります。

2次元配列の例:

import numpy as np

arr = np.array([[1, 2], [3, 4]])
result = np.sum(arr, axis=-1)
print(result)
#[3, 7]

3次元配列の場合:

arr = np.array([[[1, 2], [3, 4]], [[5, 6], [7, 8]]])
result = np.sum(arr, axis=-1)
print(result)
# [[3, 7],
#  [11, 15]]

この方法で、配列の形状が変わっても同じ次元に対して和を取るコードを書くことができます。

他にも色々比較してみます

#3x2
arr = np.array([[1,2],[3,4],[5,6]])
result = np.sum(arr,axis=-1)
print(result)
#[ 3  7 11]

result = np.sum(arr,axis=1)
print(result)
#[ 3  7 11]

result = np.sum(arr,axis=0)
print(result)
#[ 9 12]
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?