简体   繁体   中英

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

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()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM