[Python] Pandas - return the -2 row

Discussão em 'Python' iniciado por Stack, Agosto 20, 2025.

  1. Stack

    Stack Membro Participativo

    If I have an input.txt file:

    apples grapes alpha pears
    chicago paris london
    yellow blue red
    +++++++++++++++++++++
    apples grapes beta pears
    chicago paris london
    car truck van
    +++++++++++++++++++
    apples grapes gamma pears
    chicago paris london
    white purple black
    +++++++++++++++++++
    apples grapes delta pears
    chicago paris london
    car truck van


    I want to find all rows containing truck as the 2nd string, then return the 3rd string from the row two lines above.

    Output would be:

    beta
    delta


    So far, I have this code that finds the row I'd like, then creates a dataframe from the list. What is the best way to continue using Pandas, and get the -2 row/value that I need?

    data_list = []

    with open('input.txt', 'r') as data:

    for line in data:
    split_row = line.split()
    if len(split_row) > 1 and split_row[1] == "truck":
    data_list.append(split_row)

    df = pd.DataFrame(data_list)

    print(df.to_string)

    Continue reading...

Compartilhe esta Página