【问题标题】:.append() method won't work in my defined function.append() 方法在我定义的函数中不起作用
【发布时间】:2021-01-02 12:57:04
【问题描述】:

我正在尝试定义一个函数来获取与给定分布的数字对应的百分位数。

这是我定义函数的方式:

def minimum_percentile(sample, number):
    percentiles = []
    for i in range(100):
        percentile = np.percentile(sample, i)
        if percentile.any() >= number:
            percentiles.append(percentile)
        else:
            continue
    return min(percentiles)

当我调用函数时:

minimum_percentile(packages_means, 33.1388)

我得到的错误与我的函数似乎没有填充空列表有关,收到以下错误消息:

---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-64-9923821f6175> in <module>
----> 1 minimum_percentile(packages_means, 33.1388)

<ipython-input-63-955dedc13fde> in minimum_percentile(sample, number)
      5         if percentile.any() >= number:
      6             percentiles.append(percentile)
----> 7     return min(percentiles)

ValueError: min() arg is an empty sequence

我的代码有什么问题?

【问题讨论】:

  • 您没有在(空的)percentiles 列表中添加任何内容,您没有这样做的原因可能是因为您的 percentile.any() &gt;= number 没有按照您的想法进行操作。
  • Append 工作正常。你需要调试你的代码。这正是 MCVE 很重要的原因。如果你不显示它是如何调用的,那么显示你编写的函数是没有意义的。
  • if percentile.any() &gt;= number: 更改为if (percentile &gt;= number).any():
  • 根据您的回答,我投票决定关闭,因为您似乎误读了有关百分位数排序方式的文档。

标签: python numpy statistics append percentile


【解决方案1】:

我对您的代码进行了一些操作,看起来 min() 函数不起作用,因为您的列表“百分位数”为空。所以我添加了一个部分,我检查列表是否为空,程序应该返回“无”,这就是我得到的:

import numpy as np
def minimum_percentile(sample, number):
    percentiles = []
    for i in range(100):
        percentile = np.percentile(sample, i)
        if percentile >= number:
            percentiles.append(percentile)

        else:
            continue
    if not percentiles:
        return "None"
    else:
        return min(percentiles)
l = [1,2,3,4,5]
minimum_percentile(l, 2.5)

2.52

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-08-11
    • 2021-01-02
    • 2020-06-20
    • 2012-02-18
    • 2012-10-11
    • 2018-12-06
    • 2018-08-04
    相关资源
    最近更新 更多