use*_*942 5 string format numpy
问题:我的方法是将numpy数组转换为具有特定小数位数的numpy字符串数组,并且尾随零删除了"最佳"方式?
import numpy as np
x = np.array([1.12345, 1.2, 0.1, 0, 1.230000])
print np.core.defchararray.rstrip(np.char.mod('%.4f', x), '0')
Run Code Online (Sandbox Code Playgroud)
输出:
['1.1235' '1.2' '0.1' '0.' '1.23']
Run Code Online (Sandbox Code Playgroud)
这是理想的结果.(我对舍入问题没问题)
两个函数'rstrip'和'mod'都是numpy函数,这意味着这很快但是有一种方法可以通过一个内置的numpy函数实现这个功能吗?(即'mod'有一个我找不到的选项吗?)它会节省两次返回副本的开销,这对于非常大的数组来说是慢的.
谢谢!
感谢 Warren Weckesser 提供的宝贵意见。归功于他。
我将代码转换为使用:
formatter = '%d'
if num_type == 'float':
formatter = '%%.%df' % decimals
np.savetxt(out, arr, fmt=formatter)
Run Code Online (Sandbox Code Playgroud)
其中 out 是我已经写入标头的文件句柄。或者,我也可以使用headers=中的参数np.savetxt。我不知道为什么我没有在文档中看到这些选项。
对于 1300 x 1300 的 numpy 数组,像我之前那样创建逐行输出(使用np.core.defchararray.rstrip(np.char.mod('%.4f', x), '0'))需要大约 1.7 秒,而使用np.savetxt需要 0.48 秒。
np.savetxt更干净、更易读、更快速的解决方案也是如此。
注意:我确实尝试过:
np.savetxt(out, arr, fmt='%.4g')
Run Code Online (Sandbox Code Playgroud)
试图不根据数字类型进行切换,但它没有像我希望的那样工作。