I have the following pandas dataframe:
A B
0 16.3 1.10
1 23.2 1.33
2 10.7 -0.43
3 5.7 -2.01
4 5.4 -1.86
5 23.5 3.14
What I would like to accomplish is to generate a third column by comparing the values in column A in 2 adjacent rows and do the same for the next 2, and so on.
It might be a little confusing so I will give an example:
- For the first row, if
16.3 - 23.2 < 5
then the value of the first row of the new columnC
should beBad
, if that difference is==5
then the new column should beDecent
andGood
if the difference is>5
- For the second row, apply the same kind of logic but use
23.2 - 16.3
instead and generate the value ofC
for that row from that difference - Do the same for the rows 3 and 4 as a pair, 5 and 6 as a pair and so on
So the resulting dataframe should be as follows:
A B C
0 16.3 1.10 Bad
1 23.2 1.33 Good
2 10.7 -0.43 Decent
3 5.7 -2.01 Bad
4 5.4 -1.86 Bad
5 23.5 3.14 Good
I have looked around a bit and found that you can define a function which returns different states and then use df.apply.
So I thought maybe it could be possible to create 2 functions: one for the odd rows that compares the value of A
to the next row, and another for the even rows that compares it to the previous row.
However I can't wrap my head around how it would be possible to apply both the functions together to generate the column C
.
How could I implement that, or if there is an easier solution, how could it be done?