Find value from a row if another value matches with same row, above or below

import pandas as pd
import numpy as np
df= pd.read_csv ("file.csv")

n = 0
value_1 = 5
value_2 = 21

while n < len(df)-1 :
         if df.loc[n].isin([value_1]).any():       
                if (df.loc[n].isin([value_2 ]).any() or df.loc[n-1].isin([value_2 ]).any() or df.loc[n+1].isin([value_2 ]).any()):                                                                     
                       display (df.loc[n:n])
                        

Hello, I’m trying to find row of when value_1 (5) is found in any row, then it will search for value_2 (21) on the row of value_1 (which was found in row 4) or one above (row 3) or below (row 5). if found then, it will print the row 1, and continue to find for more matches. Its running on my computer but not finding all the matches but few, is there any better way to write it?

Column 1 Column 2 Column 3 Column 4
4 2 16 44
1 5 12 21
2 11 13 15
5 55 77 11
21 8 12 45
64 33 4 6

For example value_2(5) is found in row 1 and if value_2 (21) found in row1, row2 or row3 then it will print row2 . and then again if value_1 in found in row 4 and value_2 in row 3 , or 5 then it will print row4 and continue to find more matches…

There’s a small bug in you while loop, it doesn’t increment n. I’m going to assume that’s just a copy/paste error as you would have figured that out pretty quickly.

As written the code works as described. The code can be cleaned up and there are some edge cases that would likely cause an error. For example if value_1 (5) is found in row 0, or the last row then the program will crash.

  1. Can you provide an example where you expect a line to be printed but it is not?
  2. Can you define what happens if value_1 is found on the very first line (row 0 and thus there is no previous line to check)? Should the code only check the current line and the next line for value_2? Or do we ignore row 0 entirely?
  3. Can you define what happens if value_1 is found on the very last line (row 5 in this example and thus there is no next line)? Should the code only check the previous line and current line for value_2? Or do we ignore row 5 entirely?

Once the above questions are answered I can give better guidance on how to clean up the code.

Small cleanup: You should be able to use df.loc[n].eq(value_1).any() instead of isin. It’s not a big deal, just slightly less characters.