我的merging-multiple-files-based-on-the-common-column和https://superuser.com/questions/1245094/merging-multiple-files-based-on-the-common-column有类似的问题.我非常接近解决方案,但我对Python还是个新手.我需要帮助调整加入多个文件的代码. 我的个人文件ID和列如下所示:

File1.txt文件1.txt

id  SRR1071717
chr1:15039:-::chr1:15795:-  2
chr1:15948:-::chr1:16606:-  6

File2.txt文件2.txt

id  SRR1079830
chr1:11672:+::chr1:12009:+  10
chr1:11845:+::chr1:12009:+  7
chrY:9756574:+::chrY:9757796:+  0

我想要的输出

id  SRR1071717 SRR1079830
chr1:15039:-::chr1:15795:- 2 0
chr1:15948:-::chr1:16606:- 6 0
chr1:11672:+::chr1:12009:+ 0 10
chr1:11845:+::chr1:12009:+ 0 7
chrY:9756574:+::chrY:9757796:+ 0 0

我的代码:Matrix.py

import sys

columns = []
data = {}
ids = set()
for filename in sys.argv[1:]:
    with open(filename, 'rU') as f:
        key = next(f).strip().split()[1]
        columns.append(key)
        data[key] = {}
        for line in f:
            if line.strip():
                id, value = line.strip().split()
                try:
                    data[key][int(id)] = value
                except ValueError as exc:
                    raise ValueError(
                        "Problem in line: '{}' '{}' '{}'".format(
                            id, value, line.rstrip()))

                ids.add(int(id))

print('\t'.join(['ID'] + columns))

for id in sorted(ids):
    line = []
    for column in columns:
        line.append(data[column].get(id, '0'))
    print('\t'.join([str(id)] + line))

如图所示,我运行了一段python代码,但它不能正常工作(这是一种新的python).电流输出(仅两行!).

python3 matrix.py File\*.txt

电流输出

id SRR1071717 SRR1079830
chrY:9756574:+::chrY:9757796:+ 0 0

推荐答案

使用任何awk:

$ cat tst.awk
FNR == 1 { ++numCols }
{
    if ( !($1 in ids2rows) ) {
        rows2ids[++numRows] = $1
        ids2rows[$1] = numRows
    }

    rowNr = ids2rows[$1]
    vals[rowNr,numCols] = $2
}
END {
    for ( rowNr=1; rowNr<=numRows; rowNr++ ) {
        id = rows2ids[rowNr]
        printf "%s", id
        for ( colNr=1; colNr<=numCols; colNr++ ) {
            val = ( (rowNr,colNr) in vals ? vals[rowNr,colNr] : 0 )
            printf "%s%s", OFS, val
        }
        print ""
    }
}

$ awk -f tst.awk File1.txt File2.txt
id SRR1071717 SRR1079830
chr1:15039:-::chr1:15795:- 2 0
chr1:15948:-::chr1:16606:- 6 0
chr1:11672:+::chr1:12009:+ 0 10
chr1:11845:+::chr1:12009:+ 0 7
chrY:9756574:+::chrY:9757796:+ 0 0

Python相关问答推荐

Inquirer库不适用于Pyterfly

有没有方法可以关闭Python多处理资源跟踪器进程?

为什么使用SciPy中的Distance. cos函数比直接执行其Python代码更快?

在Python中,如何才能/应该使用decorator 来实现函数多态性?

删除pandas rame时间序列列中未更改的值

Tkinter -控制调色板的位置

Twilio:CallInstance对象没有来自_的属性'

如何在PIL、Python中对图像应用彩色面膜?

实现的差异取决于计算出的表达是直接返回还是首先存储在变量中然后返回

如何根据情况丢弃大Pandas 的前n行,使大Pandas 的其余部分完好无损

为什么我的Python代码在if-else声明中的行之前执行if-else声明中的行?

使用miniconda创建环境的问题

如何记录脚本输出

如何获取TFIDF Transformer中的值?

Django REST Framework:无法正确地将值注释到多对多模型,不断得到错误字段名称字段对模型无效'<><>

不能使用Gekko方程'

与命令行相比,相同的Python代码在Companyter Notebook中运行速度慢20倍

Polars asof在下一个可用日期加入

在Python中调用变量(特别是Tkinter)

matplotlib图中的复杂箭头形状