Jupyter Notebook 中美观显示矩阵与解决大数组截断问题

今天早睡
今天早睡
发布时间:2026-10-13| 5人浏览过
原创

本文介绍在 Jupyter Notebook 中通过自定义 Python 函数将矩阵转换为 Latex 格式以实现美观显示的方法,同时提供使用 np.set_printoptions 解决 numpy 大数组显示不全的两种配置方案,帮助开发者优化数据可视化效果。

Jupyter Notebook 中美观显示矩阵

为了直观展示效果,这里直接提供相关代码实现。


from IPython.display import display,Latex,Math
%matplotlib inline
 
from IPython.core.interactiveshell import InteractiveShell
sh = InteractiveShell.instance()
 
def number_to_str(n,cut=5):
  ns=str(n)
  format_='{0:.'+str(cut)+'f}'
  if 'e' in ns or ('.' in ns and len(ns)>cut+1):
    return format_.format(n)
  else:
    return str(n)
 
def matrix_to_latex(mat,style='bmatrix'):
  if type(mat)==np.matrixlib.defmatrix.matrix:
    mat=mat.A
  head=r'\begin{'+style+'}'
  tail=r'\end{'+style+'}'
  if len(mat.shape)==1:
    body=r'\\'.join([str(el) for el in mat])
    return head+body+tail
  elif len(mat.shape)==2:
    lines=[]
    for row in mat:
      lines.append('&'.join([number_to_str(el) for el in row])+r'\\')
    s=head+' '.join(lines)+tail
    return s
  return None
 
sh.display_formatter.formatters['text/latex'].type_printers[np.ndarray]=matrix_to_latex

将代码输入到 Notebook 单元格并运行即可生效。

执行后,矩阵的打印输出将呈现更加美观的排版格式。

解决 numpy 大数组显示不全问题

补充知识:解决 python numpy 大数组显示不全的问题

import numpy as np np.set_printoptions(threshold=np.inf)

或者

np.set_printoptions(threshold='nan')

其中 threshold 表示:

Total number of array elements to be print(输出数组的元素数目)

以上这篇 jupyter notebook 中美观显示矩阵实例就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持本站。

免责声明:本文内容仅供参考,不代表本站观点。转载或引用请注明出处。

Python 相关产品和应用

全部下载
Selenium

Selenium

4.51.0 · Windows

用于浏览器自动化和 Web 测试的 Python 工具。

scikit-learn

scikit-learn

1.9.1 · Windows

常用 Python 机器学习算法与模型评估工具库。

Black

Black

26.10.1 · Windows

强调一致性的 Python 自动代码格式化工具。

Ruff

Ruff

0.17.1 · macOS

由 Rust 编写的高速 Python 代码检查和格式化工具。

pytest

pytest

9.1.1 · Windows

简洁而强大的 Python 自动化测试框架。

FastAPI

FastAPI

0.146.0 · Windows

高性能 Python API 框架,支持类型提示和自动接口文档。

Flask

Flask

3.1.3 · Windows

轻量灵活的 Python Web 应用框架。

Django

Django

6.1.2 · Windows

成熟的 Python Web 框架,适合构建内容站点和业务系统。

Spyder

Spyder

6.1.7 · Windows

面向科学计算与数据分析的 Python 集成开发环境。

SciPy

SciPy

1.18.1 · Windows

面向科学、工程和技术计算的 Python 算法库。