1

i have a range:

start = 87.5

end = 107.5

in between start and end i have allocations that look like this

enter image description here

if visualized it looks like this:

enter image description here

now i have another input as X = 0.3

0.3 is actually a value that can be allocated inside the range.

my question is how do i solve this in dataframe-pandas and have the most optimal solution.

by optimal solution i mean the new allocation doesn't create more whitespaces hence decreasing the continuity. inshort i want to increase the congestion in the range so i can place more X's in the range.

if default allocations are:

lower upper

87.85 88.15

89.75 90.05

91.45 91.75

96.05 96.35

96.85 97.15

98.85 99.15

100.85 101.15

101.9 102.1

102.9 103.1

105.35 105.65

107.81 107.99

then one of the many solutions can be(considering x= 0.3:

lower upper

87.85 88.15

88.55 88.85

89.75 90.05

91.45 91.75

96.05 96.35

96.85 97.15

98.85 99.15

100.85 101.15

101.9 102.1

102.9 103.1

105.35 105.65

107.81 107.99

Saud Ahmed
  • 65
  • 6

1 Answers1

1

IIUC, you can compute the size of the empty ranges, find the smallest that is larger than your target:

X = 0.3

diff = df['lower'].sub(df['upper'].shift()).sort_values()
n = np.searchsorted(diff, X)
idx = diff.index[n]

a = df.loc[idx-1, "upper"]
b = df.loc[idx, "lower"]

delta = (b-a)-X//3

print(f'insert {X} between {a} and {b}')
print(f'potential range: {a+delta}-{b-delta}')

Output:

insert 0.3 between 96.35 and 96.85
potential range: 95.05-92.75
mozway
  • 194,879
  • 13
  • 39
  • 75
  • this works. one more question. instead of printing, how can i insert a row in the dataframe in that position. the only way i found is to split the dataframe at that position and then append them back into one dataframe with new row – Saud Ahmed May 11 '23 at 06:28
  • Insert in the end and sort, this is the easiest with small size data. – mozway May 11 '23 at 10:53
  • i cannot change the positions of the rows. if i do i will break alot of things. also can you tell me how can i get more than 1 range? the output of your function gives the best possible solution. but what if i also want more than 1 solutions(not optimal ones). – Saud Ahmed May 11 '23 at 11:11
  • 1
    `diff = df['lower'].sub(df['upper'].shift()).sort_values()` gives your all the `diff`, then `diff.gt(X)` should give your the positions of insertion – mozway May 11 '23 at 11:14