「Python」二次元配列ndarrayの行列ごとに条件を満たす要素数をカウントする

環境
PyCharm 2021.3
Python 3.9.7

構文
変数名 = np.arange(配列の数).reshape((行数, 列数))

二次元配列は引数axis=0で列ごとで条件を満たす要素数をカウントします。
np.count_nonzero(条件式, axis=0)

二次元配列は引数axis=0で行ごとで条件を満たす要素数をカウントします。
np.count_nonzero(条件式, axis=1)

使用例

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
# coding: utf-8
import numpy as np
cft = np.arange(6).reshape((2, 3))
print("二次元配列の要素")
print(cft)
print("列ごとに4以下の要素数をカウント")
print(np.count_nonzero(cft < 4, axis=0))
print("行ごとに4以下の要素数をカウント")
print(np.count_nonzero(cft < 4, axis=1))
print("列ごとに% 2 == 0で要素を比較するカウント結果")
print(np.count_nonzero(cft % 2 == 0,axis=0))
print("行ごとに% 2 == 0で要素を比較するカウント結果")
print(np.count_nonzero(cft % 2 == 0,axis=1))
# coding: utf-8 import numpy as np cft = np.arange(6).reshape((2, 3)) print("二次元配列の要素") print(cft) print("列ごとに4以下の要素数をカウント") print(np.count_nonzero(cft < 4, axis=0)) print("行ごとに4以下の要素数をカウント") print(np.count_nonzero(cft < 4, axis=1)) print("列ごとに% 2 == 0で要素を比較するカウント結果") print(np.count_nonzero(cft % 2 == 0,axis=0)) print("行ごとに% 2 == 0で要素を比較するカウント結果") print(np.count_nonzero(cft % 2 == 0,axis=1))
# coding: utf-8
import numpy as np

cft = np.arange(6).reshape((2, 3))
print("二次元配列の要素")
print(cft)

print("列ごとに4以下の要素数をカウント")
print(np.count_nonzero(cft < 4, axis=0))

print("行ごとに4以下の要素数をカウント")
print(np.count_nonzero(cft < 4, axis=1))

print("列ごとに% 2 == 0で要素を比較するカウント結果")
print(np.count_nonzero(cft % 2 == 0,axis=0))

print("行ごとに% 2 == 0で要素を比較するカウント結果")
print(np.count_nonzero(cft % 2 == 0,axis=1))

実行結果

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
二次元配列の要素
[[0 1 2]
[3 4 5]]
列ごとに4以下の要素数をカウント
[2 1 1]
行ごとに4以下の要素数をカウント
[3 1]
列ごとに% 2 == 0で要素を比較するカウント結果
[1 1 1]
行ごとに% 2 == 0で要素を比較するカウント結果
[2 1]
二次元配列の要素 [[0 1 2] [3 4 5]] 列ごとに4以下の要素数をカウント [2 1 1] 行ごとに4以下の要素数をカウント [3 1] 列ごとに% 2 == 0で要素を比較するカウント結果 [1 1 1] 行ごとに% 2 == 0で要素を比較するカウント結果 [2 1]
二次元配列の要素
[[0 1 2]
 [3 4 5]]
列ごとに4以下の要素数をカウント
[2 1 1]
行ごとに4以下の要素数をカウント
[3 1]
列ごとに% 2 == 0で要素を比較するカウント結果
[1 1 1]
行ごとに% 2 == 0で要素を比較するカウント結果
[2 1]

 

Python

Posted by arkgame