pandas - Pandas:用于导出到 csv 的可变精度
问题描述
如何设置可调精度,使其根据值自行调整?这是导出到csv。
例如对于以下值:
将最大精度设置为 18。
0.00748333333333333 -> 0.00748333333333
12.0000000 -> 12.0
0.43242300000 -> 0.432423
解决方案
一种可能的解决方案是使用正则表达式替换保存的 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
推荐阅读
- mysql - 将具有相同值的多行分组mysql
- wordpress - WordPress + Nginx + Cloudflare - 无法正确加载
- css - 轮播中使用的图像高度与用于保存轮播的 div 无关
- python-3.x - 将边缘列表加载到图形工具中
- javascript - 如何将我的机器学习 R 代码嵌入网站
- c# - 修改RESX文件后无法构建我的解决方案
- macos - Mac OS 上的 HTC vive 开发(Macbook Pro 15" 2017 年末,配备 Radeon pro 555)
- sql-server - 同一个站号(参考号),如何对比2小时前的记录
- ssas - SSAS 如何填充 MDSCHEMA_LEVELS 行集中的 LEVEL_TYPE 信息
- typescript - NestJs 是否支持 WebSocket 网关的速率限制?