0

My aim is to have a user, enter a value into a tkinter GUI. This value is then used to extract a row that contains the users input value. Example of test.CSV file;

enter image description here

The user input is 1000, thus
[(field1 cat),(field2 fred),(field3 apple),(field4 1000),(field5 car)] will be extracted

I have achieved the CSV lookup by using the following code

import csv

with open('test.csv') as f:
    reader =csv.DictReader(f)
    rows = [row for row in reader if row['field4'] =='1000']
for row in rows:
    print (row)

The next step is to print only the columns that i require i.e. not all the columns are required :

I only want [(field1 cat), (field3 apple)], can this be achieved using the above code, or is there a better way of a Vlookup() in Python ?

2
  • print(*(row[field] for field in ('field1', 'field3')]))? Commented Aug 22, 2018 at 15:08
  • use pandas, df = pd.read_csv("ur_file"). df = df[df.field4 == 1000] Commented Aug 22, 2018 at 15:11

1 Answer 1

1

The standard tool in Python for working with tables is pandas, and its core tool is an object called a DataFrame.

import pandas as pd

df = pd.read_csv("test.csv")
print(df[["field1", "field2"]][df["field4"]==1000])

Update: As requested in a comment, you may or may not want the headers printed. By explicitly calling the .to_string() method for the DataFrame you can avoid that pretty easily.

print(df[["field1", "field2"]][df["field4"]==1000].to_string(header=False))
Sign up to request clarification or add additional context in comments.

3 Comments

Is there a way to print without displaying the column headers ?
I also found another solution .tolist() - thanks for all your help !!
Glad that works. Be a little careful if the dataframe is too large since that will instantiate another object (your list) that's essentially a copy of the dataframe before creating the string it prints.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.