Pandas: find the previous line of matching value

I am trying to create a column with values ​​from one column, but based on matching another column with the previous value.

Here is my current code:

d = {'a':[1,2,3,1,2,3,2,1], 'b':[10,20,30,40,50,60,70,80]}

df = pd.DataFrame(d)

df['c'] = df['b'][df['a'] == df['a'].prev()]

And my desired result:

   a   b    c
0  1  10  NaN
1  2  20  NaN
2  3  30  NaN
3  1  40   10
4  2  50   20
5  3  60   30
6  2  70   50
7  1  80   40

... which I do not receive, because .prev()- this is not the real thing. Any thoughts?

+4
source share
1 answer

We can group a column athat sorts values ​​by default and then binds the shift b :

In [110]: df['c'] = df.groupby('a')['b'].transform(lambda x: x.shift())

In [111]: df
Out[111]:
   a   b     c
0  1  10   NaN
1  2  20   NaN
2  3  30   NaN
3  1  40  10.0
4  2  50  20.0
5  3  60  30.0
6  2  70  50.0
7  1  80  40.0

Or a much better option - using GroupBy.shift()(thanks @Mitch )

In [114]: df['c'] = df.groupby('a')['b'].shift()

In [115]: df
Out[115]:
   a   b     c
0  1  10   NaN
1  2  20   NaN
2  3  30   NaN
3  1  40  10.0
4  2  50  20.0
5  3  60  30.0
6  2  70  50.0
7  1  80  40.0
+4
source

Source: https://habr.com/ru/post/1670781/


All Articles