Writing a pandas DataFrame to CSV file

前端 未结 7 1784
死守一世寂寞
死守一世寂寞 2020-11-22 11:07

I have a dataframe in pandas which I would like to write to a CSV file. I am doing this using:

df.to_csv(\'out.csv\')

And getting the error

7条回答
  •  攒了一身酷
    2020-11-22 11:26

    Something else you can try if you are having issues encoding to 'utf-8' and want to go cell by cell you could try the following.

    Python 2

    (Where "df" is your DataFrame object.)

    for column in df.columns:
        for idx in df[column].index:
            x = df.get_value(idx,column)
            try:
                x = unicode(x.encode('utf-8','ignore'),errors ='ignore') if type(x) == unicode else unicode(str(x),errors='ignore')
                df.set_value(idx,column,x)
            except Exception:
                print 'encoding error: {0} {1}'.format(idx,column)
                df.set_value(idx,column,'')
                continue
    

    Then try:

    df.to_csv(file_name)
    

    You can check the encoding of the columns by:

    for column in df.columns:
        print '{0} {1}'.format(str(type(df[column][0])),str(column))
    

    Warning: errors='ignore' will just omit the character e.g.

    IN: unicode('Regenexx\xae',errors='ignore')
    OUT: u'Regenexx'
    

    Python 3

    for column in df.columns:
        for idx in df[column].index:
            x = df.get_value(idx,column)
            try:
                x = x if type(x) == str else str(x).encode('utf-8','ignore').decode('utf-8','ignore')
                df.set_value(idx,column,x)
            except Exception:
                print('encoding error: {0} {1}'.format(idx,column))
                df.set_value(idx,column,'')
                continue
    

提交回复
热议问题