创建表,其中包含从多个 .csv 文件检索到的唯一名称的频率

创建表,其中包含从多个 .csv 文件检索到的唯一名称的频率

我有 32 个 CSV 文件,其中包含从数据库获取的信息。我需要制作一个 TSV/CSV 格式的频率表,其中行的名称是每个文件的名称,列的名称是在整个文件中找到的唯一名称。然后需要用每个文件的每个名称的频率计数来填充该表。最大的问题是并非所有文件都包含相同的获取名称。

.csv输入:

$cat file_1

name_of_sequence,C cc,'other_information'
name_of_sequence,C cc,'other_information'
name_of_sequence,C cc,'other_information'
name_of_sequence,D dd,'other_information'
...

$cat file_2

name_of_sequence,B bb,'other_information'
name_of_sequence,C cc,'other_information'
name_of_sequence,C cc,'other_information'
name_of_sequence,C cc,'other_information'
...

$cat file_3

name_of_sequence,A aa,'other_information'
name_of_sequence,A aa,'other_information'
name_of_sequence,A aa,'other_information'
name_of_sequence,A aa,'other_information'
...

$cat `.csv/.tsv` output:

taxa,A aa,B bb,C cc,D dd    
File_1,0,0,3,1    
File_2,0,1,3,0    
File_3,4,0,0,0    

使用 bash 我知道如何获取cut第二列sortuniq名称,然后获取每个文件中每个名称的计数。我不知道如何制作一个表格来显示所有名称、计数并在文件中不存在该名称时放置“0”。我通常使用 Bash 对数据进行排序,但 python 脚本也可以工作。

答案1

以下内容应适用于 python 2 和 3,另存为xyz.py并使用以下命令运行
python xyz.py file_1 file_2 file_3

import sys
import csv

names = set()  # to keep track of all sequence names

files = {}  # map of file_name to dict of sequence_names mapped to counts
# counting
for file_name in sys.argv[1:]:
    # lookup the file_name create a new dict if not in the files dict
    b = files.setdefault(file_name, {})    
    with open(file_name) as fp:
        for line in fp:
            x = line.strip().split()  # split the line 
            names.add(x[1])  # might be a new sequence name
            # retrieve the sequence name or set it if not there yet
            # what would not work is "i += 1" as you would need to assign
            # that to b[x[1]] again. The list "[0]" however is a reference 
            b.setdefault(x[1], [0])[0] += 1  

# output
names = sorted(list(names))  # sort the unique sequence names for the columns
grid = []
# create top line
top_line = ['taxa']
grid.append(top_line)
for name in names:
    top_line.append(name)
# append each files values to the grid
for file_name in sys.argv[1:]:
    data = files[file_name]
    line = [file_name]
    grid.append(line)
    for name in names:
        line.append(data.get(name, [0])[0])  # 0 if sequence name not in file
# dump the grid to CSV
with open('out.csv', 'w') as fp:
    writer = csv.writer(fp)
    writer.writerows(grid)

使用[0]计数器比直接使用整数更容易更新值。如果输入文件更复杂,最好使用 Python 的 CSV 库读取它们

相关内容