[英]read text based(bed) files, add new column to them save in csv file
我尝试读取 700 个床位文件并将它们保存在一个 csv 文件中。 这部分我没有问题。 我必须在每个bedfile中添加一列作为条形码,这个条形码是每个文件名的一部分(文件名TCGA-02-0047-01A-01R-1849-01
,条形码部分是TCGA-02-0047-01A
),每个bedfile由 64000 行组成。 这意味着在条形码列中我重复相同的值 67000 次。 我写的代码有点工作,但我被困在for
循环中并且不起作用。
这是我的代码:
import pyranges as pr
import pandas as pd
import os
H = ["chrom", "chromStart", "chromEnd", "strand", "gene_symbol", "entrez_gene_id", "transcript_id" , "raw_count", "scaled_estimate", "normalized_count", "barcode"]
list = os.listdir("E:\\newdata")
#extract the barcode
code =[]
for f in list:
x = '-'.join(f.split('-')[0:3])
code.append(x)
print('2')
#find direction of each bed file
newList=[]
for i in range(len(list)):
newList.append("E:\\newdata\\" + list[i])
print('3')
#read the bed files one after another, save it in file and add barcode
for bed in newList: #bed file in newlist
for n in code: #barcode for each bed files
df = pr.read_bed(bed, as_df=True)
df['barcode'] = n #add colum for each bed file
filename = df.to_csv('E:\\data951.csv',mode ='a', header = H, index=False)
从您的代码中,我假设代码是相对于文件的。 所以你不应该使用嵌套循环(一个用于文件,一个用于代码),而是一个单循环并使用具有相同索引的代码。 CSV 文件的顶部应该只有一个 header。 所以我会使用:
#read the bed files one after another, save it in file and add barcode
# create the csv file and add a header only on first file
header = H
mode = 'w'
for i, bed in enumerate(newList): #bed file in newlist and get its index for the code
n = code[i]: # barcode associated with each bed files
df = pr.read_bed(bed, as_df=True)
df['barcode'] = n #add colum for each bed file
header = None # will append without any header for following files
mode = 'a'
df.to_csv('E:\\data951.csv',mode=mode, header = header, index=False)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.