Ima*_*ngo 5 python arrays numpy pretty-print
np.set_printoptions允许自定义numpy 数组的漂亮打印。然而,对于不同的用例,我希望有不同的打印选项。
理想情况下,无需每次都重新定义整个选项即可完成此操作。我正在考虑使用本地范围,例如:
with np.set_printoptions(precision=3):
print my_numpy_array
Run Code Online (Sandbox Code Playgroud)
但是,set_printoptions似乎不支持with语句,因为会抛出错误(AttributeError: __exit__)。有没有什么方法可以在不创建自己的漂亮打印类的情况下完成这项工作?我知道我可以创建自己的上下文管理器:
class PrettyPrint():
def __init__(self, **options):
self.options = options
def __enter__(self):
self.back = np.get_printoptions()
np.set_printoptions(**self.options)
def __exit__(self, *args):
np.set_printoptions(**self.back)
Run Code Online (Sandbox Code Playgroud)
并将其用作:
>>> print A
[ 0.29276529 -0.01866612 0.89768998]
>>> with PrettyPrint(precision=3):
print A
[ 0.293 -0.019 0.898]
Run Code Online (Sandbox Code Playgroud)
然而,有没有比创建新类更直接的东西(最好已经内置)?
尝试
np.array_repr(x, precision=6, suppress_small=True)
Run Code Online (Sandbox Code Playgroud)
或者采用诸如 之类的关键字的相关函数之一precision。看起来它可以控制许多(如果不是全部)打印选项。
因此,基于@unutbu给出的链接,而不是使用
with np.set_printoptions(precision=3):
print (my_numpy_array)
Run Code Online (Sandbox Code Playgroud)
我们应该使用:
with np.printoptions(precision=3):
print my_numpy_array
Run Code Online (Sandbox Code Playgroud)
这适用于我的情况。如果情况似乎没有改变,请尝试操作打印选项的其他参数,例如linewidth = 125, edgeitems = 7, threshold = 1000等等。