如何将一个CSV文件按字段分组并删除列,分割成多个较小的csv文件?

2024-07-04 16:24:11 发布

您现在位置:Python中文网/ 问答频道 /正文

即使这听起来像是一个重复的问题,我也没有找到解决办法。我有一个很大的.csv文件,看起来像:

prot_hit_num,prot_acc,prot_desc,pep_res_before,pep_seq,pep_res_after,ident,country
1,gi|21909,21 kDa seed protein [Theobroma cacao],A,ANSPV,L,F40,EB
1,gi|21909,21 kDa seed protein [Theobroma cacao],A,ANSPVL,D,F40,EB
1,gi|21909,21 kDa seed protein [Theobroma cacao],L,SSISGAGGGGLA,L,F40,EB
1,gi|21909,21 kDa seed protein [Theobroma cacao],D,NYDNSAGKW,W,F40,EB
....

目的是根据最后两列('ident'和'country')将这个.csv文件分成多个更小的.csv文件。在

我使用了前一个post中的答案中的代码,如下所示:

^{pr2}$

但是,我需要我的output.csv只包含列'pep_seq',一个期望的输出,如:

pep_seq    
ANSPV
ANSPVL
SSISGAGGGGLA
NYDNSAGKW

我能做什么?在


Tags: 文件csvresseqpepseedebgi
2条回答

下面将为每个国家输出一个csv文件,其中只包含您需要的字段。在

你总是可以根据你需要的第二个字段添加另一个步骤。在

import csv

# use a dict so you can store the list of pep_seqs found for each country
# the country value with be the dict key
csv_rows_by_country = {}
with open('in.csv', 'rb') as csv_in:
    csv_reader = csv.reader(csv_in)
    for row in csv_reader:
        if row[7] in csv_rows_by_country:
            # add this pep_seq to the list we already found for this country
            csv_rows_by_country[row[7]].append(row[4])
        else:
            # start a new list for this country - we haven't seen it before
            csv_rows_by_country[row[7]] = [row[4],]

for country in csv_rows_by_country:
    # create a csv output file for each country and write the pep_seqs into it.
    with open('out_%s.csv' % (country, ), 'wb') as csv_out:
        csv_writer = csv.writer(csv_out)
        for pep_seq in csv_rows_by_country[country]:
            csv_writer.writerow([pep_seq, ])

您的代码几乎是正确的,它只需要正确设置fieldsnames,并设置{}。这将告诉DictWriter只写入您指定的字段:

import itertools   
import operator    
import csv

outfile_path4 = 'input.csv'    
outfile_path5 = r'my_output_folder\output.csv'
csv_contents = []

with open(outfile_path4, 'rb') as fin:
    dict_reader = csv.DictReader(fin)   # default delimiter is comma
    fieldnames = dict_reader.fieldnames # save for writing

    for line in dict_reader:            # read in all of your data
        csv_contents.append(line)         # gather data into a list (of dicts)

group = ['prot_desc','ident','country']
# input to itertools.groupby must be sorted by the grouping value 
sorted_csv_contents = sorted(csv_contents, key=operator.itemgetter(*group))

for groupkey, groupdata in itertools.groupby(sorted_csv_contents, key=operator.itemgetter(*group)):
    with open(outfile_path5+'slice_{:s}.csv'.format(groupkey), 'wb') as fou:
        dict_writer = csv.DictWriter(fou, fieldnames=['pep_seq'], extrasaction='ignore')    
        dict_writer.writeheader()
        dict_writer.writerows(groupdata) 

这将为您提供一个包含以下内容的csv输出文件:

^{pr2}$

相关问题 更多 >

    热门问题