Home > OS >  Get the previous row from dataframe.loc result in pandas
Get the previous row from dataframe.loc result in pandas

Time:09-26

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

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

CodePudding user response:

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

CodePudding user response:

use shift(1) to return previous value of column A

df.loc[(df["B"] > 4) & (df["C"] > 8),  'match'] = df['A'].shift(1)
df
    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
  • Related