[NumPy]配列の行、列ごとの合計値を取得するサンプル

環境
PyCharm 2021.3
Python 3.9.7

構文
1.合計
np.sum()に配列ndarrayを渡すと、すべての要素の合計値が取得されます。

2.列、行ごとの合計値
引数axisに0を渡すと列ごとの合計値、1を渡すと行ごとの合計値が取得されます

使用例

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
import numpy as np
#3 x 4の配列
cft = np.arange(12).reshape(3, 4)
print(cft.shape)
print("配列の要素")
print(cft)
print("すべての要素の合計値")
print(np.sum(cft))
print("列ごとの合計値")
print(np.sum(cft, axis=0))
print("行ごとの合計値")
print(np.sum(cft, axis=1))
import numpy as np #3 x 4の配列 cft = np.arange(12).reshape(3, 4) print(cft.shape) print("配列の要素") print(cft) print("すべての要素の合計値") print(np.sum(cft)) print("列ごとの合計値") print(np.sum(cft, axis=0)) print("行ごとの合計値") print(np.sum(cft, axis=1))
import numpy as np

#3 x 4の配列
cft = np.arange(12).reshape(3, 4)
print(cft.shape)
print("配列の要素")
print(cft)

print("すべての要素の合計値")
print(np.sum(cft))

print("列ごとの合計値")
print(np.sum(cft, axis=0))

print("行ごとの合計値")
print(np.sum(cft, axis=1))

実行結果

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
(3, 4)
配列の要素
[[ 0 1 2 3]
[ 4 5 6 7]
[ 8 9 10 11]]
すべての要素の合計値
66
列ごとの合計値
[12 15 18 21]
行ごとの合計値
[ 6 22 38]
(3, 4) 配列の要素 [[ 0 1 2 3] [ 4 5 6 7] [ 8 9 10 11]] すべての要素の合計値 66 列ごとの合計値 [12 15 18 21] 行ごとの合計値 [ 6 22 38]
(3, 4)
配列の要素
[[ 0  1  2  3]
 [ 4  5  6  7]
 [ 8  9 10 11]]
すべての要素の合計値
66
列ごとの合計値
[12 15 18 21]
行ごとの合計値
[ 6 22 38]

 

NumPy

Posted by arkgame