複数の.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    

cutBashを使用して2番目の列とsort名前を取得し、各uniqファイルの各名前の数を取得する方法を知っています。すべての名前を表示して名前を数え、ファイルに名前がない場合は、「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ライブラリを使用して読むことをお勧めします。

おすすめ記事