「NumPy」多次元配列の行、列ごとの合計値を取得する
環境
PyCharm 2021.3
Python 3.9.7
構文
多次元配列名 = np.arange(数値).reshape(値1, 値2, 値3)
多次元配列名.sum(axis=0)
引数axisに0を渡すと列ごとの合計値を取得します。
多次元配列名.sum(axis=1)
引数axisに1を渡すと行ごとの合計値を取得します。
使用例
import numpy as np
cft = np.arange(24).reshape(2, 3, 4)
print(cft.shape)
print("すべての要素の合計値")
print(cft)
print("列ごとの合計値")
print(cft.sum(axis=0))
print("行ごとの合計値")
print(cft.sum(axis=1))
import numpy as np
cft = np.arange(24).reshape(2, 3, 4)
print(cft.shape)
print("すべての要素の合計値")
print(cft)
print("列ごとの合計値")
print(cft.sum(axis=0))
print("行ごとの合計値")
print(cft.sum(axis=1))
import numpy as np cft = np.arange(24).reshape(2, 3, 4) print(cft.shape) print("すべての要素の合計値") print(cft) print("列ごとの合計値") print(cft.sum(axis=0)) print("行ごとの合計値") print(cft.sum(axis=1))
実行結果
(2, 3, 4)
すべての要素の合計値
[[[ 0 1 2 3]
[ 4 5 6 7]
[ 8 9 10 11]]
[[12 13 14 15]
[16 17 18 19]
[20 21 22 23]]]
列ごとの合計値
[[12 14 16 18]
[20 22 24 26]
[28 30 32 34]]
行ごとの合計値
[[12 15 18 21]
[48 51 54 57]]
(2, 3, 4)
すべての要素の合計値
[[[ 0 1 2 3]
[ 4 5 6 7]
[ 8 9 10 11]]
[[12 13 14 15]
[16 17 18 19]
[20 21 22 23]]]
列ごとの合計値
[[12 14 16 18]
[20 22 24 26]
[28 30 32 34]]
行ごとの合計値
[[12 15 18 21]
[48 51 54 57]]
(2, 3, 4) すべての要素の合計値 [[[ 0 1 2 3] [ 4 5 6 7] [ 8 9 10 11]] [[12 13 14 15] [16 17 18 19] [20 21 22 23]]] 列ごとの合計値 [[12 14 16 18] [20 22 24 26] [28 30 32 34]] 行ごとの合計値 [[12 15 18 21] [48 51 54 57]]