我有以下课程
def get_percentile(obs,*args):
lstper = []
for arg in args:
lstper.append(np.percentile(obs,arg))
return lstper
get_percentile([1,2,3,4,5],25,50,75)
[2.0, 3.0, 4.0]
class Metric(object):
def __init__(self,*args):
self.max = max(args)
self.median =np.median(args)
self.min = min(args)
self.percentile = get_percentile(args)
我无法理解self.percentile = get_percentile(args)
的正确集合以获得各种百分位数
答案 0 :(得分:1)
解决此问题的一种方法是使用命名关键字参数而不是*args
:
def get_percentile(obs,*args):
if len(args) == 0:
args = [25,50,75] # default to quartiles
lstper = []
for arg in args:
lstper.append(np.percentile(obs,arg))
return lstper
class Metric(object):
def __init__(self, values=[], percentiles=[]):
self.max = max(values)
self.median =np.median(values)
self.min = min(values)
self.percentile = get_percentile(values, percentiles)
行动中:
>>> m = Metric(range(30,300,13), [20,40,60,80])
>>> m.max
290
>>> m.percentile
[[82.0, 134.0, 186.0, 238.0]]
或者,如果您想继续使用args
,您可以在列表(或元组,词组,集合......)中给出值和百分位数。这是必要的,否则无法判断一个人的结局和另一个人的开始:
class Metric(object):
def __init__(self, *args):
if not len(args) == 2:
raise ValueError("Usage: Metric([values],[percentiles])")
values, percentiles = args
self.max = max(values)
self.median =np.median(values)
self.min = min(values)
self.percentile = get_percentile(values, percentiles)
用法与上述相同。