How can i find a value in a row, another value in the next row and show row if it matches in python

I am very beginner in python. I was trying to find out if any value matches with any row from the data and another given value matches with the next row of it, then print the first row and continue until the last row

import pandas as pd    
    df= pd.read_csv ("prac.csv")
    n = 0
    a = input ("write the 1st number: ")
    b = input ("write the 2nd number: ")

    while n < 5 : 
        if df.loc[n:n] == a: 
            if df.loc[n+1:n+1] == b:
                print (df.loc[n:n])
        else: print ("No match") 
        n+=1
Column 1 Column 2 Column 3 Column 4
4 35 3 66
10 22 12 23
5 3 21 21
88 29 2 7
37 39 33 1

For example if 1st value (4) matches with any row (row 1) any 2nd value (22) with the next row (row 2) of it then it should print the row it matched first and continue. I am trying to run the code but its not working.

Column 1 Column 2 Column 3 Column 4
4 35 3 66

Nice job with the formatting of the code and the tables in the forum. That makes it possible to copy-paste for us :slight_smile:

What would be even better is if for an example like this, you include the construction of the dataframe in the code rather than loading from a csv file (that we won’t have access to). And if you modify the code so that we can just copy and run it. For example, as:

import pandas as pd

# Define the data for the DataFrame
data = {
    "Column 1": [4, 10, 5, 88, 37],
    "Column 2": [35, 22, 3, 29, 39],
    "Column 3": [3, 12, 21, 2, 33],
    "Column 4": [66, 23, 21, 7, 1]
}

# Create the DataFrame
df = pd.DataFrame(data)

n = 0
a = 4
b = 22

while n < 5 : 
    if df.loc[n:n] == a: 
        if df.loc[n+1:n+1] == b:
            print (df.loc[n:n])
    else: print ("No match") 
    n+=1

Now I get

---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
[...]
      2 a = 4
      3 b = 22
      4 
      5 while n < 5 :
----> 6     if df.loc[n:n] == a:
      7         if df.loc[n+1:n+1] == b:
      8             print (df.loc[n:n])
      9     else: print ("No match")

...\anaconda3\envs\peter\Lib\site-packages\pandas\core\generic.py in ?(self)
   1575     @final
   1576     def __nonzero__(self) -> NoReturn:
-> 1577         raise ValueError(
   1578             f"The truth value of a {type(self).__name__} is ambiguous. "
   1579             "Use a.empty, a.bool(), a.item(), a.any() or a.all()."
   1580         )

ValueError: The truth value of a DataFrame is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().

From which you can deduce that df.loc[n:n] does not extract a number from your database. You can try display(df.loc[n:n]) to verify this.

(It seems likely you actually want df.iloc[n,n])

Sorry for not being able to write the question properly as its my first time here, and Thank you for the help :)), but i am getting this message " The truth value of a DataFrame is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all() " so if statement is returning a boolean here, how can i change it to int? I have used if df[df.loc[n:n]]== a: but still not working

There are a couple of errors here. What is causing your problem is that you are comparing a dataframe to a value which is why you get 'The truth value of a DataFrame is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all()

df.loc[n+1:n+1]

means take row [n+1] from the dataframe. Row n+1 is itself a dataframe so there is no meaning to compare it with a scalar. One minor point here is that it would be better simply to write df.loc[n+1]
What you really want is to say if b is any where in the row. To do that the syntax is:

if df.loc[n].isin([b]).any():

If you try the following it should work:

while n < 4 : 
    if df.loc[n].isin([a]).any(): 
        if df.loc[n+1].isin([b]).any():
            print (df.loc[n])
    else: print ("No match") 
    n+=1

Note that you need to have n < 4 otherwise the program will try and access row 5 of the dataframe which does not exist.

I hope this helps

1 Like

Thank you very very much. I was stuck there for a day. really appreciate it :pray: :slightly_smiling_face:

1 Like