简体   繁体   中英

Pandas, how to find rows that meet certain conditions and save the previous row in a new dataframe

I am trying to make it so that my script reads through the 'data_b' and 'data_d' columns and if it sees the conditions 'Rest' and 'True', it should save the previous row.

data_frame

Row_ID           data_a      data_b    data_c      data_d
59               0.30781     Discharge 2.31725     NaN
60               0.30786     Discharge 2.31714     NaN
61               0.30792          Rest 2.34857    True
62               0.31313          Rest 2.38084     NaN
181              0.93398     Discharge 2.31103     NaN
182              0.93398     Discharge 2.31115     NaN
183              0.93408          Rest 2.34550    True
184              0.93930          Rest 2.36800     NaN

I would like the output to be as follows:

Row_ID           data_a      data_b    data_c      data_d
60               0.30786     Discharge 2.31714     NaN
182              0.93398     Discharge 2.31115     NaN

As you can see, rows 61 and 183 meet the criteria. There for it must save only rows 60 and 182.

Try:

l = list()
for index , row in df.iterrows():
    try:
        if row["data_b"] == "Rest" and row["data_d"] == "True":
            fila = df.iloc[index - 1,:]
            l.append(fila)
    except Exception as e:
        print(e)
        continue
result = pd.DataFrame(l)

Try with shift

newdf = df[df['data_d'].shift(-1).equal('True') & df['data_b'].shift(-1).eq('Rest')]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM