Python Pandas读取具有可变前导长度的csv文件

2024-09-27 07:18:44 发布

您现在位置:Python中文网/ 问答频道 /正文

嗨,我正在使用pandas读入一系列文件并将它们连接到一个数据帧。我的文件开始时有一堆长度可变的垃圾,我想忽略它们。pd.read_csv()具有skiprows方法。我已经编写了一个函数来处理这个问题,但是我必须打开文件两次才能使它正常工作。有更好的方法吗?在

HEADER = '#Start'

def header_index(file_name):
    with open(file_name) as fp:
        for ind, line in enumerate(fp):
            if line.startswith(HEADER):
                return ind

for row in directories:
    path2file = '%s%s%s' % (path2data, row, suffix)
    myDF = pd.read_csv(path2file, skiprows=header_index(path2file), header=0, delimiter='\t')

任何帮助都将不胜感激。在


Tags: 文件csv方法nameforreadindexfile
1条回答
网友
1楼 · 发布于 2024-09-27 07:18:44

现在这是可能的(不知道当时是否可行),如下所示:

pos= 0
oldpos = None

while pos != oldpos:  # make sure we stop reading, in case we reach EOF
    line= fp.readline()
    if line.startswith(HEADER):
        # set the read position to the start of the line
        # so pandas can read the header
        fp.seek(pos)
        break
    oldpos= pos
    pos= fp.tell()    # renenber this position as sthe start of the next line

pd.read_csv(fp, ...your options here...)

相关问题 更多 >

    热门问题