Numpy 数组入门

来源:互联网 发布:java int转date 编辑:程序博客网 时间:2024/06/06 07:14

一.ndarray数组

import numpy as py(引入模块的别名,即换个名字)

N维数组对象:ndarray


'''#计算A的平方  +  B的平方 ,其中A和B是一维数组                         
def pySum():
     a = [0,1,2,3,4]
     b = [9,8,7,6,5]
     c = []

     for i in range(len(a)):
          c.append(a[i]**2 + b[i]**3)

     return c

print(pySum())

结果    :  [729, 513, 347, 225, 141]

def npSum():
     a = np.array([0,1,2,3,4])
     b = np.array([9,8,7,6,5])

     c = a**2 + b**3   #可以数组对象可以去掉元素间所需循环,使一维向量更像单个数据,优化速度

     return c

print(npSum())

结果   : [729 513 347 225 141]


np.arry()生成一个ndarray数组(nnarray别名:array)
#ndarray对象的基本属性
.ndim    秩,及轴的数量或维度的数量
.shape   ndarray对象的尺度,对于矩阵,n行m列
.size    ndarray对象元素的个数,相当于.shape中n*m的值
.itemsize  ndarray对象中每个元素的大小,以字节为单位

import numpy as np

a = np.array([[0,1,2,3,4],[9,8,7,6,5]])

a.ndim
Out[6]: 2

a.shape
Out[7]: (2, 5)

a.size
Out[8]: 10

a.dtype
Out[9]: dtype('int32')  #取值32位的长度整数
a.itemsize
Out[10]: 4

二.ndarray数组创建
a = np.array(list/yuple)
np.arange(n)  类似range()函数,返回ndarray类型,元素从0到n-1
np.ones(shape) 根据shape生成一个全1数组,shape是元组类型
np.zeros(shape) 根据shape.........0....................
np.full(shape,val) ...........生成一个数组,每个元素都是val
np.eye(n)           创建一个正方n*n的单位矩阵,对角线为1,其余为0

np.arange(10)
Out[11]: array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])


np.ones((3,6))
Out[12]: 
array([[ 1.,  1.,  1.,  1.,  1.,  1.],
       [ 1.,  1.,  1.,  1.,  1.,  1.],
       [ 1.,  1.,  1.,  1.,  1.,  1.]])
np.zeros((3,6),dtype=np.int32)
Out[16]: 
array([[0, 0, 0, 0, 0, 0],
       [0, 0, 0, 0, 0, 0],
       [0, 0, 0, 0, 0, 0]])


np.eye(5)
Out[17]: 
array([[ 1.,  0.,  0.,  0.,  0.],
       [ 0.,  1.,  0.,  0.,  0.],
       [ 0.,  0.,  1.,  0.,  0.],
       [ 0.,  0.,  0.,  1.,  0.],
       [ 0.,  0.,  0.,  0.,  1.]])
x =np.ones((2,3,4))


print(x)
[[[ 1.  1.  1.  1.]
  [ 1.  1.  1.  1.]
  [ 1.  1.  1.  1.]]


 [[ 1.  1.  1.  1.]
  [ 1.  1.  1.  1.]
  [ 1.  1.  1.  1.]]]


x.shape
Out[22]: (2, 3, 4)


三.数组运算
实例计算:a与元素平均值的商(标量运算)
#实例计算:a与元素平均值的商

import numpy as np

a = np.arange(24).reshape((2,3,4))

a
Out[4]: 
array([[[ 0,  1,  2,  3],
        [ 4,  5,  6,  7],
        [ 8,  9, 10, 11]],


       [[12, 13, 14, 15],
        [16, 17, 18, 19],
        [20, 21, 22, 23]]])

a.mean()     #计算平均值
Out[5]: 11.5

a = a/a.mean()

a
Out[7]: 
array([[[ 0.        ,  0.08695652,  0.17391304,  0.26086957],
        [ 0.34782609,  0.43478261,  0.52173913,  0.60869565],
        [ 0.69565217,  0.7826087 ,  0.86956522,  0.95652174]],


       [[ 1.04347826,  1.13043478,  1.2173913 ,  1.30434783],
        [ 1.39130435,  1.47826087,  1.56521739,  1.65217391],
        [ 1.73913043,  1.82608696,  1.91304348,  2.        ]]])
np.abs(x)  和  np.fabs(x)        #计算各元素的绝对值
np.squarre(x)                         #计算各个元素的平方
np.ceil(x)   np.floor(x)       #计算个元素的ceiling值(不超过这个元素的整数值)或floor值(小于这个元素的最大整数值)
np.rint(x)                   #四舍五入
 np.modf(x)           #将各元素的小树和整数部分以两个独立数形式返回
#NumPy一元函数实例
a = np.arange(24).reshape((2,3,4))

np.square(a)
Out[10]: 
array([[[  0,   1,   4,   9],
        [ 16,  25,  36,  49],
        [ 64,  81, 100, 121]],


       [[144, 169, 196, 225],
        [256, 289, 324, 361],
        [400, 441, 484, 529]]], dtype=int32)

a = np.sqrt(a)

a
Out[12]: 
array([[[ 0.        ,  1.        ,  1.41421356,  1.73205081],
        [ 2.        ,  2.23606798,  2.44948974,  2.64575131],
        [ 2.82842712,  3.        ,  3.16227766,  3.31662479]],


       [[ 3.46410162,  3.60555128,  3.74165739,  3.87298335],
        [ 4.        ,  4.12310563,  4.24264069,  4.35889894],
        [ 4.47213595,  4.58257569,  4.69041576,  4.79583152]]])


np.modf(a)
Out[13]: 
(array([[[ 0.        ,  0.        ,  0.41421356,  0.73205081],
         [ 0.        ,  0.23606798,  0.44948974,  0.64575131],
         [ 0.82842712,  0.        ,  0.16227766,  0.31662479]],
 
        [[ 0.46410162,  0.60555128,  0.74165739,  0.87298335],
         [ 0.        ,  0.12310563,  0.24264069,  0.35889894],
         [ 0.47213595,  0.58257569,  0.69041576,  0.79583152]]]),
 array([[[ 0.,  1.,  1.,  1.],
         [ 2.,  2.,  2.,  2.],
         [ 2.,  3.,  3.,  3.]],
 
        [[ 3.,  3.,  3.,  3.],
         [ 4.,  4.,  4.,  4.],
         [ 4.,  4.,  4.,  4.]]]))

#注意数组是否被真实改变
#NumPy二元函数实例
a = np.arange(24).reshape((2,3,4))

b = np.sqrt(a)

a
Out[18]: 
array([[[ 0,  1,  2,  3],
        [ 4,  5,  6,  7],
        [ 8,  9, 10, 11]],


       [[12, 13, 14, 15],
        [16, 17, 18, 19],
        [20, 21, 22, 23]]])

b
Out[19]: 
array([[[ 0.        ,  1.        ,  1.41421356,  1.73205081],
        [ 2.        ,  2.23606798,  2.44948974,  2.64575131],
        [ 2.82842712,  3.        ,  3.16227766,  3.31662479]],


       [[ 3.46410162,  3.60555128,  3.74165739,  3.87298335],
        [ 4.        ,  4.12310563,  4.24264069,  4.35889894],
        [ 4.47213595,  4.58257569,  4.69041576,  4.79583152]]])

np.maximum(a,b)
Out[20]: 
array([[[  0.,   1.,   2.,   3.],
        [  4.,   5.,   6.,   7.],
        [  8.,   9.,  10.,  11.]],


       [[ 12.,  13.,  14.,  15.],
        [ 16.,  17.,  18.,  19.],
        [ 20.,  21.,  22.,  23.]]])

a > b
Out[21]: 
array([[[False, False,  True,  True],          #浮点数 > 整数
        [ True,  True,  True,  True],
        [ True,  True,  True,  True]],


       [[ True,  True,  True,  True],
        [ True,  True,  True,  True],
        [ True,  True,  True,  True]]], dtype=bool)
数组的索引和切片 与Python的基础相差不大

切片:

:     (单独一个冒号)相当于0:n:1,其中n为数组长度

m       和 m:n 相当于 m:n:1  

:n       0:n:1

::d     相当于0:n:d

线性切片 : flat 函数    对数组中每个元素都分配一个索引,并通过这个索引顺序来读取元素,形成一个一维数组.在二维数                      组或数列中,线性切片在工作中先按行从小到大开始访问,再按列从小到大开始访问  

a = array([[4,5,6],[7,8,9],[1,2,3]])

b = a.flat[ : ]

print b

[4,5,6,7,8,9,1,2,3]


队列与栈,列表也可以当作一个队列使用.队列与栈的区别主要在于队列从列表的一侧(如头部)添加数据,而从另一侧(如尾部)移除数据. deque类型

栈中元素采用后进先出的执行方法,可以用append() ,pop()实现栈的功能.


  • CSV文件(只能存取一维和二维数组)

np.savetxt(frame,array,fmt='%.18e',delimiter=None)

frame : 文件,字符串或产生器,可以是。gz或。bz2的压缩文件

fmt :写入的格式              delimiter : 分割字符串,默认为空格


np.loadtxt(frame,dtype=np.float,delimiter=None,unpack=False)

unpack : 如果True,读入属性将分别写入不同变量


  • 多维数组的存取

a.tofile(frame,sep='',format='%s')

sep : 数据分割字符串,如果是空串,写入文件为二进制

np.save(fname,array)或 np.savez(fname,array)  #以.npy为扩展名,压缩扩展名为.npz

np.load(fname)读取文件


  • 随机数组

sn = np.random.randn(3,4,5)

sn
Out[26]: 
array([[[-0.12241083, -0.52394628,  1.09553903,  1.87213847, -0.13358786],
        [-0.91843283, -1.80263793,  2.26122775,  0.63730007,  1.11279538],
        [-0.06576705,  0.00836529, -1.46299842,  0.69638254, -0.36406794],
        [-0.86383909, -0.52418818, -1.4299069 ,  0.90961197,  2.8088832 ]],


       [[ 1.22669186,  0.42892004, -1.75001861, -0.62423701,  0.58799862],
        [-0.09684481,  1.15564161, -0.84121368,  0.59125192, -1.82188369],
        [-1.03908402, -1.01983527, -0.20922319,  0.04587301, -0.45170951],
        [-0.89738236,  0.01276272, -1.42369456,  3.04221196,  0.99425362]],


       [[-0.43926186,  0.26754   ,  1.13553707, -0.6142006 ,  0.37579421],
        [-0.78116082, -0.51389238,  0.099022  , -0.48468705,  0.89259937],
        [-0.2864084 , -0.93720742,  0.67191002,  0.25211513,  0.52273129],
        [-0.08180043, -0.29751012, -1.93157978,  0.80518486,  0.64162913]]])

b = np.random.randint(100,200,(3,4))

b
Out[28]: 
array([[171, 117, 107, 100],
       [106, 166, 199, 144],
       [138, 189, 125, 176]])

np.random.seed(10)

np.random.randint(100,200,(3,4))
Out[30]: 
array([[109, 115, 164, 128],
       [189, 193, 129, 108],
       [173, 100, 140, 136]])

np.random.seed(10)

np.random.randint(100,200,(3,4))
Out[32]: 
array([[109, 115, 164, 128],
       [189, 193, 129, 108],
       [173, 100, 140, 136]])



  • shuffle(a)   根据数组a的第一轴进行随排列,改变数组x
  • permutation(a)     ........................乱序数组,不改变数组x
  • choice(a[,size,replace,p])          从一维数组a中以概率p抽取元素,形成size形状新数组replace表示是否可以重组元素,默认为Flase

b = np.random.randint(100,200,(3,4))

b
Out[28]: 
array([[171, 117, 107, 100],
       [106, 166, 199, 144],
       [138, 189, 125, 176]])

np.random.seed(10)

np.random.randint(100,200,(3,4))
Out[30]: 
array([[109, 115, 164, 128],
       [189, 193, 129, 108],
       [173, 100, 140, 136]])

np.random.seed(10)

np.random.randint(100,200,(3,4))
Out[32]: 
array([[109, 115, 164, 128],
       [189, 193, 129, 108],
       [173, 100, 140, 136]])

a = np.random.randint(100,200,(3,4))

a
Out[34]: 
array([[116, 111, 154, 188],
       [162, 133, 172, 178],
       [149, 151, 154, 177]])

np.random.shuffle(a)

a
Out[36]: 
array([[116, 111, 154, 188],
       [149, 151, 154, 177],
       [162, 133, 172, 178]])


#正态分布  抽取随机变量

u = np.random.uniform(0,10,(3,4))

u
Out[38]: 
array([[ 4.13667374,  7.78728808,  5.83901366,  1.82631436],
       [ 8.26082248,  1.05401833,  2.83576679,  0.65563266],
       [ 0.56444187,  7.65455818,  0.11788029,  6.11943341]])

n = np.random.normal(10,5,(3,4))

n
Out[40]: 
array([[ 13.39465597,   0.43222893,   5.28770972,   1.2722851 ],
       [  4.89527367,   9.18965487,   6.7101455 ,  12.11056531],
       [ 13.12011669,  12.50820048,  14.20717363,   1.79875008]])


还有梯度函数np.gradient()