pandas to_csv float format 任意精度无工程格式化

pandas to_csv float format arbitrary precision without engineering formating

我有一个 pandas 数据框,其中包含任意大值和小值(其大小未知 先验 ),比如:

>>> import pandas as pd
>>> df = pd.DataFrame({'a' : [0.0000001, 2, 3], 'b' : [4, 5000000, 0.6]})

默认显示会将某些数字转换为工程格式

>>> df
              a          b
0  1.000000e-07        4.0
1  2.000000e+00  5000000.0
2  3.000000e+00        0.6

我不在乎。然而,我的目标是将其写入一个没有工程格式的 csv 文件,同时也不打印不必要的 0。要求的第二部分是控制文件大小,因为有数百万行。

例如,如果我 运行 df.to_csv(csv_file) 那么文件看起来像

,a,b
0,1e-07,4.0
1,2.0,5000000.0
2,3.0,0.6

如果我 运行 df.to_csv(csv_file, float_format="%.7f") 那么它看起来像(注意所有不必要的 0):

,a,b
0,0.0000001,4.0000000
1,2.0000000,5000000.0000000
2,3.0000000,0.6000000

我想在输出文件中包含的内容是:

,a,b
0,0.0000001,4.0
1,2.0,5000000.0
2,3.0,0.6

有没有简单的方法可以实现?

import pandas as pd   
df = pd.DataFrame({'a' : [0.0000001, 2, 3], 'b' : [4, 5000000, 0.6]})   


def export_formatted(df, csv_path, cols=None):

    # By default, format all columns in df
    if cols==None:
        cols = df.columns

    # Change columns to strings with 0's stripped as desired
    for c in cols:
        df[c] = df[c].map('{:,.15f}'.format).str.rstrip('0')

    # export
    df.to_csv(csv_path)

export_formatted(df, 'stack_overflow_scratch2.csv')

提供我认为你想要的(下):

    a               b
0   0.0000001       4
1   2               5000000
2   3               0.6