我尝试读取700个床文件,并将它们保存在一个csv文件中。我对这个部分没有问题。我必须为每个文件添加一列条形码,这个条形码是每个文件名的一部分(文件名为TCGA-02-0047-01A-01R-1849-01,条形码部分为TCGA-02-0047-01A),每个床上文件由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)发布于 2020-12-14 23:06:18
根据您的代码,我假设代码是相对于文件的。因此,您不应该使用嵌套循环(一个用于文件,另一个用于代码),而应该使用单个循环,并使用具有相同索引的代码。并且CSV文件在顶部应该只有一个头。因此,我将使用:
#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)https://stackoverflow.com/questions/65286222
复制相似问题