numpy数组
1. array()
numpy.array可以将一个List转成numpy数组,如:
import numpy as np
np.array([1,2,3,4])
np.array([[1,2,3],[1,2,3],[1,2,3]])
运行结果为:
array([1, 2, 3, 4])
array([[1, 2, 3],
[1, 2, 3],
[1, 2, 3]])
2. arange()
numpy.arange的使用方法类似与range,只是生成的是numpy数组,如:
import numpy as np
np.arange(5)
运行结果为:
array([0, 1, 2, 3, 4])
3. logspace()
logspace函数和linspace类似,不过它创建等比数列,下面的例子产生1(100)到100(102)、有20个元素的等比数列:
如:
import numpy as np
np.logspace(0, 2, 20)1, 2, 3, 4])
运行结果为:
array([ 1. , 1.27427499, 1.62377674, 2.06913808,
2.6366509 , 3.35981829, 4.2813324 , 5.45559478,
6.95192796, 8.8586679 , 11.28837892, 14.38449888,
18.32980711, 23.35721469, 29.76351442, 37.92690191,
48.32930239, 61.58482111, 78.47599704, 100. ])
4. linspace()
linspace函数通过指定开始值、终值和元素个数来创建一维数组,可以通过endpoint关键字指定是否包括终值,缺省设置是包括终值 ,如:
import numpy as np
np.linspace(2.0, 3.0, num=5, endpoint=False)
运行结果为:
array([ 2. , 2.2, 2.4, 2.6, 2.8])
5. ones()
numpy.ones用于生成一个全是1的numpy数组,如:
import numpy as np
np.ones(5)
np.ones((5, 3))
运行结果为:
array([ 1., 1., 1., 1., 1.])
array([[ 1., 1., 1.],
[ 1., 1., 1.],
[ 1., 1., 1.],
[ 1., 1., 1.],
6. zeros()
numpy.zeros的使用方式与numpy.ones类似,不同的是数组中的内容全部为0,如:
import numpy as np
np.zeros(2)
np.zeros((2, 2))
运行结果为:
array([ 0, 0])
array([[ 0, 0],
[ 0, 0]])
7. empty()
numpy.empty的使用方式与numpy.ones类似,不同的是数组中的内容是无意义的数值,如:
import numpy as np
np.empty(2)
np.empty((2, 2))
运行结果为:
array([ 4.24399158e-314, 8.48798317e-314])
array([[ 4.94065646e-324, 9.88131292e-324],
[ 1.48219694e-323, 1.97626258e-323]])
8. meshgrid()
快速生成二维数据的行列号。用途:X、Y二维数组可当作matplotlib会图库的x,y两个参数使用。
import numpy as np
x = np.arange(10)
y = np.arange(15)
X, Y = np.meshgrid(x, y)
运行结果为:
X
array([[0, 1, 2, 3, 4, 5, 6, 7, 8, 9],
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9],
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9],
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9],
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9],
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9],
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9],
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9],
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9],
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9],
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9],
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9],
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9],
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9],
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]])
Y
array([[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
[ 2, 2, 2, 2, 2, 2, 2, 2, 2, 2],
[ 3, 3, 3, 3, 3, 3, 3, 3, 3, 3],
[ 4, 4, 4, 4, 4, 4, 4, 4, 4, 4],
[ 5, 5, 5, 5, 5, 5, 5, 5, 5, 5],
[ 6, 6, 6, 6, 6, 6, 6, 6, 6, 6],
[ 7, 7, 7, 7, 7, 7, 7, 7, 7, 7],
[ 8, 8, 8, 8, 8, 8, 8, 8, 8, 8],
[ 9, 9, 9, 9, 9, 9, 9, 9, 9, 9],
[10, 10, 10, 10, 10, 10, 10, 10, 10, 10],
[11, 11, 11, 11, 11, 11, 11, 11, 11, 11],
[12, 12, 12, 12, 12, 12, 12, 12, 12, 12],
[13, 13, 13, 13, 13, 13, 13, 13, 13, 13],
[14, 14, 14, 14, 14, 14, 14, 14, 14, 14]])