在一个大的txt文件pandas中查找标题



假设我有一个包含几百万行的大文件。前300多行(可变数字(包含有关文件的信息,然后在数据之前有一个标题行。我不知道标题在哪行,但我知道它从什么开始。以下是我的数据示例:

#This File contains some cool suff
#We will see what line the header is on
#Maybe it is in this line
#CHROM POS ID 
1 100 17
2 200 18
2 300 18

标题行是#CHROM POS ID

这是我尝试过的,但它返回list index out of range:

database = pd.read_table(infile, header=[num for num,line in enumerate(infile) if line.startswith("#CHROM")])

我想我天真地认为pd.read_table的工作方式与with open()相同,这可能已经奏效了。任何帮助都将不胜感激!

EDIT:刚刚看到它是一个文本文件

将变量设置为headerrow、

lineno = 0
for line in infile.readlines():
if line.startswith('#CHROM'):
headerrow = lineno
lineno += 1

然后,当您引入该文件时,您可以执行类似pd.readtable('my_file.txt',header=headerrow(之类的操作,再加上您需要的任何其他参数。

我发现这对于在大型文本文件中查找标头的特定应用程序来说是成功的。首先,写一个函数逐行读取,直到找到匹配:

def headerFinder(infile):
with open(infile) as f:
for num,line in enumerate(f):
if line.startswith("#CHROM"):
return num

第一块代码将枚举文件中的行并找到匹配的行,然后您可以实际将函数调用传递给pd.read_table()函数,如下所示:

def tableReader(infile, *argv):
df = pd.read_table(infile, header=headerFinder(infile), usecols=argv)
return df

因为我的中野很大,也有300+列,所以我发现这是传递可变数量的头的好方法,函数调用的例子:

tableDF = tableReader(input_file, '#CHROM', 'POS', 'ID', 'REF', 'ALT', 'INFO')

所以我的整个小程序如下:

import pandas as pd
import sys
input_file = sys.argv[1]
def headerFinder(infile):
with open(infile) as f:
for num,line in enumerate(f):
if line.startswith("#CHROM"):
return num
def tableReader(infile, *argv):
df = pd.read_table(infile, header=headerFinder(infile), usecols=argv)
return df
tableDF = tableReader(input_file, '#CHROM', 'POS', 'ID', 'REF', 'ALT', 'INFO')
#to view as test of success
(tableDF[:10]).to_csv('./test_table', sep='t', index=False)

最新更新