python/numpy를 사용하여 백분위수를 계산하는 방법은 무엇입니까?
시퀀스 또는 1차원 숫자 배열에 대해 백분위수를 계산하는 편리한 방법이 있습니까?
엑셀의 백분위수 함수와 비슷한 것을 찾고 있습니다.
NumPy의 통계 자료를 찾아봤지만, 이것을 찾을 수 없었습니다.중위수(50번째 백분위수)만 찾을 수 있었지만 더 구체적인 것은 찾을 수 없었다.
SciPy Stats 패키지에 관심이 있을 수 있습니다.이것은 여러분이 원하는 백분위수 함수와 다른 많은 통계적 효과를 가지고 있습니다.
percentile()
에서 입수할 수 있습니다.numpy
import numpy as np
a = np.array([1,2,3,4,5])
p = np.percentile(a, 50) # return 50th percentile, e.g median.
print p
3.0
이 티켓은 그들이 통합하지 않을 거라고 믿게끔 한다.percentile()
곧 마비될 거야
덧붙여서, 백분위수 함수의 순수 Python 실장은, scipy에 의존하지 않는 경우에 대비하고 있습니다.함수는 다음과 같이 복사됩니다.
## {{{ http://code.activestate.com/recipes/511478/ (r1)
import math
import functools
def percentile(N, percent, key=lambda x:x):
"""
Find the percentile of a list of values.
@parameter N - is a list of values. Note N MUST BE already sorted.
@parameter percent - a float value from 0.0 to 1.0.
@parameter key - optional key function to compute value from each element of N.
@return - the percentile of the values
"""
if not N:
return None
k = (len(N)-1) * percent
f = math.floor(k)
c = math.ceil(k)
if f == c:
return key(N[int(k)])
d0 = key(N[int(f)]) * (c-k)
d1 = key(N[int(c)]) * (k-f)
return d0+d1
# median is 50th percentile.
median = functools.partial(percentile, percent=0.5)
## end of http://code.activestate.com/recipes/511478/ }}}
import numpy as np
a = [154, 400, 1124, 82, 94, 108]
print np.percentile(a,95) # gives the 95th percentile
다음은 pyon을 사용하지 않고 python만을 사용하여 백분위수를 계산하는 방법입니다.
import math
def percentile(data, perc: int):
size = len(data)
return sorted(data)[int(math.ceil((size * perc) / 100)) - 1]
percentile([10.0, 9.0, 8.0, 7.0, 6.0, 5.0, 4.0, 3.0, 2.0, 1.0], 90)
# 9.0
percentile([142, 232, 290, 120, 274, 123, 146, 113, 272, 119, 124, 277, 207], 50)
# 146
★★★★★Python 3.8
표준 라이브러리는 모듈의 일부로서 다음과 같은 기능이 포함되어 있습니다.
from statistics import quantiles
quantiles([1, 2, 3, 4, 5], n=100)
# [0.06, 0.12, 0.18, 0.24, 0.3, 0.36, 0.42, 0.48, 0.54, 0.6, 0.66, 0.72, 0.78, 0.84, 0.9, 0.96, 1.02, 1.08, 1.14, 1.2, 1.26, 1.32, 1.38, 1.44, 1.5, 1.56, 1.62, 1.68, 1.74, 1.8, 1.86, 1.92, 1.98, 2.04, 2.1, 2.16, 2.22, 2.28, 2.34, 2.4, 2.46, 2.52, 2.58, 2.64, 2.7, 2.76, 2.82, 2.88, 2.94, 3.0, 3.06, 3.12, 3.18, 3.24, 3.3, 3.36, 3.42, 3.48, 3.54, 3.6, 3.66, 3.72, 3.78, 3.84, 3.9, 3.96, 4.02, 4.08, 4.14, 4.2, 4.26, 4.32, 4.38, 4.44, 4.5, 4.56, 4.62, 4.68, 4.74, 4.8, 4.86, 4.92, 4.98, 5.04, 5.1, 5.16, 5.22, 5.28, 5.34, 5.4, 5.46, 5.52, 5.58, 5.64, 5.7, 5.76, 5.82, 5.88, 5.94]
quantiles([1, 2, 3, 4, 5], n=100)[49] # 50th percentile (e.g median)
# 3.0
quantiles
특정 배포에 대한 수익률dist
n - 1
n
간격)dist
n
"CHANGE: "CHANGE: (CHANGE: "CHANGE:
통계 정보정량수(dist, *, n=4, method='displaces')
서 ''는n
는)percentiles
는 )개요100
.
내가 일반적으로 보는 백분위수의 정의에서는 P 퍼센트의 값이 아래에 있는 제공된 목록의 값을 예상합니다.즉, 결과는 집합 요소 간의 보간이 아니라 집합에서 나와야 합니다.그러기 위해서는, 보다 심플한 기능을 사용할 수 있습니다.
def percentile(N, P):
"""
Find the percentile of a list of values
@parameter N - A list of values. N must be sorted.
@parameter P - A float value from 0.0 to 1.0
@return - The percentile of the values.
"""
n = int(round(P * len(N) + 0.5))
return N[n-1]
# A = (1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
# B = (15, 20, 35, 40, 50)
#
# print percentile(A, P=0.3)
# 4
# print percentile(A, P=0.8)
# 9
# print percentile(B, P=0.3)
# 20
# print percentile(B, P=0.8)
# 50
P 퍼센트의 값이 검출된 값보다 낮은 값을 제공 리스트에서 취득하는 경우는, 다음의 간단한 변경을 사용합니다.
def percentile(N, P):
n = int(round(P * len(N) + 0.5))
if n > 1:
return N[n-2]
else:
return N[0]
또는 @ijustlovemath가 제안하는 단순화를 통해:
def percentile(N, P):
n = max(int(round(P * len(N) + 0.5)), 2)
return N[n-2]
scipy.disc 모듈을 확인합니다.
scipy.stats.scoreatpercentile
시리즈의 백분위수를 계산하려면 다음을 수행합니다.
from scipy.stats import rankdata
import numpy as np
def calc_percentile(a, method='min'):
if isinstance(a, list):
a = np.asarray(a)
return rankdata(a, method=method) / float(len(a))
예를 들어 다음과 같습니다.
a = range(20)
print {val: round(percentile, 3) for val, percentile in zip(a, calc_percentile(a))}
>>> {0: 0.05, 1: 0.1, 2: 0.15, 3: 0.2, 4: 0.25, 5: 0.3, 6: 0.35, 7: 0.4, 8: 0.45, 9: 0.5, 10: 0.55, 11: 0.6, 12: 0.65, 13: 0.7, 14: 0.75, 15: 0.8, 16: 0.85, 17: 0.9, 18: 0.95, 19: 1.0}
1차원 numpy 시퀀스 또는 행렬에 대한 백분위수를 계산하는 편리한 방법은 numpy를 사용하는 것입니다.percentile < https://docs.scipy.org/doc/numpy/reference/generated/numpy.percentile.html > 。예:
import numpy as np
a = np.array([0,1,2,3,4,5,6,7,8,9,10])
p50 = np.percentile(a, 50) # return 50th percentile, e.g median.
p90 = np.percentile(a, 90) # return 90th percentile.
print('median = ',p50,' and p90 = ',p90) # median = 5.0 and p90 = 9.0
그러나 데이터에 NaN 값이 있는 경우 위의 함수는 유용하지 않습니다.이 경우 numpy.nan percentile <https://docs.scipy.org/doc/numpy/reference/generated/numpy.nanpercentile.html> 함수를 사용하는 것이 좋습니다.
import numpy as np
a_NaN = np.array([0.,1.,2.,3.,4.,5.,6.,7.,8.,9.,10.])
a_NaN[0] = np.nan
print('a_NaN',a_NaN)
p50 = np.nanpercentile(a_NaN, 50) # return 50th percentile, e.g median.
p90 = np.nanpercentile(a_NaN, 90) # return 90th percentile.
print('median = ',p50,' and p90 = ',p90) # median = 5.5 and p90 = 9.1
위에 제시된 두 가지 옵션에서도 보간 모드를 선택할 수 있습니다.이해하기 쉽게 하기 위해 다음 예를 따르십시오.
import numpy as np
b = np.array([1,2,3,4,5,6,7,8,9,10])
print('percentiles using default interpolation')
p10 = np.percentile(b, 10) # return 10th percentile.
p50 = np.percentile(b, 50) # return 50th percentile, e.g median.
p90 = np.percentile(b, 90) # return 90th percentile.
print('p10 = ',p10,', median = ',p50,' and p90 = ',p90)
#p10 = 1.9 , median = 5.5 and p90 = 9.1
print('percentiles using interpolation = ', "linear")
p10 = np.percentile(b, 10,interpolation='linear') # return 10th percentile.
p50 = np.percentile(b, 50,interpolation='linear') # return 50th percentile, e.g median.
p90 = np.percentile(b, 90,interpolation='linear') # return 90th percentile.
print('p10 = ',p10,', median = ',p50,' and p90 = ',p90)
#p10 = 1.9 , median = 5.5 and p90 = 9.1
print('percentiles using interpolation = ', "lower")
p10 = np.percentile(b, 10,interpolation='lower') # return 10th percentile.
p50 = np.percentile(b, 50,interpolation='lower') # return 50th percentile, e.g median.
p90 = np.percentile(b, 90,interpolation='lower') # return 90th percentile.
print('p10 = ',p10,', median = ',p50,' and p90 = ',p90)
#p10 = 1 , median = 5 and p90 = 9
print('percentiles using interpolation = ', "higher")
p10 = np.percentile(b, 10,interpolation='higher') # return 10th percentile.
p50 = np.percentile(b, 50,interpolation='higher') # return 50th percentile, e.g median.
p90 = np.percentile(b, 90,interpolation='higher') # return 90th percentile.
print('p10 = ',p10,', median = ',p50,' and p90 = ',p90)
#p10 = 2 , median = 6 and p90 = 10
print('percentiles using interpolation = ', "midpoint")
p10 = np.percentile(b, 10,interpolation='midpoint') # return 10th percentile.
p50 = np.percentile(b, 50,interpolation='midpoint') # return 50th percentile, e.g median.
p90 = np.percentile(b, 90,interpolation='midpoint') # return 90th percentile.
print('p10 = ',p10,', median = ',p50,' and p90 = ',p90)
#p10 = 1.5 , median = 5.5 and p90 = 9.5
print('percentiles using interpolation = ', "nearest")
p10 = np.percentile(b, 10,interpolation='nearest') # return 10th percentile.
p50 = np.percentile(b, 50,interpolation='nearest') # return 50th percentile, e.g median.
p90 = np.percentile(b, 90,interpolation='nearest') # return 90th percentile.
print('p10 = ',p10,', median = ',p50,' and p90 = ',p90)
#p10 = 2 , median = 5 and p90 = 9
입력 배열이 정수 값으로만 구성된 경우 백분율 응답을 정수로 사용할 수 있습니다.이 경우 '낮음', '높음' 또는 '가장 가까운'과 같은 보간 모드를 선택합니다.
입력 numpy 배열의 멤버가 되기 위해 답변이 필요한 경우:
디폴트로는 numpy 단위의 백분위수 함수가 입력 벡터의 2개의 인접 엔트리의 선형 가중 평균으로 출력을 계산합니다.경우에 따라서는 반환된 백분위수가 벡터의 실제 요소가 되기를 원할 수 있습니다. 이 경우 v1.9.0 이후부터는 "낮음", "높음" 또는 "가장 가까운" 옵션을 사용할 수 있습니다.
import numpy as np
x=np.random.uniform(10,size=(1000))-5.0
np.percentile(x,70) # 70th percentile
2.075966046220879
np.percentile(x,70,interpolation="nearest")
2.0729677997904314
후자는 벡터의 실제 엔트리이고, 전자는 백분위수에 인접한 두 벡터 엔트리의 선형 보간이다.
영상 시리즈: 사용된 함수 설명
다음과 같은 열 sales 및 id를 가진 df가 있다고 가정합니다.판매에 대한 백분위수를 계산하려고 하면 다음과 같이 작동합니다.
df['sales'].describe(percentiles = [0.0,0.1,0.2,0.3,0.4,0.5,0.6,0.7,0.8,0.9,1])
0.0: .0: minimum
1: maximum
0.1 : 10th percentile and so on
데이터를 부트스트랩하고 10개의 샘플에 대한 신뢰구간을 플롯했습니다.신뢰 구간은 확률이 5%와 95% 사이의 범위를 나타냅니다.
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
import numpy as np
import json
import dc_stat_think as dcst
data = [154, 400, 1124, 82, 94, 108]
#print (np.percentile(data,[0.5,95])) # gives the 95th percentile
bs_data = dcst.draw_bs_reps(data, np.mean, size=6*10)
#print(np.reshape(bs_data,(24,6)))
x= np.linspace(1,6,6)
print(x)
for (item1,item2,item3,item4,item5,item6) in bs_data.reshape((10,6)):
line_data=[item1,item2,item3,item4,item5,item6]
ci=np.percentile(line_data,[.025,.975])
mean_avg=np.mean(line_data)
fig, ax = plt.subplots()
ax.plot(x,line_data)
ax.fill_between(x, (line_data-ci[0]), (line_data+ci[1]), color='b', alpha=.1)
ax.axhline(mean_avg,color='red')
plt.show()
언급URL : https://stackoverflow.com/questions/2374640/how-do-i-calculate-percentiles-with-python-numpy
'source' 카테고리의 다른 글
MySQL/MariaDB - 쿼리의 HAVING 부분 내에서 SELECT 쿼리의 필드 값을 덮어씁니다. (0) | 2022.09.05 |
---|---|
Java Lombok:@AllArgsConstructor에서 필드 하나를 생략하시겠습니까? (0) | 2022.09.04 |
EC2-classic의 소스 끝점과 관련된 AWS DMS 문제 (0) | 2022.09.04 |
Android에서 c++에서 Java 메서드 호출 (0) | 2022.09.04 |
java.sql에서 열 이름을 검색합니다.결과 세트 (0) | 2022.09.04 |