Skip to content
Advertisement

how to check if a number exists between two columns of pandas dataframe & replace a value

I have a data frame and integer like this:

number_to_check = 17

df:
min   max
1      3
6      9
13     19
29     46

I want to check if the given number(17) is in between the min & max column of any row. If the number is between min & max columns, then the max column value in that row should be replaced by that integer.

In the example, the integer 17 exists between 13 and 19 i.e third row. So the max value of that row should be replaced by the integer and delete the rows after that particular row.

The final result should be like this:

df:
min   max
1      3
6      9
13     17

Many Thanks in advance!

Advertisement

Answer

You can try:

number = 17
df.loc[df['min'].le(number) & df['max'].ge(number), 'max'] = number

# delete max > 17
df = df.loc[df['max'] > number]
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement