简介
NumPy是一个开源的Python库,它提供了一个强大的N维数组对象和许多用于操作这些数组的函数。它是大多数Python科学计算的基础,包括Pandas、SciPy和scikit-learn等库都建立在NumPy之上。
安装
python
!pip install numpy
导入
python
import numpy as np
用法
python
# 创建1*6矩阵
a = np.array([1, 2, 3, 4, 5, 6])
print('a=\n', a)
print('a.shape=', a.shape)
# 数组索引
b = a[0:3]
print('b=', b)
c = a[1:3]
print('c=', c)
d = a[3:]
print('d=', d)
a=
[1 2 3 4 5 6]
a.shape= (6,)
b= [1 2 3]
c= [2 3]
d= [4 5 6]
python
# 创建3*3的矩阵
a = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
print('a=\n', a)
print('a[0, 0]=', a[0, 0])
print('a.shape=', a.shape)
print('a.ndim=', a.ndim)
print('a.size=', a.size)
print('a.dtype=', a.dtype)
# 数组索引
b = a[1:,2:]
print('b=', b)
a=
[[1 2 3]
[4 5 6]
[7 8 9]]
a[0, 0]= 1
a.shape= (3, 3)
a.ndim= 2
a.size= 9
a.dtype= int64
b= [[6]
[9]]
python
# 创建0数组
a = np.zeros(2)
print('a=\n', a)
a=
[0. 0.]
python
# 创建1数组
a = np.ones(3)
print('a=\n', a)
a=
[1. 1. 1.]
python
# 创建等差序列,从2到15递增3
a = np.arange(2, 15, 3)
print('a=\n', a)
a=
[ 2 5 8 11 14]
python
# 创建等差序列,从2到15共10个数
a = np.linspace(2, 15, num=10)
print('a=\n', a)
a=
[ 2. 3.44444444 4.88888889 6.33333333 7.77777778 9.22222222
10.66666667 12.11111111 13.55555556 15. ]
python
# 数组排序
a = np.array([2, 4 ,6, 8, 1, 9, 10])
print('a_sort=', np.sort(a))
a_sort= [ 1 2 4 6 8 9 10]
python
import matplotlib.pyplot as plt
python
# 一维数组作图
x = np.linspace(0, 5, 30)
y = np.linspace(0, 10, 30)
plt.plot(x, y, 'r') # line
plt.plot(x, y, 'o') # dots
[<matplotlib.lines.Line2D at 0x7f8f70513e50>]
python
fig = plt.figure()
ax = fig.add_subplot(projection='3d')
X = np.arange(-5, 10, 0.15)
Y = np.arange(-5, 8, 0.15)
X, Y = np.meshgrid(X, Y)
R = np.sqrt(X**2 + Y**2)
Z = np.sin(R)
d(X, Y)
R = np.sqrt(X**2 + Y**2)
Z = np.sin(R)
ax.plot_surface(X, Y, Z, rstride=1, cstride=1, cmap='viridis')
<mpl_toolkits.mplot3d.art3d.Poly3DCollection at 0x7f8ecd21de10>