Bio*_*ram 5 python concatenation dataframe pandas
我正在尝试编写一个脚本,通过某个模式/变量循环文件,然后它连接文件的第8列,同时保留所有文件通用的前4列.如果我使用以下命令,该脚本可以工作:
reader = csv.reader(open("1isoforms.fpkm_tracking.txt", 'rU'), delimiter='\t') #to read the header names so i can use them as index. all headers for the three files are the same
header_row = reader.next() # Gets the header
df1 = pd.read_csv("1isoforms.fpkm_tracking.txt", index_col=header_row[0:4], sep="\t") #file #1 with index as first 5 columns
df2 = pd.read_csv("2isoforms.fpkm_tracking.txt", index_col=header_row[0:4], sep="\t") #file #2 with index as first 5 columns
df3 = pd.read_csv("3isoforms.fpkm_tracking.txt", index_col=header_row[0:4], sep="\t") #file #3 with index as first 5 columns
result = pd.concat([df1.ix[:,4], df2.ix[:,4]], keys=["Header1", "Header2", "Header3"], axis=1) #concatenates the 8th column of the files and changes the header
result.to_csv("OutputTest.xls", sep="\t")
Run Code Online (Sandbox Code Playgroud)
虽然这有效,但我一个接一个地输入文件名是不实际的,因为我有时会有100个文件,因此无法输入df ...函数.相反,我试图使用for循环来做到这一点,但我无法弄明白.这是我到目前为止:
k=0
for geneFile in glob.glob("*_tracking*"):
while k < 3:
reader = csv.reader(open(geneFile, 'rU'), delimiter='\t')
header_row = reader.next()
key = str(k)
key = pd.read_csv(geneFile, index_col=header_row[0:1], sep="\t")
result = pd.concat([key[:,5]], axis=1)
result.to_csv("test2.xls", sep="\t")
Run Code Online (Sandbox Code Playgroud)
但是,这不起作用.
我面临的问题如下:
我怎样才能迭代输入文件并为每个输出文件生成不同的变量名称,然后我可以在pd.concat函数中依次使用它们?
如何使用for循环生成一个字符串文件名,该文件名是df一个整数和一个整数的组合
如何修复上面的脚本获取我想要的项目.
一个小问题是关于我使用col_index函数的方式:有没有办法使用列#而不是列名?我知道它适用于index_col=0任何单一的#.但是我无法使用整数来进行> 1列索引.
请注意,所有文件都具有完全相同的结构,索引列是相同的.
非常感谢您的反馈.
考虑使用merge和right_index参数left_index:
import pandas as pd
numberoffiles = 100
# FIRST IMPORT (CREATE RESULT DATA FRAME)
result = pd.read_csv("1isoforms.fpkm_tracking.txt", sep="\t",
index_col=[0,1,2,3], usecols=[0,1,2,3,7])
# ALL OTHER IMPORTS (MERGE TO RESULT DATA FRAME, 8TH COLUMN SUFFIXED ITERATIVELY)
for i in range(2,numberoffiles+1):
df = pd.read_csv("{}isoforms.fpkm_tracking.txt".format(i), sep="\t",
index_col=[0,1,2,3], usecols=[0,1,2,3,7])
result = pd.merge(result, df, right_index=True, left_index=True, suffixes=[i-1, i])
result.to_excel("Output.xlsx")
result.to_csv("Output.csv")
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3290 次 |
| 最近记录: |