首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >读取基于文本(Bed)的文件,添加新列保存到csv文件中

读取基于文本(Bed)的文件,添加新列保存到csv文件中
EN

Stack Overflow用户
提问于 2020-12-14 17:07:15
回答 1查看 70关注 0票数 0

我尝试读取700个床文件,并将它们保存在一个csv文件中。我对这个部分没有问题。我必须为每个文件添加一列条形码,这个条形码是每个文件名的一部分(文件名为TCGA-02-0047-01A-01R-1849-01,条形码部分为TCGA-02-0047-01A),每个床上文件由64000行组成。这意味着在条形码列中,我将相同的值重复67000次。我写的代码可以工作,但我被困在for循环中,不能工作。

这是我的代码:

代码语言:javascript
复制
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)
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-12-14 23:06:18

根据您的代码,我假设代码是相对于文件的。因此,您不应该使用嵌套循环(一个用于文件,另一个用于代码),而应该使用单个循环,并使用具有相同索引的代码。并且CSV文件在顶部应该只有一个头。因此,我将使用:

代码语言:javascript
复制
#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)
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/65286222

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档