Pandas to_csv call is prepending a comma

前端 未结 1 1951
花落未央
花落未央 2020-12-10 03:45

I have a data file, apples.csv, that has headers like:

\"id\",\"str1\",\"str2\",\"str3\",\"num1\",\"num2\"

I read it into a dataframe with

相关标签:
1条回答
  • 2020-12-10 03:53

    Set index=False (the default is True hence why you see this output) so that it doesn't save the index values to your csv, see the docs

    So this:

    df = pd.DataFrame({'a':np.arange(5), 'b':np.arange(5)})
    df.to_csv(r'c:\data\t.csv')
    

    results in

    ,a,b
    0,0,0
    1,1,1
    2,2,2
    3,3,3
    4,4,4
    

    Whilst this:

    df.to_csv(r'c:\data\t.csv', index=False)
    

    results in this:

    a,b
    0,0
    1,1
    2,2
    3,3
    4,4
    

    It's for the situation where you may have some index values you want to save

    0 讨论(0)
提交回复
热议问题