无限上下界切割Pandas

2024-05-12 02:31:56 发布

您现在位置:Python中文网/ 问答频道 /正文

pandas ^{} documentation声明:“结果的分类对象中的越界值将是NA。”这使得当上界不一定清晰或重要时变得困难。例如:

cut (weight, bins=[10,50,100,200])

将产生垃圾箱:

[(10, 50] < (50, 100] < (100, 200]]

所以cut (250, bins=[10,50,100,200])会产生NaN,也会产生cut (5, bins=[10,50,100,200])。我要做的是为第一个示例生成> 200,为第二个示例生成< 10

我知道我可以做cut (weight, bins=[float("inf"),10,50,100,200,float("inf")])或类似的工作,但是我所遵循的报表样式不允许像(200, inf]这样的事情。我也意识到我可以通过cut()上的labels参数指定自定义标签,但这意味着每次调整bins时都要记住调整它们,这可能是经常的。

我是否已经用尽了所有的可能性,或者在cut()或者pandas的其他地方有什么东西可以帮助我做到这一点?我正在考虑为cut()编写一个包装函数,它将自动从容器中生成所需格式的标签,但我想先检查一下这里。


Tags: 对象声明示例pandasdocumentation分类标签float
2条回答

您可以在bin列表中使用float("inf")作为上限,使用-float("inf")作为下限。它将删除NaN值。

在等待了几天之后,仍然没有发布任何答案——我想这可能是因为除了编写cut()包装器函数之外,实在没有别的办法来解决这个问题。我在这里发布我的版本,并将问题标记为已回答。如果有新的答案,我会改的。

def my_cut (x, bins,
            lower_infinite=True, upper_infinite=True,
            **kwargs):
    r"""Wrapper around pandas cut() to create infinite lower/upper bounds with proper labeling.

    Takes all the same arguments as pandas cut(), plus two more.

    Args :
        lower_infinite (bool, optional) : set whether the lower bound is infinite
            Default is True. If true, and your first bin element is something like 20, the
            first bin label will be '<= 20' (depending on other cut() parameters)
        upper_infinite (bool, optional) : set whether the upper bound is infinite
            Default is True. If true, and your last bin element is something like 20, the
            first bin label will be '> 20' (depending on other cut() parameters)
        **kwargs : any standard pandas cut() labeled parameters

    Returns :
        out : same as pandas cut() return value
        bins : same as pandas cut() return value
    """

    # Quick passthru if no infinite bounds
    if not lower_infinite and not upper_infinite:
        return pd.cut(x, bins, **kwargs)

    # Setup
    num_labels      = len(bins) - 1
    include_lowest  = kwargs.get("include_lowest", False)
    right           = kwargs.get("right", True)

    # Prepend/Append infinities where indiciated
    bins_final = bins.copy()
    if upper_infinite:
        bins_final.insert(len(bins),float("inf"))
        num_labels += 1
    if lower_infinite:
        bins_final.insert(0,float("-inf"))
        num_labels += 1

    # Decide all boundary symbols based on traditional cut() parameters
    symbol_lower  = "<=" if include_lowest and right else "<"
    left_bracket  = "(" if right else "["
    right_bracket = "]" if right else ")"
    symbol_upper  = ">" if right else ">="

    # Inner function reused in multiple clauses for labeling
    def make_label(i, lb=left_bracket, rb=right_bracket):
        return "{0}{1}, {2}{3}".format(lb, bins_final[i], bins_final[i+1], rb)

    # Create custom labels
    labels=[]
    for i in range(0,num_labels):
        new_label = None

        if i == 0:
            if lower_infinite:
                new_label = "{0} {1}".format(symbol_lower, bins_final[i+1])
            elif include_lowest:
                new_label = make_label(i, lb="[")
            else:
                new_label = make_label(i)
        elif upper_infinite and i == (num_labels - 1):
            new_label = "{0} {1}".format(symbol_upper, bins_final[i])
        else:
            new_label = make_label(i)

        labels.append(new_label)

    # Pass thru to pandas cut()
    return pd.cut(x, bins_final, labels=labels, **kwargs)

相关问题 更多 >