Jessica Chambers
Jessica Chambers

Reputation: 1316

Python: Extracting specific rows from csv as list

Probably a repost but I can't find a solution that works in my case.

I have a .csv file with an id number associated to a string like this:

0   |   ABC
1   |   DEF
   ...
100 |   XYZ

I would like to extract the row with an ID number x and append it to a list, so ideally something like:

with open('myfile.csv', 'rb') as f:
    reader = csv.reader(f)
    results.append([row for idx, row in enumerate(reader) if idx[0] == x)])

this solution does not appear to work as it tells me that the "iterator should return strings, not bytes" despite the fact that I though I opened it in byte mode

Upvotes: 2

Views: 1073

Answers (1)

Janko
Janko

Reputation: 147

use pandas to read the csv-file into a dataframe

import pandas as pd
sourceinput = pd.read_csv('myfile.csv')

outputlist = sourceinput['id'].loc[sourceinput['id'] == <value_you_need>].tolist()

Upvotes: 3

Related Questions