Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Get the previous row from dataframe.loc result in pandas

I have a Dataframe like this:

A  B  C  D
0  1  2  3
1  2  6  5
2  5  9  8
3  5  7  9

I use pandas Dataframe.loc with particular conditions to identify the A value that matches that conditions, but I need to populate into column "match" the previous A value, not the one that matches the conditions.

eg:
dataframe["match"] = dataframe.loc[(dataframe["B"] > 4) & (dataframe["C"] > 8), ["A"]] will match the third row with index A = 2

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

A  B  C  D  match
0  1  2  3  NaN
1  2  6  5  NaN
2  5  9  8  2
3  5  7  9  NaN

What should I do to getthe index of the previous row (second one in my example)?

what I need to get:

A  B  C  D  match
0  1  2  3  NaN
1  2  6  5  NaN
2  5  9  8  1
3  5  7  9  NaN

>Solution :

shift your dataframe:

df['match'] = df.shift().loc[(df["B"] > 4) & (df["C"] > 8), ["A"]]

output:

   A  B  C  D  match
0  0  1  2  3    NaN
1  1  2  6  5    NaN
2  2  5  9  8    1.0
3  3  5  7  9    NaN
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading