python numpyで最頻値を求める
pythonで、ライブラリnumpyのuniqueを使用して、最頻値を求めるサンプルコードを記述してます。pythonのバージョンは3.10.0でnumpyを使用してます。
環境
- OS windows10 pro 64bit
- python 3.10.0
numpyインストール
numpyをインストールされていない方は、pipでインストールしておきます。
pip install numpy
Successfully installed numpy-1.22.3
unique使い方
uniqueを使用すると、配列データから最頻値を求めることが可能です。
import numpy as np
result, count = np.unique(配列, return_counts=True)
# 最頻値
print( result[count == np.amax(count)] )
以下は、用意した配列から最頻値を求めるサンプルコードとなります。
from unittest import result
import numpy as np
arr = np.array(
[10, 20, 30, 40, 20, 50, 50]
)
result, count = np.unique(arr, return_counts=True)
# 最頻値
print( result[count == np.amax(count)] ) # [20 50]
最頻値が取得されていることが確認できます。
-
前の記事
Dart 文字列の最初にある空白のみを除去する 2023.02.15
-
次の記事
javascript エラー「Uncaught TypeError: regex.test is not a function」の解決方法 2023.02.16
コメントを書く