「NumPy」mean()で配列の行、列の平均値を取得するサンプル

環境
PyCharm 2021.3
Python 3.9.7

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

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

使用例

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

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

print("すべての要素の平均値")
print(np.mean(cft))

print("列ごとの平均値")
print(np.mean(cft, axis=0))

print("行ごとの平均値")
print(np.mean(cft, axis=1))

実行結果

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
(4, 4)
配列の要素
[[ 0 1 2 3]
[ 4 5 6 7]
[ 8 9 10 11]
[12 13 14 15]]
すべての要素の平均値
7.5
列ごとの平均値
[6. 7. 8. 9.]
行ごとの平均値
[ 1.5 5.5 9.5 13.5]
(4, 4) 配列の要素 [[ 0 1 2 3] [ 4 5 6 7] [ 8 9 10 11] [12 13 14 15]] すべての要素の平均値 7.5 列ごとの平均値 [6. 7. 8. 9.] 行ごとの平均値 [ 1.5 5.5 9.5 13.5]
(4, 4)
配列の要素
[[ 0  1  2  3]
 [ 4  5  6  7]
 [ 8  9 10 11]
 [12 13 14 15]]
すべての要素の平均値
7.5
列ごとの平均値
[6. 7. 8. 9.]
行ごとの平均値
[ 1.5  5.5  9.5 13.5]

 

NumPy

Posted by arkgame