1.手动构造数组
import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt
import math
from matplotlib import cm
def visualize_2D(array, vmax, vmin):
fig_width = math.ceil(array.shape[1] * 0.5)
fig_length = math.ceil(array.shape[0] * 0.5)
fig, ax = plt.subplots(figsize = (fig_width, fig_length))
sns.heatmap(array,
vmax = vmax,
vmin = vmin,
annot = True,
fmt = '.0f',
square = True,
cmap = 'RdYlBu_r',
linewidth = .5,
cbar = False,
xticklabels = False,
yticklabels = False,
ax = ax)
def visual_1D(array):
fix, ax = plt.subplots()
colors = cm.RdYlBu_r(np.linspace(0, 1, len(array)))
for idx,num in enumerate(array):
circle_idx = plt.Circle((idx, 0 ),
0.5,
facecolor = colors[idx],
edgecolor = 'w')
ax.add_patch(circle_idx)
ax.text(idx, 0, s = str(array[idx]),
horizontalalignment = 'center',
verticalalignment = 'center'
)
ax.set_xlim(-0.6, 0.6 + len(array))
ax.set_ylim(-0.6, 0.6)
ax.set_aspect('equal', adjustable = 'box')
1.一维数组的生成
a_1D = np.array(range(-1,8))
print(a_1D)
print(a_1D.shape)
print(len(a_1D))
print(a_1D.size)
print(a_1D.ndim)
visual_1D(a_1D)
[-1 0 1 2 3 4 5 6 7]
(9,)
9
9
1

2.二维数组的生成
a_2D = np.array([[1,-1,3],[2,3,-9]])
print(a_2D)
print(a_2D.shape)
print(len(a_2D))
print(a_2D.size)
print(a_2D.ndim)
visualize_2D(a_2D,1,-9)
[[ 1 -1 3]
[ 2 3 -9]]
(2, 3)
2
6
2

3.三维数组的生成
a_3D = np.array([[[1,-1,3],
[2,3,-9]],
[[0,-1,8],
[2,3,-1]]])
print(a_3D)
print(a_3D.shape)
print(len(a_3D))
print(a_3D.size)
print(a_3D.ndim)
visualize_2D(a_3D[0],9,-1)
visualize_2D(a_3D[1],9,-1)
[[[ 1 -1 3]
[ 2 3 -9]]
[[ 0 -1 8]
[ 2 3 -1]]]
(2, 2, 3)
2
12
3


2.网格数据的生成
import numpy as np
import matplotlib.pyplot as plt
x1_array = np.linspace(-3, 3, 21)
x2_array = np.linspace(-3, 3, 21)
xx1, xx2 = np.meshgrid(x1_array, x2_array)
print(x2_array.shape,x1_array.shape,xx1.shape)
ff = xx1 * np.exp(-xx1**2 - xx2**2)
fig = plt.figure()
ax = fig.add_subplot(projection = '3d')
ax.plot_wireframe(xx1,xx2,ff,color = 'grey',
rstride = 1,
cstride = 1
)
ax.scatter(xx1, xx2, ff, c = ff, cmap = 'RdYlBu_r')
plt.show()
(21,) (21,) (21, 21)

3.特殊数组
构造单位矩阵
a = np.eye(5)
visualize_2D(a,1,0)

构造固定值填充的矩阵
visualize_2D(np.full((3,3), 0),0,0)

A = np.array([[1, 2, 3],
[4, 5, 6]])
np.full_like(A, 100)
array([[100, 100, 100],
[100, 100, 100]])
构造全1矩阵
np.ones(5)
array([1., 1., 1., 1., 1.])
np.ones((5,5))
A = np.array([[1, 2, 3],
[4, 5, 6]])
np.ones_like(A)
构造全0矩阵
np.zeros(5)
np.zeros((5,5))
A = np.array([[1, 2, 3],
[4, 5, 6]])
np.zeros_like(A)
array([[0, 0, 0],
[0, 0, 0]])
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本