I want to add a new column to my DataFrame with the next higher or lower number to y from an external array with allowed_numbers_y.
I have:
allowed_numbers_y = [4,8,15,47]
df = pd.DataFrame({'x': [1,1,1,2,2,3,3,3,4,4,4],
'y': [5,12,13,14,15,16,17,25,21,10,9]})
df output looks like this:
x y
0 1 5
1 1 12
2 1 13
3 2 14
4 2 15
5 3 16
6 3 17
7 3 25
8 4 21
9 4 10
10 4 9
I would like to have this:
x y next_up_y next_down_y
0 1 5 8 4
1 1 12 15 8
2 1 13 15 8
3 2 14 15 8
4 2 15 47 15
5 3 16 47 15
6 3 17 47 15
7 3 25 47 15
8 4 21 47 15
9 4 10 15 8
10 4 9 15 8
I have this, but since my dataframe is big I think there must be a better thing to do instead of looping over every row with this function.
def next_higher(my_list, my_number): # finds the next higher number in list
jojo_list = list(my_list)
if not (len(list(filter(lambda x: x == my_number, my_list))) > 0): # Number exists
jojo_list.append(int(my_number))
jojo_list.sort()
jojo_list.index(int(my_number))
if my_number >= my_list[-1]: # my_number is the last in list
return my_list[-1]
else:
return jojo_list[jojo_list.index(my_number) + 1]