首页 > 解决方案 > 在熊猫读取csv中保存跳过行

问题描述

我有一个跳过行的列表(比如 [1,5,10] --> 行号),当我将它传递给pandas read_csv时,它会忽略这些行。但是,我需要将这些跳过的行保存在不同的文本文件中。

我浏览了 pandas read_csv 文档和其他几篇文章,但不知道如何将其保存到文本文件中。

例子 :

输入文件 :

a,b,c
# Some Junk to Skip 1
4,5,6
# Some junk to skip 2
9,20,9
2,3,4
5,6,7

代码 :

skiprows = [1,3]
df = pandas.read_csv(file, skip_rows = skiprows)

现在 output.txt :

# Some junk to skip 1
# Some junk to skip 2

提前致谢!

标签: pythonpython-3.xpandasnumpydataframe

解决方案


def write_skiprows(infile, skiprows, outfile='skiprows.csv')
    maxrow = max(skiprows)
    with open(infile, 'r') as f, open(outfile, 'w') as o:
        for i, line in enumerate(f):
            if i in skiprows:
                o.write(line)
            if i == maxrow:
                return

推荐阅读