从CSV中返回一行,如果行中指定的值与条件匹配 [英] Returning a row from a CSV, if specified value within the row matches condition

查看:666
本文介绍了从CSV中返回一行,如果行中指定的值与条件匹配的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Ahoy,我在写一个Python脚本来过滤一些大的CSV文件。

Ahoy, I'm writing a Python script to filter some large CSV files.

我只想保留满足我的条件的行。

I only want to keep rows which meet my criteria.

我的输入是以下格式的CSV文件

My input is a CSV file in the following format


Locus         Total_Depth  Average_Depth_sample   Depth_for_17
chr1:6484996  1030         1030                   1030
chr1:6484997  14           14                     14
chr1:6484998  0            0                      0


我想返回Total_Depth为0的行。

I want to return lines where the Total_Depth is 0.

已经关注这个答案来读取数据。

I've been following this answer to read the data. But am stuck trying to parse over the rows and pull out the lines that meet my condition.

这里是我到目前为止所有的代码:

Here is the code I have so far:

import csv

f = open("file path", 'rb')
reader = csv.reader(f) #reader object which iterates over a csv file(f)
headers = reader.next() #assign the first row to the headers variable
column = {} #list of columns
for h in headers: #for each header
    column[h] = []
for row in reader: #for each row in the reader object
    for h, v in zip(headers, row): #combine header names with row values (v) in a series of tuples
        column[h].append(v) #append each value to the relevant column

我知道我的数据现在是字典格式,我想根据Total_Depth键过滤它,但我不确定如何做这个。我的目的是使用一个'if'语句来选择相关的行,但不知道如何做这个字典结构。

I understand that my data is now in a dictionary format, and I want to filter it based on the "Total_Depth" key, but I am unsure how to do this. I'm aiming to use an 'if' statement to select the relevant rows, but not sure how to do this with the dictionary structure.

任何建议将非常感谢。 SB:)

Any advice would be greatly appreciated. SB :)

推荐答案

使用列表推导。

import csv

with open("filepath", 'rb') as f:
    reader = csv.DictReader(f)
    rows = [row for row in reader if row['Total_Depth'] != '0']

for row in rows:
    print row

DictReader

这篇关于从CSV中返回一行,如果行中指定的值与条件匹配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆