Save skip rows in pandas read csv

淺唱寂寞╮ 提交于 2021-02-04 16:44:27

问题


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.

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

Example :

Input 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

Code :

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

Now output.txt :

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

Thanks in advance!


回答1:


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



回答2:


try this,

df=pd.read_csv('input.csv')
skiprows=[1,3,6]
df,df_skiprow=df.drop(skiprows),df.iloc[skiprows]
#df_skiprow.to_csv('skiprows.csv',index=False)

Input:

    a    b
0   1   c1
1   2   c2
2   3   c3
3   4   c4
4   5   c5
5   6   c6
6   7   c7
7   8   c8
8   9   c9
9  10  c10

Output: df

    a    b
0   1   c1
2   3   c3
4   5   c5
5   6   c6
7   8   c8
8   9   c9
9  10  c10

df_skiprow

   a   b
1  2  c2
3  4  c4
6  7  c7

Explanation:

  1. read whole file.
  2. split file by df and skiprow
  3. convert into seperate csv file.


来源:https://stackoverflow.com/questions/50613156/save-skip-rows-in-pandas-read-csv

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!