首页 > 解决方案 > Pandas:用于导出到 csv 的可变精度

问题描述

如何设置可调精度,使其根据值自行调整?这是导出到csv。

例如对于以下值:

将最大精度设置为 18。

0.00748333333333333 -> 0.00748333333333
12.0000000 -> 12.0
0.43242300000 -> 0.432423

标签: pandas

解决方案


一种可能的解决方案是使用正则表达式替换保存的 CSV 文件中不需要的零:

import re

df = pd.DataFrame({
    'x1':[*np.random.randn(5), *[2, 3, 1.25]],
    'x2':[*np.random.randn(5), *[2, 3, 1.25]],
})

# Save CSV file
csv_file_name = 'test.csv'
df.to_csv(csv_file_name, float_format="%0.8f") 

# Read CSV file
with open(csv_file_name, 'r') as file: 
    s = file.read()

# Replace zeros using regex
s = re.sub("[0]+\n", "\n", s)
s = re.sub("[0]+,", ",", s)

# Re-save CSV file
with open(csv_file_name, 'w') as file: 
    file.write(s)

生成的 CSV:

,x1,x2
,-0.48248428,0.37133094
1,-0.58110733,-1.08972915
2,-0.25407414,-0.83307601
3,-0.73887322,-0.37982818
4,0.11092894,0.93965402
5,2.,2.
6,3.,3.
7,1.25,1.25

推荐阅读