# numpy Numerical Python

# imread imshow

import matplotlib.pyplot as plt
cat=plt.imread("cat.jpg")
cat2=cat - 200
plt.imshow(cat2)
plt.show()

# shape

创建numpy.array(list无shape属性)

import numpy as np
n2=np.array([[1,23,4,5],[4,5,6,7],[6,7,8,9]])
# n2.shape (3,4) n2数组是3行4列

# numpy的类型

l = [3,1,4,5,9,6]
n = np.array(l)
display(n,l)
display(type(n),type(l))
array([3, 1, 4, 5, 9, 6])
[3, 1, 4, 5, 9, 6]
numpy.ndarray
list

# 使用np的routines函数创建

np.ones(shape,dtype,order)
np.zeros(shape,dtype,order)
np.full(shape,fill_value,dtype,order)
np.eye(N,M=None,k=0,dtype=float)
np.linspace(start,stop,num,endpoint=True,retstep=False,dtype=None)
np.arange([start,]stop,[step,]dtype=None)
np.random.randint(low,high=None,size=None,dtype="1")
np.random.randn(d0)
np.random.normal(loc=0,scale=1.0,size=None)
np.random.random(size=None)生成01的随机数,左闭右开
#线性
np.linspace(0,10,6,dtype=int)
# array([ 0,  2,  4,  6,  8, 10])

# 步长
np.arange(0,10,2,dtype=int)
# array([0, 2, 4, 6, 8])
 
# 随机
np.random.randint(0,150,size=5)
# array([146,  91, 115,  81,  79])

# 标准正太分布
np.random.randn(10)

# scale波动系数,越大越剧烈
np.random.normal(10,1,10)
#array([11.646244  ,  9.29981394,  8.88761907, 10.27297031,  9.95040353,
#        9.24070823, 10.32444857, 11.06972157, 10.26123253, 10.36532004])
        
#np.random.random(size=(2,3,3))   
#array([[[0.06618484, 0.96274796, 0.4167572 ],
#        [0.03267436, 0.25739268, 0.41684517],
#        [0.48272179, 0.93466897, 0.22049458]],
#
#       [[0.03243421, 0.93512471, 0.96669209],
#        [0.17708725, 0.78758772, 0.83752398],
#        [0.2127407 , 0.33376817, 0.0972154 ]]])

# ndarray

  • 索引多维数组时与js不同
n1=np.random.randint(0,100,(2,3,4))
n1[1,1,1]
#30
#array([[[83, 55, 40, 81],
#        [16, 35, 11, 36],
#        [80,  5, 48, 62]],
#
#       [[20, 96, 73, 87],
#        [71, 30,  0,  2],
#        [34, 62, 41, 72]]])
  • 反转数组
arr =np.arange(0,10,1)
arr[::-2]
# array([9, 7, 5, 3, 1])
  • 变形reshape函数参数是元组

xx.reshape((2,5))

  • np.concatenate()级联 axis改变维度

  • np.hstack() np.vstack() 水平和垂直级联

  • np.split np.hsplit np.vsplit

  • copy()

# 聚合操作

  • np.sum np.max() np.min()

# 矩阵操作

+ - x 、

# ndarray的排序

  • np.sort adarray.sort
  • np.partition(a,k)k为正,取小的k个数 k为负数 取最大的k个数
最后更新: 10/18/2019, 11:18:26 AM