python-2.7 - 从多个文件中提取特定列并写入文件 Python

标签 python-2.7

我有七个制表符分隔的文件,每个文件都有确切的列数和名称,但每个文件的数据不同。以下是七个文件中的任何一个的示例:

 test_id gene_id gene    locus   sample_1        sample_2        status  value_1 value_2 log2(fold_change)
  000001     000001     ZZ 1:1   01  01   NOTEST  0       0       0       0       1       1       no

我试图基本上读取所有这七个文件并提取第三、第四和第十列(基因、基因座、log2(fold_change))并将这些列写入一个新文件。所以文件看起来像这样:

gene name   locus   log2(fold_change)    log2(fold_change)    log2(fold_change)    log2(fold_change)    log2(fold_change)    log2(fold_change)    log2(fold_change)
ZZ  1:1         0     0     0     0

所有的 log2(fold_change) 都是从七个文件的第十列中获取的

到目前为止我所拥有的是这个并且需要帮助构建一个更有效的 pythonic 方法来完成上述任务,请注意代码仍然没有完成上面解释的任务,需要一些工作

 dicti = defaultdict(list)
 filetag = []

 def read_data(file, base):
  with open(file, 'r') as f:
    reader = csv.reader((f), delimiter='\t')
     for row in reader:
      if 'test_id' not in row[0]:
            dicti[row[2]].append((base, row))

 name_of_fold = raw_input("Folder name to stored output files in: ")
 for file in glob.glob("*.txt"):
  base=file[0:3]+"-log2(fold_change)"
  filetag.append(base)
  read_data(file, base)


 with open ("output.txt", "w") as out:
  out.write("gene name" + "\t"+  "locus" + "\t" + "\t".join(sorted(filetag))+"\n")
  for k,v in dicti:
   out.write(k + "\t" + v[1][1][3] + "\t" + "".join([ int(z[0][0:3]) * "\t" + z[1][9]  for z in v ])+"\n")

所以,上面的代码是一个工作代码,但不是我要找的代码,这就是为什么。输出代码是问题,我正在写一个制表符分隔的输出文件,第一列 (k) 的基因,v[1][1][3] 是那个特定基因的基因座,最后是我我很难编码这是输出文件的一部分:

 "".join([ int(z[0][0:3]) * "\t" + z[1][9]  for z in v ])

我正在尝试提供七个文件中每个文件在该特定基因和位点的倍数变化列表,然后将其写入正确的列号,所以我基本上是将文件号所在的列号乘以“\t"这将确保该值将转到正确的列,问题是当另一个文件的下一列很长时,写入将从它停止写入的地方开始,我不想要,我想从写作的开头重新开始:

这就是我的意思,例如,

 gene name   locus     log2(fold change) from file 1    .... log2(fold change) from file7 
 ZZ           1:3      0           
                             0

因为第一个 log2 将根据实例 2 的列号进行记录,这是为了确保记录,我将列 (2) 的数量乘以 "\t"和 fold_change 值,它会记录它没问题但是那么最后一列将是第七列,并且不会记录到第七列,因为最后一次写入已完成。

最佳答案

这是我的第一种方法:

import glob
import numpy as np

with open('output.txt', 'w') as out:
    fns = glob.glob('*.txt') # Here you can change the pattern of the file (e.g. 'file_experiment_*.txt')
    # Title row:
    titles = ['gene_name', 'locus'] + [str(file + 1) + '_log2(fold_change)' for file in range(len(fns))]
    out.write('\t'.join(titles) + '\n')
    # Data row:
    data = []
    for idx, fn in enumerate(fns):
        file = np.genfromtxt(fn, skip_header=1, usecols=(2, 3, 9), dtype=np.str, autostrip=True)
        if idx == 0:
            data.extend([file[0], file[1]])
        data.append(file[2])
    out.write('\t'.join(data))

创建的文件 output.txt 的内容(注意:我只创建了三个文件用于测试):

gene_name   locus   1_log2(fold_change) 2_log2(fold_change) 3_log2(fold_change)
ZZ  1:1 0   0   0

关于python-2.7 - 从多个文件中提取特定列并写入文件 Python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37061606/

相关文章:

python - 向图中添加导航工具栏(matplotlib 和 PyQt4)

python - 当子类化 threading.Thread 时,我是否必须调用 super.join() ?

python - 如何将不同维度的numpy数组附加到python中已有的文本文件中

python - 在 Python 字典中如何根据键的第一个值找到一个?

python - 如何在python中将所有参数转换为字典

python - 如何将字符串标签转换为数值

python - python中变量和打印变量的输出之间的区别

python - 用 numpy/python 推断数据

python - 如何在另一个 python 文件中运行我的 python 文件?

python-2.7 - 导入错误 : No module named cryptography. hazmat.bindings._openssl