保存跳过的行在 pandas 读csv [英] Save skip rows in pandas read csv

查看:62
本文介绍了保存跳过的行在 pandas 读csv的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a list of skip rows ( say [1,5,10] --> row numbers) and when I passed this to pandas read_csv, it ignores those rows. But, I need to save these skipped rows in a different text file.

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

I went through pandas read_csv documentation and few other articles, but have no idea how to save this into a text file.

示例:

输入文件:

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:

Now output.txt :

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

提前谢谢!

推荐答案

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

这篇关于保存跳过的行在 pandas 读csv的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆