StudyNotes-Numpy array

1.Basic Conception

我们创建数组的目的,很多时候是用来做原型验证和算法验证的。NumPy 为创建数组提供了非常丰富的手段,可以无中生有(简单数组),可以移花接木,还可以举一反三(复杂数组)。配合数据类型设置、结构设置,就可以构造出我们想要的任何形式的数组了。

2.Create Simple Arrays

2.1蛮力构造法 np.array():

numpy.array(object, dtype=None, copy=True, order=None, subok=False, ndmin=0)
eg.
a=np.array([1,2,3],[4,5,6]) #创建两行三列数组

2.2特殊数值法 np.ones()/ np.zeros()/ np.eye()/ np.empty():

特殊值一般指0,1,空值等。特殊数值法适合构造全0、全1、空数组,或者由0、1组成的类似单位矩阵(主对角线为1,其余为0)的数组。
umpy.zeros(shape, dtype=float, order=‘C’)
numpy.ones(shape, dtype=float, order=‘C’)
numpy.empty(shape, dtype=float, order=‘C’)
numpy.eye(N, M=None, k=0, dtype=float, order='C’)
eg.
np.zeros(6)
array([0., 0., 0., 0., 0., 0.])

np.zeros((2,3))
array([[0., 0., 0.],
[0., 0., 0.]])

np.ones((2,3),dtype=np.float)
array([[1., 1., 1.],
[1., 1., 1.]])

np.empty((2,3))
array([[1., 1., 1.],
[1., 1., 1.]])

np.eye(2)
array([[1., 0.],
[0., 1.]])

#创建一个三行四列数值都是5的数组
a=np.empty((3,4),dtype=int8)
a.fill(5)
array([[5, 5, 5, 5],
[5, 5, 5, 5],
[5, 5, 5, 5]], dtype=int8)

2.3随机数值法 np.random.random()/ np.random.randint()

numpy.random.random(size=None)
numpy.random.randint(low, high=None, size=None, dtype=‘l’)
numpy.random.normal(loc=0.0, scale=1.0, size=None)
eg. random() 生成 [0,1) 区间内的随机浮点数数,randint() 生成 [low, high) 区间内的随机整数。
np.random.random(3)
array([0.4129063 , 0.94242888, 0.10129428])

np.random.random((2,3))
array([[0.80530845, 0.96161533, 0.89166972],
[0.22920038, 0.84989557, 0.46865645]])

np.random.randint(5)
4

np.random.randint(1,5,size=(2,3))
array([[3, 3, 1],
[3, 3, 3]])

normal() 生成以 loc 为均值、以 scale 为标准差的正态分布数组。下面,我们用正态分布函数模拟生成1000位成年男性的身高数据(假定中国成年男性平均身高170厘米,标准差4厘米),并画出柱状图:
import matplotlib.pyplot as plt
tall=np.random.normal(170,4,1000)
bins=np.arange(156,190,2) #start, stop, step
plt.hist(tall, bins)
StudyNotes-Numpy array

2.4定长分割法 np.arange()/ np.linspace()/ np.logspace():

numpy.arange(start, stop, step, dtype=None)
numpy.linspace(start, stop, num=50, endpoint=True, retstep=False, dtype=None)
eg.
np.arange(5)
array([0, 1, 2, 3, 4])

np.arange(5,11)
array([ 5, 6, 7, 8, 9, 10])

np.arange(5,11,2)
array([5, 7, 9])

np.arange(5.5,11,1.5)
array([ 5.5, 7. , 8.5, 10. ])

np.arange(3,15).reshape(3,4)
array([[ 3, 4, 5, 6],
[ 7, 8, 9, 10],
[11, 12, 13, 14]])

linspace() 函数需要3个参数:一个起点、一个终点,一个返回元素的个数。linspace() 返回的元素包括起点和终点,我们可以通过endpoint参数选择是否包含终点。
eg.
np.linspace(0, 4.5, 5) # 0到4.5之间返回5个等距数值(包括0和4.5)
array([0. , 1.125, 2.25 , 3.375, 4.5 ])

np.linspace(0,4.5,5,endpoint=False) # 0到4.5之间返回5个等距数值(包括0,但不包括4.5)
array([0. , 0.9, 1.8, 2.7, 3.6])

3. Create Complex Arrays

3.1重复构造法

  • 重复元素 np.repeat()
  • 重复数组 np.tile()
    eg.
    a=np.arange(5)
    a
    array([0, 1, 2, 3, 4])
    np.repeaty(a,3) #每个元素各重复3遍
    array([0, 0, 0, 1, 1, 1, 2, 2, 2, 3, 3, 3, 4, 4, 4])

np.tile(a,3) # 重复数组3次
array([0, 1, 2, 3, 4, 0, 1, 2, 3, 4, 0, 1, 2, 3, 4])

np.tile(a,(3,2)) # 重复数组3行2列
array([[0, 1, 2, 3, 4, 0, 1, 2, 3, 4],
[0, 1, 2, 3, 4, 0, 1, 2, 3, 4],
[0, 1, 2, 3, 4, 0, 1, 2, 3, 4]])

对多维数组:
np.arange(6).reshape((2,3))
a
array([[0, 1, 2],
[3, 4, 5]])
np.repeat(a,3)
array([0, 0, 0, 1, 1, 1, 2, 2, 2, 3, 3, 3, 4, 4, 4, 5, 5, 5])

np.repeat(a,3,axis=0)
array([[0, 1, 2],
[0, 1, 2],
[0, 1, 2],
[3, 4, 5],
[3, 4, 5],
[3, 4, 5]])

np.repeat(a,3,axis=1)
array([[0, 0, 0, 1, 1, 1, 2, 2, 2],
[3, 3, 3, 4, 4, 4, 5, 5, 5]])

np.tile(a,3)
array([[0, 1, 2, 0, 1, 2, 0, 1, 2],
[3, 4, 5, 3, 4, 5, 3, 4, 5]])

np.tile(a,(2,3))
array([[0, 1, 2, 0, 1, 2, 0, 1, 2],
[3, 4, 5, 3, 4, 5, 3, 4, 5],
[0, 1, 2, 0, 1, 2, 0, 1, 2],
[3, 4, 5, 3, 4, 5, 3, 4, 5]])

3.2网络构造法

用数组表示经纬度网格,一般有两种方式。第一种方式,用两个一维数组表示;第二种方式,用 np.meshgrid()生成两个二维数组。

  • 数组表示法:
    lon = np.linspace(-180,180,37) # 网格精度为10°,共计37个经度点
    lat = np.linspace(-90,90,19) # 网格精度为10°,共计19个纬度点
  • np.meshgrid()
    np.meshgrid() 以刚才的两个一维数组 lon 和 lat 为参数,生成的网格精度也是10°。
    lons, lats=np.meshgrid(lons, lats) #构造网格
    lons.shape
    (19, 37)
    lats.shape
    (19, 37)
  • np.mgrid()
    lats, lons = np.mgrid[-90:91:5., -180:181:5.] # 网格精度为5°,网格shape为(37,73)
    lons.shape, lats.shape
    ((37, 73), (37, 73))

lats, lons = np.mgrid[-90:90:37j, -180:180:73j] # 也可以用虚实指定分割点数,网格精度同样为5°
lons.shape, lats.shape
((37, 73), (37, 73))
画图:
lats, lons = np.mgrid[-90:91:5., -180:181:5.]
lons = np.radians(lons) # 度转弧度
lats = np.radians(lats) # 度转弧度
z = np.sin(lats) # 网格上所有点的z坐标
x = np.cos(lats)*np.cos(lons) # 网格上所有点的x坐标
y = np.cos(lats)*np.sin(lons) # 网格上所有点的y坐标
import matplotlib.pyplot as plt
import mpl_toolkits.mplot3d
ax = plt.subplot(111,projection='3d’)
ax.plot_surface(x,y,z,cmap=plt.cm.coolwarm,alpha=0.8)
plt.show()
StudyNotes-Numpy array