1.NumPy中的np.set_printoptions使用:
在 NumPy 中,np.set_printoptions
函数用于自定义数组的打印格式,使输出更符合特定需求。以下是它的详细用法和应用场景:
1.基础语法:
np.set_printoptions(
precision=None, # 浮点数的精度(小数点后的位数)
threshold=None, # 数组元素超过此值时使用缩略打印
edgeitems=None, # 边缘显示的元素数量
linewidth=None, # 每行的字符宽度
suppress=None, # 是否强制浮点数使用固定点表示法
nanstr=None, # NaN的字符串表示
infstr=None, # Inf的字符串表示
formatter=None, # 自定义格式化函数
...
)
2.常见示例:
1. 控制浮点数精度
import numpy as np
x = np.array([1.23456789])
np.set_printoptions(precision=3)
print(x) # 输出:[1.235]
2. 抑制科学计数法
y = np.array([1e-10, 1e-5, 1e10])
np.set_printoptions(suppress=True)
print(y) # 输出:[0. 0.00001 10000000000.]
3. 缩略打印大型数组
z = np.arange(100)
np.set_printoptions(threshold=5) # 只显示边缘元素
print(z) # 输出:[ 0 1 2 ... 97 98 99]
4. 自定义元素格式
a = np.array([1, 2, 3])
np.set_printoptions(formatter={'all': lambda x: f'*{x}*'})
print(a) # 输出:[*1* *2* *3*]
3.常用参数详解:
参数 | 作用 |
---|---|
precision |
设置浮点数的显示精度(小数点后的位数)。 |
threshold |
当数组元素总数超过此值时,启用缩略打印(显示省略号)。 |
edgeitems |
缩略打印时,数组首尾显示的元素数量。 |
suppress |
若为 True ,则强制浮点数使用固定点表示法(如 0.001 而非 1e-3 )。 |
formatter |
传入字典,为不同类型的元素指定自定义格式化函数(如 int , float , complex )。 |
4.应用场景:
<