Output different precision by column with pandas.DataFrame.to_csv()?

后端 未结 6 1691
深忆病人
深忆病人 2020-12-13 02:51

Question

Is it possible to specify a float precision specifically for each column to be printed by the Python pandas package method pandas.DataFrame.t

相关标签:
6条回答
  • 2020-12-13 03:00

    The to_string approach suggested by @mattexx looks better to me, since it doesn't modify the dataframe.

    It also generalizes well when using jupyter notebooks to get pretty HTML output, via the to_html method. Here we set a new default precision of 4, and override it to get 5 digits for a particular column wider:

    from IPython.display import HTML
    from IPython.display import display
    
    pd.set_option('precision', 4)
    
    display(HTML(df.to_html(formatters={'wider': '{:,.5f}'.format})))
    
    0 讨论(0)
  • 2020-12-13 03:08

    Change the type of column "vals" prior to exporting the data frame to a CSV file

    df_data['vals'] = df_data['vals'].map(lambda x: '%2.1f' % x)
    
    df_data.to_csv(outfile, index=False, header=False, float_format='%11.6f')
    
    0 讨论(0)
  • 2020-12-13 03:15

    You can do this with to_string. There is a formatters argument where you can provide a dict of columns names to formatters. Then you can use some regexp to replace the default column separators with your delimiter of choice.

    0 讨论(0)
  • 2020-12-13 03:20

    The more current version of hknust's first line would be:

    df_data['vals'] = df_data['vals'].map(lambda x: '{0:.1}'.format(x))
    

    To print without scientific notation:

    df_data['vals'] = df_data['vals'].map(lambda x: '{0:.1f}'.format(x)) 
    
    0 讨论(0)
  • 2020-12-13 03:23

    You can use round method for dataframe before saving the dataframe to the file.

    df_data = df_data.round(6)
    df_data.to_csv('myfile.dat')
    
    0 讨论(0)
  • 2020-12-13 03:23

    This question is a bit old, but I'd like to contribute with a better answer, I think so:

    formats = {'lats': '{:10.5f}', 'lons': '{:.3E}', 'vals': '{:2.1f}'}
    
    for col, f in formats.items():
        df_data[col] = df_data[col].map(lambda x: f.format(x))
    

    I tried with the solution here, but it didn't work for me, I decided to experiment with previus solutions given here combined with that from the link above.

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