2017-01-11 3 views
0

Привет У меня есть набор данные следующим образом, например:Представления данных по одному столбцу в питоне

sample pos mutation 
2fec2  40  TC 
1f3c  40  TC 
19b0  40  TC 
tld3  60  CG 

Я хочу, чтобы иметь возможность найти питон путь к, например, найти все экземпляры, где 2fec2 и 1f3c имеют те же мутации и распечатать код. До сих пор я пробовал следующее, но он просто возвращает все. Я совершенно новичок в python и пытаюсь отучить себя от awk - пожалуйста, помогите!

from sys import argv 
script, vcf_file = argv 
import vcf 
vcf_reader = vcf.Reader(open(vcf_file, 'r')) 
for record.affected_start in vcf_reader: #.affect_start is this modules way of calling data from the parsed pos column from a particular type of bioinformatics file 
    if record.sample == 2fec2 and 1f3c != 19b0 !=t1d3: #ditto .sample 
     print record.affected_start 
+0

Почему вы используете 'pyvcf', чтобы прочитать этот входной файл (так как это не формат)? –

+0

Что вы называете «кодом», который хотите напечатать? – bli

+0

Есть ли связь между форматом, описанным в следующей ссылке, и набором данных из трех столбцов, который вы показываете? http://www.internationalgenome.org/wiki/Analysis/vcf4.0/ – bli

ответ

0

Как об этом

from sys import argv 
script, vcf_file = argv 
import vcf 
vcf_reader = vcf.Reader(open(vcf_file, 'r')) 

# Store our results outside of the loop 
fecResult = "" 
f3cResult = "" 

# For each record 
for record.affected_start in vcf_reader: 
    if record.sample == "2fec2": 
     fecResult = record.mutation 
    if record.sample == "1f3c": 
     f3cResult = record.mutation 

# Outside of the loop compare the results and if they match print the record. 
if fecResult == f3cResult: 
    print record.affected_start 
1

Я предполагаю, что ваши данные в формате, который вы описать и не VCF.

Вы можете попробовать просто разобрать файл со стандартными методами питона и для каждой пары (позы, мутация), построить множество образцов с его следующим образом:

from sys import argv 
from collections import defaultdict 
# More convenient than a normal dict: an empty set will be 
# automatically created whenever a new key is accessed 
# keys will be (pos, mutation) pairs 
# values will be sets of sample names 
mutation_dict = defaultdict(set) 
# This "with" syntax ("context manager") is recommended 
# because file closing will be handled automatically 
with open(argv[1], "r") as data_file: 
    # Read first line and check headers 
    # (assert <something False>, "message" 
    # will make the program exit and display "message") 
    assert data_file.readline().strip().split() == ["sample", "pos", "mutation"], "Unexpected column names" 
    # .strip() removes end-of-line character 
    # .split() splits into a list of words 
    # (by default using "blanks" as separator) 
    # .readline() has "consumed" a first line. 
    # Now we can loop over the rest of the lines 
    # that should contain the data 
    for line in data_file: 
     # Extract the fields 
     [sample, pos, mutation] = line.strip().split() 
     # add the sample to the set of samples having 
     # this (pos, mutation) combination 
     mutation_dict[(pos, mutation)].add(sample) 
    # Now loop over the key, value pairs in our dict: 
    for (pos, mutation), samples in mutation_dict.items(): 
     # True if set intersection (&) is not empty 
     if samples & {"2fec2", "1f3c"}: 
      print("2fec2 and 1f3c share mutation %s at position %s" % (mutation, pos)) 

С вашими, например, данными в качестве первого аргумента сценария, эти выходы:

2fec2 and 1f3c share mutation TC at position 40 
+0

Мое решение может быть нецелесообразным, если вы работаете с огромными данными (будет слишком много комбинаций (pos, mutation), поэтому словарь будет использовать слишком много памяти) – bli

+0

Спасибо, мой ответ помог мне адаптировать скрипт, который работает - мои данные были действительно в реальном формате VCF. Я просто упрощал его, так как это довольно запутанный формат в своем собственном праве, особенно для небиологов! –