简体   繁体   English

Pandas Dataframe select 基于条件的行和条件之前的前 N 行

[英]Pandas Dataframe select row based on a condition and the previous N rows that are previous the condition

I have a dataframe and I want to select the rows based on a condition and the previous N rows that are previous the condition.我有一个 dataframe,我想要 select 基于条件的行和条件之前的前 N 行。

Example:例子:

pd.DataFrame({'value':[10,20,30,40,50,60,70,80,90],'is_fishing':['NO','NO','YES','NO','YES','NO','NO','NO','YES']})

     value     is_fishing
0     10         NO
1     20         NO
2     30        YES
3     40         NO
4     50        YES
5     60         NO
6     70         NO
7     80         NO
8     90        YES

Expected with N=1 and condition is_fishing=='YES'预期 N=1 且条件为_fishing=='YES'

     value     is_fishing
1     20         NO
2     30        YES
3     40         NO
4     50        YES
7     80         NO
8     90        YES

Numpy's split Numpy的split

def n_prior_to_condition(df, n, condition):
    i = np.flatnonzero(condition) + 1
    return pd.concat([d.tail(n+1) for d in np.split(df, i)])

n_prior_to_condition(df, 1, df.is_fishing=="YES")

   value is_fishing
1     20         NO
2     30        YES
3     40         NO
4     50        YES
7     80         NO
8     90        YES

groupby

def n_prior_to_condition(df, n, condition):
    groups = condition.iloc[::-1].cumsum()
    return df.groupby(groups).tail(n+1)

n_prior_to_condition(df, 1, df.is_fishing=="YES")

   value is_fishing
1     20         NO
2     30        YES
3     40         NO
4     50        YES
7     80         NO
8     90        YES
​

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在 dataframe 中的第 n 行 select 以及基于每日间隔的前几行的条件 - How to select every n-th row in dataframe with condition of previous rows based on daily interval 根据条件删除 Pandas Dataframe 中的前一行 - Delete previous rows in Pandas Dataframe based on condition 如果前面的行满足条件,则 pandas dataframe 的最后 N 行的平均值 - Mean of last N rows of pandas dataframe if the previous rows meet a condition 如何根据先前的行和列条件填充 pandas dataframe 的行? - How to populate row of pandas dataframe based on previous row and column condition? Pandas dataframe 如果其他条件基于先前行不工作 - Pandas dataframe if else condition based on previous rows not working Pandas dataframe 如果其他条件基于先前行不工作 - Pandas dataframe if else condition based on previous rows not working Pandas Dataframe 根据条件从前面的行中减去值 - Pandas Dataframe Subtract Value From Previous Rows Based On Condition Pandas Dataframe根据条件通过上一个更新行值 - Pandas Dataframe update the row values by previous one based on condition 如何基于当前行的条件获取Pandas GroupedBy Dataframe的前一行? - How to get previous rows of a pandas GroupedBy Dataframe based on a condition on the current row? 如何在 Pandas 的 DataFrame 中获取带有条件的前一行 - How to get previous row with condition in a DataFrame of Pandas
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM