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

Time:07-21

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!

CodePudding user response:

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]

CodePudding user response:

In your case

out = df.loc[df['min']<number_to_check].clip(upper = number_to_check)
Out[40]: 
   min  max
0    1    3
1    6    9
2   13   17
  • Related