【发布时间】:2020-08-04 20:58:09
【问题描述】:
我有一个目录,其中包含 >200 个制表符分隔的文件,所有文件的结构都相同(列 #s,列标题)
+------+--------------+-------+-------+-----------+------+---------+
| col1 | col2 | col2 | col3 | p_val_adj | col4 | gene |
+------+--------------+-------+-------+-----------+------+---------+
| 0 | 1.980029448 | 0.978 | 0.124 | 0 | 0 | TRDV2 |
| 0 | 1.812616859 | 0.979 | 0.176 | 0 | 0 | TRGV9 |
| 0 | 1.442023797 | 0.688 | 0.09 | 0 | 0 | TRDC |
| 0 | -1.834847304 | 0.021 | 0.735 | 0 | 0 | TRAV1-2 |
+------+--------------+-------+-------+-----------+------+---------+
我的目标是生成一个包含“基因”作为第一列的输出文件,并合并所有文件中的所有“avg_logFC”列数据。对于不重叠的基因,将该值留空。
要完成的步骤: 1) 读取以 .txt [done] 结尾的目录中的所有文件 ex: File1.txt , File2.txt, File3.txt 2)使用列“基因”作为index_col [完成] 3)将文件合并到一个数据框[错误] 4) 列标题而不是 avg_logFC 应该反映文件名
这是我目前所做的:
args = parse_args()
path=os.getcwd() #opens the path
allFiles = glob.glob(path + "/*.txt") #reads all files in the path with .txt
result = pd.read_csv(allFiles[0], sep="\t", index_col=["gene"]) #index by gene
for i in range(1,len(allFiles)): #iterates over remaining files; note first file is 0.
print i
df = pd.read_csv(allFiles[i], sep="\t", index_col=["gene"])
result = pd.merge(result, df, right_index=False, left_index=True, how='inner')
result.to_csv(args.output+".xls", sep="\t", na_rep="")
我无法获得所需的输出,如下所示。
+----------+-------+-------+--------+
| genes | File1 | File2 | File 3 |
+----------+-------+-------+--------+
| TRDV2 | 0.5 | 12 | 2 |
| TRGV9 | 2 | 2 | |
| TRDC | -2 | 3 | 1 |
| TRAV1-2 | | 21 | -5 |
| CD8A | 0.24 | | -2 |
| TRBV20-1 | 3 | 1 | -2 |
| TRBC1 | 0.2 | | 3 |
| FCGR3A | 1 | 2 | 4 |
+----------+-------+-------+--------+
【问题讨论】: