Search within csv and bring other row columns - Python

Asked

Viewed 185 times

2

Well I have a Python application that generates a csv file of 7000 lines and 4 columns, for example:

Mesa,Entrada,Saida,Conta
"P",21:00,22:00,95.00
"A",14:00,18:00,195.00
"C",18:00,21:00,75.00
"D",16:30,18:30,75.00
"E",16:00,18:45,178.00
"R",19:00,15:45,178.00
"Z",19:00,15:45,178.00

Basically the application has to search for Table "X" and as a result bring the account of table "X". Currently I do so:

def get_status(mesa):
    csv_loc = f"{os.getcwd()}/teste.csv"
    with open(csv_loc) as csvfile:
        readCSV = csv.reader(csvfile, delimiter=',')
        next(readCSV, None)
        for row in readCSV:
            if row[0] == mesa:
                return row[3]

But I wanted to do it differently with pandas, for example, someone knows?

1 answer

2


Using the pandas library is quite simple to solve this problem. You can read csv automatically using the pandas read_csv command. And filter the lines that contain the table you want. In my example below, I’ve filtered which lines have the Table column equal to "P". df[df.Mesa=="P"]. You can do this kind of logical operation with any column.

import pandas as pd
df = pd.read_csv("teste.csv")
mesa_p = df[df.Mesa=="P"]
print(mesa_p)

If you want to work with normal python arrays even, you can convert the result to a Matrix just like in the code below.

mesa_p = mesa_p.as_matrix()
print(mesa_p[0]) # Escrever no ecrã a primeira linha da matrix.
  • Cara valeu was just what I was looking for, the only change I made was: print(mesa_p[0][3]), to bring the account field

  • I’m glad it worked out! :)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.