[Python] Find value from row , above and below using If statements in python

Discussão em 'Python' iniciado por Stack, Fevereiro 18, 2025.

  1. Stack

    Stack Membro Participativo


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

    a = 7 # 1st value to find in row1
    b = 39 # 2nd value to find in row2
    c = 10 # 3rd value to find in row3
    d = 38 # 4th value to find in row4

    value_1 = 5
    value_2 = 21

    while n < len(df)-1 :
    if df.loc[n].isin([a]).any # 7 is in any in n row
    if df.loc[n+1].isin().any(): #39 is in any in n+1 row
    if df.loc[n+2].isin([c]).any(): #10 is in any in n+2 row
    if df.loc[n+3].isin([d]).any(): #44 is in any in n+3 row

    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])
    elif df.loc[n+1].isin([value_1]).any() :
    if (df.loc[n+1].isin([value_2 ]).any() or df.loc[n].isin([value_2 ]).any() or df.loc[n+1].isin([value_2 ]).any()):
    display (df.loc[n:n])
    elif df.loc[n-1].isin([value_1]).any() :
    if (df.loc[n-1].isin([value_2 ]).any() or df.loc[n-2].isin([value_2 ]).any() or df.loc[n].isin([value_2 ]).any()):
    display (df.loc[n:n])
    ​


    I am very beginner in python. Sorry for the mess. I am trying to find a,b,c,d to find in row 1,2,3,4 from data and once it matches from the data , then if value_1 be in row n and value_2 is in row n or n-1 or n+1 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()): then show the data. and then same again one below and one above. The code is running but not finding all the matched datas but few. Have i done any mistake using or operator?

    For example, first it will find the value a(7) from any row, (here in found in row 4) once it found then more to next row to find b (39 found in row 5), and then c(10 found in row 6) and d(38 found in row 7). Once it found, then it will search for value_1 (5) in the row of a(7 which was found in row 4) or one above(row 3) or below (row 5)

    A B C D E F
    1 | 4 5 8 16 5 44 #VALUE_1 (5)
    2 | 1 4 12 15 22 21 #VALUE_2 (21)
    3 | 2 11 13 15 28 33
    4 | 5 15 29 35 7 33
    5 | 6 7 39 12 14 16
    6 | 1 9 10 12 20 26
    7 | 6 38 20 36 33 34
    8 | 12 21 7 28 35 39
    9 | 5 18 39 33 35 36
    10| 4 7 10 18 19 28
    11| 3 4 15 19 28 38

    and later when value_1 (5) is found, then it 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 more match

    Continue reading...

Compartilhe esta Página