简体   繁体   English

Python:从csv中提取特定行作为列表

[英]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: 我有一个.csv文件,其ID号与这样的字符串相关联:

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: 我想提取ID号为x的行并将其附加到列表中,因此理想情况是:

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 尽管我虽然以字节模式打开它,但它告诉我“ iterator should return strings, not bytes ”,所以该解决方案似乎不起作用

use pandas to read the csv-file into a dataframe 使用熊猫将csv文件读入数据帧

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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