I have a dataframe that looks as follows:
data = np.array([[5, 'red', 2,6, 8, 10],
[11, 'red', 3,9,6,15],
[8, 'blue', 0, 3, 5, 10],
[2, 'blue', 1, 2, 3, 4]])
df = pd.DataFrame(data, columns = ['A','B','red_lower', 'red_upper', 'blue_lower', 'blue_upper'])
A B red_lower red_upper blue_lower blue_upper
0 5 red 2 6 8 10
1 11 red 3 9 6 15
2 8 blue 0 3 5 10
3 2 blue 1 2 3 4
I'd like to create an additional column that tells me if the value in a column A is in the range of the color given in column B. For example, in row 0, since 5 has the designation red, I will check if 5 is between 2 and 6. It is, so I will have the new column have a 1.
Desired result:
A B red_lower red_upper blue_lower blue_upper in_range
0 5 red 2 6 8 10 1
1 11 red 3 9 6 15 0
2 8 blue 0 3 5 10 1
3 2 blue 1 2 3 4 0
I've tried to write a loop, but I'm getting many series errors. I really dont want to have to split up the dataframe (by color), but maybe that's the way to go? (in my actual dataframe, there are six different 'colors', not just two).
Thank you!
EDIT: bonus if we have the additional column tell me if the value is above or below the range! For example, in row 1, 11 is outside the range, so is too high. Table should look this way:
A B red_lower red_upper blue_lower blue_upper in_range
0 5 red 2 6 8 10 inside
1 11 red 3 9 6 15 above
2 8 blue 0 3 5 10 inside
3 2 blue 1 2 3 4 below