如何减少打印NumPy数组时小数点后的零位数?
NumPy数组打印格式优化问题
我运行了以下代码:
import numpy as np V = np.ones((12, 12)) V[1][5] = 123523.42341234 print(np.round(V[0], 3)) print(np.round(V, 3))
第一个print输出符合预期:
[1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1.]
但第二个print输出用科学计数法显示所有元素,导致可读性极差:
[[1.00000000e+00 1.00000000e+00 1.00000000e+00 1.00000000e+00 1.00000000e+00 1.00000000e+00 1.00000000e+00 1.00000000e+00 1.00000000e+00 1.00000000e+00 1.00000000e+00 1.00000000e+00] [1.00000000e+00 1.00000000e+00 1.00000000e+00 1.00000000e+00 1.00000000e+00 1.23523423e+05 1.00000000e+00 1.00000000e+00 1.00000000e+00 1.00000000e+00 1.00000000e+00 1.00000000e+00] ...]
实际场景中数组还有更多非1元素,我希望把1.00000000e+00显示为1,同时保留其他元素的合理精度,该怎么实现?
解决方案
方法1:全局设置NumPy打印选项
通过调整NumPy的默认打印规则,让数值自动以紧凑格式显示:
import numpy as np # 配置打印参数:禁用科学计数法、保留3位小数、固定精度格式 np.set_printoptions(suppress=True, precision=3, floatmode='fixed') V = np.ones((12, 12)) V[1][5] = 123523.42341234 print(np.round(V, 3))
输出效果:
[[1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. ] [1. 1. 1. 1. 1. 123523.423 1. 1. 1. 1. 1. 1. ] [1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. ] ...]
suppress=True:强制关闭科学计数法,小数部分为0的数值自动显示为整数格式precision=3:统一保留3位小数floatmode='fixed':确保所有数值按固定精度规则显示
方法2:临时设置打印格式(不影响全局)
如果不想修改全局默认配置,用上下文管理器实现临时生效:
import numpy as np V = np.ones((12, 12)) V[1][5] = 123523.42341234 with np.printoptions(suppress=True, precision=3, floatmode='fixed'): print(np.round(V, 3))
方法3:自定义格式化函数(精细控制)
如果需要更灵活的规则(比如仅将整数显示为整数,其他数值保留小数),可以遍历数组自定义格式化:
import numpy as np def format_array(arr): return [[int(x) if x.is_integer() else round(x, 3) for x in row] for row in arr] V = np.ones((12, 12)) V[1][5] = 123523.42341234 formatted_V = format_array(np.round(V, 3)) # 逐行打印格式化后的数组 for row in formatted_V: print(row)
输出效果:
[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1] [1, 1, 1, 1, 1, 123523.423, 1, 1, 1, 1, 1, 1] [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1] ...
内容的提问来源于stack exchange,提问作者Silviu
相关产品推荐
相关产品推荐

