如何使用 python 加入多个标签文件
how to join multiple tab files by using python
我在不同的文件夹中有多个同名的标签文件,就像这样
F:/RNASEQ2019/ballgown/abundance_est/RBRN02.sorted.bam\t_data.ctab
F:/RNASEQ2019/ballgown/abundance_est/RBRN151.sorted.bam\t_data.ctab
每个文件有 5-6 个公共列,我想选择两列 - Gene 和 FPKM。所有的基因列都是相同的,只有 FPKM 值不同。我想从每个文件中提取 Gene 和 FPKM 列并制作一个这样的主文件
Gene RBRN02 RBRN03 RBRN151
gene1 67 699 88
gene2 66 77 89
我做到了
import os
path ="F:/RNASEQ2019/ballgown/abundance_est/"
files =[]
## r=root, d=directory , f=file
for r, d, f in os.walk(path):
for file in f:
if 't_data.ctab' in file:
files.append(os.path.join(r, file))
df=[]
for f in files:
df.append(pd.read_csv(f, sep="\t"))
但这不是进行横向合并。我如何获得上述格式?请帮忙
如何在单独的数据框中读取每个文件然后合并它们?
IIUC,你可以通过简单的列表理解得到你想要的结果:
dfs = [pd.read_csv(f,sep='\t') for f in files]
df = pd.concat(dfs)
print(df)
或作为一个班轮
df = pd.concat([pd.read_csv(f,sep='\t') for f in files])
使用datatable
,您可以通过指定模式一次读取多个文件:
import datatable as dt
dfs = dt.fread("F:/RNASEQ2019/ballgown/abundance_est/**/t_data.ctab",
columns={"Gene", "FPKM"})
如果有多个文件,这将生成一个字典,其中每个键都是文件名,对应的值是该文件的内容,解析成一个框架。可选的 columns
参数限制了您要阅读的列。
在你的情况下,你似乎想根据它来自的文件的名称重命名列,所以你可以这样做:
frames = []
for filename, frame in dfs.items():
mm = re.search(r"(\w+)\.sorted\.bam", filename)
frame.names = {"FPKM": mm.group(1)}
frames.append(frame)
最后可以cbind框架列表:
df = dt.cbind(frames)
如果您需要使用 pandas 数据框,您可以轻松转换:df.to_pandas()
.
我在不同的文件夹中有多个同名的标签文件,就像这样
F:/RNASEQ2019/ballgown/abundance_est/RBRN02.sorted.bam\t_data.ctab
F:/RNASEQ2019/ballgown/abundance_est/RBRN151.sorted.bam\t_data.ctab
每个文件有 5-6 个公共列,我想选择两列 - Gene 和 FPKM。所有的基因列都是相同的,只有 FPKM 值不同。我想从每个文件中提取 Gene 和 FPKM 列并制作一个这样的主文件
Gene RBRN02 RBRN03 RBRN151
gene1 67 699 88
gene2 66 77 89
我做到了
import os
path ="F:/RNASEQ2019/ballgown/abundance_est/"
files =[]
## r=root, d=directory , f=file
for r, d, f in os.walk(path):
for file in f:
if 't_data.ctab' in file:
files.append(os.path.join(r, file))
df=[]
for f in files:
df.append(pd.read_csv(f, sep="\t"))
但这不是进行横向合并。我如何获得上述格式?请帮忙
如何在单独的数据框中读取每个文件然后合并它们?
IIUC,你可以通过简单的列表理解得到你想要的结果:
dfs = [pd.read_csv(f,sep='\t') for f in files]
df = pd.concat(dfs)
print(df)
或作为一个班轮
df = pd.concat([pd.read_csv(f,sep='\t') for f in files])
使用datatable
,您可以通过指定模式一次读取多个文件:
import datatable as dt
dfs = dt.fread("F:/RNASEQ2019/ballgown/abundance_est/**/t_data.ctab",
columns={"Gene", "FPKM"})
如果有多个文件,这将生成一个字典,其中每个键都是文件名,对应的值是该文件的内容,解析成一个框架。可选的 columns
参数限制了您要阅读的列。
在你的情况下,你似乎想根据它来自的文件的名称重命名列,所以你可以这样做:
frames = []
for filename, frame in dfs.items():
mm = re.search(r"(\w+)\.sorted\.bam", filename)
frame.names = {"FPKM": mm.group(1)}
frames.append(frame)
最后可以cbind框架列表:
df = dt.cbind(frames)
如果您需要使用 pandas 数据框,您可以轻松转换:df.to_pandas()
.