簡體   English   中英

基於超過閾值的Pandas重采樣

[英]Pandas Resampling based on Value exceeding threshold

我有一個包含2列的數據庫。

import pandas as pd
data = pd.DataFrame({'a':[1,2,1,4,1,1,3,1,4,1,1,1],'b':[5,2,8,3,10,3,5,15,45,41,23,9]}) 

    a   b
0   1   5
1   2   2
2   1   8
3   4   3
4   1   10
5   1   3
6   3   5
7   1   15
8   4   45
9   1   41
10  1   23
11  1   9

每當自上次發生以來的累積值超過列a的給定閾值時,是否有一種pythonic /最快的方法來挑選行索引? 例如,在上面的df中,如果我的閾值是5,我會得到指數3,6,8。

我目前正在這樣做的方式是遍歷每一行,然后跟蹤值何時超過它。 我不是一個python專家想出一個潛在的(如果它存在)更好的方式..

謝謝

直到有人發明了一些pandas one-liner(如果可能的話),你可以嘗試以下方法:

來自IPython會話:

In [393]: get_a_cumsum_lim = lambda df, col, threshold: df[col][df[col].cumsum() >= threshold]

In [394]: s, result = get_a_cumsum_lim(data, 'a', 5), []

In [395]: while not s.empty:
     ...:     idx = s.index[0]
     ...:     result.append(idx)
     ...:     s = get_a_cumsum_lim(data[idx+1:], 'a', 5)
     ...:     
     ...:     

In [396]: result
Out[396]: [3, 6, 8]

暫無
暫無

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

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