Numpy 배열 모드를 계산하는 방법(예제 포함)
다음 기본 구문을 사용하여 NumPy 배열의 모드를 찾을 수 있습니다.
#find unique values in array along with their counts
vals, counts = np. unique (array_name, return_counts= True )
#find fashion
mode_value = np. argwhere (counts == np. max (counts))
모드는 표에 가장 자주 나타나는 값이라는 점을 기억하세요.
어레이에는 하나 이상의 모드가 있을 수 있습니다.
다음 예에서는 이 구문을 실제로 사용하는 방법을 보여줍니다.
예제 1: 단일 모드로 NumPy 배열 모드 계산
다음 코드는 모드가 하나만 있는 NumPy 배열의 모드를 찾는 방법을 보여줍니다.
import numpy as np #create NumPy array of values with only one mode x = np. array ([2, 2, 2, 3, 4, 4, 5, 5, 5, 5, 7]) #find unique values in array along with their counts vals, counts = np. unique (x, return_counts= True ) #find fashion mode_value = np. argwhere (counts == np. max (counts)) #print list of modes print (vals[mode_value] .flatten (). tolist ()) [5] #find how often mode occurs print (np. max (counts)) 4
출력에서 모드가 5 이고 NumPy 배열에서 4 번 발생한다는 것을 알 수 있습니다.
예제 2: 여러 모드로 NumPy 배열을 계산하는 방법
다음 코드는 여러 모드가 있는 NumPy 배열의 모드를 찾는 방법을 보여줍니다.
import numpy as np #create NumPy array of values with multiple modes x = np. array ([2, 2, 2, 3, 4, 4, 4, 5, 5, 5, 7]) #find unique values in array along with their counts vals, counts = np. unique (x, return_counts= True ) #find fashion mode_value = np. argwhere (counts == np. max (counts)) #print list of modes print (vals[mode_value] .flatten (). tolist ()) [2, 4, 5] #find how often mode occurs print (np. max (counts)) 3
출력에서 이 NumPy 배열에는 2 , 4 , 5 의 세 가지 모드가 있음을 알 수 있습니다.
또한 이러한 각 값이 표에 3 번씩 나타나는 것을 볼 수 있습니다.
추가 리소스
다음 튜토리얼에서는 NumPy에서 다른 일반적인 작업을 수행하는 방법을 설명합니다.
NumPy 배열에 함수를 매핑하는 방법
NumPy 배열에서 값 인덱스를 찾는 방법
NumPy를 사용하여 벡터의 크기를 계산하는 방법