使用percentile
计算分位点:
import numpy as np
data = [1, 2, 3, 4, 5, 6, 7, 8, 9, ]
print(np.percentile(data, 50)) # 50% 分位点
print(np.percentile(data, 20)) # 20% 分位点
在此基础上,可以使用如下函数得到分位点对应的区间:
import numpy as np
import pandas as pd
def transfer_value(series: pd.Series):
type_value = pd.Series(data=4, index=series.index)
value_5 = np.percentile(series.values, 5)
value_20 = np.percentile(series.values, 20)
value_75 = np.percentile(series.values, 75)
type_value[series < value_75] = 3 # 将低于75分位点的标记为3
type_value[series < value_20] = 2 # 将低于20分位点的标记为2
type_value[series < value_5] = 1 # 将低于5分位点的标记为1
return type_value
if __name__ == '__main__':
data = pd.Series(range(11))
print(transfer_value(data))