簡體   English   中英

在pandas中,如何找到累積和大於閾值的行/索引?

[英]In pandas, how to find the row/index where the cumulative sum is greater than a threshold?

我想找到某一列中值的累積總和超過閾值的行(索引)。

我可以並且確實使用一個簡單的循環找到這個位置,如下所示:

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中是否有更好/更好的方法來實現這一目標。

最簡單的方法可能就是

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

但這假設您的列中沒有負數。

所以你想要這樣的東西:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM