如何在Jupyter Notebook中显示numpy数组的全部结果值?
问题:Jupyter Notebook中无法查看完整NumPy数组内容
我编写了如下基于NumPy库的Python代码,用于生成晶格坐标数组coords1和coords2:
import numpy as np import matplotlib.pyplot as plt d0 = 0.3330630630630631 a0 = 0.15469469469469468 theta = 2 nmax=15 # lattice vectors sublattice 1 a1= np.array([3/2*a0,3**0.5/2*a0,0]) a2= np.array([3/2*a0,-3**0.5/2*a0,0]) # lattice vectors sublattice 2 b1 = np.array([ np.cos(theta) * a1[0] - np.sin(theta) * a1[1], np.sin(theta) * a1[0] + np.cos(theta) * a1[1], 0 ]) b2 = np.array([ np.cos(theta) * a2[0] - np.sin(theta) * a2[1], np.sin(theta) * a2[0] + np.cos(theta) * a2[1], 0 ]) ## coordinates for the unrotated layer sublattice a&b coords1a = np.array([i * a1 + j * a2 for i in range(-nmax-1, nmax+1) for j in range(-nmax-1, nmax+1)]) coords1b = np.array([i * a1 + j * a2 + [a0,0.,0.] for i in range(-nmax-1, nmax+1) for j in range(-nmax-1, nmax+1)]) ## coordinates for the rotated layer sublattice a&b coords2a = np.array([i * b1 + j * b2 + [0.,0.,d0] for i in range(-nmax-1, nmax+1) for j in range(-nmax-1, nmax+1)]) coords2b = np.array([i * b1 + j * b2 + [np.cos(theta)*a0,np.sin(theta)*a0,d0] for i in range(-nmax-1, nmax+1) for j in range(-nmax-1, nmax+1)]) coords1 = np.concatenate((coords1a, coords1b)) coords2 = np.concatenate((coords2a, coords2b))
但在Jupyter Notebook中查看coords1和coords2数组时,仅显示6个元素及省略号,无法查看全部值,请问该如何设置才能显示所有结果值?
解决方案
方法1:修改NumPy全局打印配置
通过设置NumPy的打印阈值为无穷大,让它显示数组的所有元素:
import numpy as np # 设置显示所有元素 np.set_printoptions(threshold=np.inf) # 直接打印数组 print(coords1) print(coords2)
如果不想全局修改配置,可使用上下文管理器临时生效:
import numpy as np with np.printoptions(threshold=np.inf): print(coords1)
方法2:转换为Python列表查看
将NumPy数组转换为普通Python列表,默认会显示所有元素:
print(coords1.tolist())
方法3:结合Jupyter的显示工具
使用IPython的display函数配合NumPy配置,在Notebook中完整显示数组:
from IPython.display import display import numpy as np np.set_printoptions(threshold=np.inf) display(coords1)
内容的提问来源于stack exchange,提问作者didem
相关产品推荐
相关产品推荐

