【问题标题】:In pandas, how to find the row/index where the cumulative sum is greater than a threshold?在 pandas 中,如何找到累积总和大于阈值的行/索引?
【发布时间】:2017-12-14 00:17:45
【问题描述】:

我想找到某列中值的累积总和超过阈值的行(索引)。

我可以并且确实可以使用简单的循环找到这个位置,如下所示:

def sum_to(df, col, threshold):
    s = 0
    for r in df.iterrows():
        if s + r[1][col] > threshold:
            return r[0]
        else:
            s += r[1][col]

    return len(df)

但是,我想知道在 Pandas 中是否有更好/更好的方法来实现这一点。

【问题讨论】:

  • 是的。有个更好的方法。我们可以看到您的数据以文本形式编辑到您的问题中吗?希望这不是太多的要求,它确实让回答问题时的生活变得轻松。

标签: python pandas


【解决方案1】:

最简单的方法大概是

df[col].cumsum().searchsorted(threshold)

但这假设您的列中没有负数。

【讨论】:

  • 不,我没有负值。这会很好用。谢谢!
【解决方案2】:

所以你想要这样的东西:

df = pd.DataFrame({'A': [1, 2, 3, 4, 5]})
df[df['A'].cumsum() > 5]
#  A
#2 3
#3 4
#4 5

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-03-26
    • 2020-03-30
    • 2019-02-15
    • 2020-09-13
    • 1970-01-01
    • 2021-10-28
    • 1970-01-01
    • 2021-02-28
    相关资源
    最近更新 更多