zoukankan      html  css  js  c++  java
  • Python Numpy Array

    Numpy 是Python中数据科学中的核心组件,它给我们提供了多维度高性能数组对象。

    Arrays

    1. Numpy.array   dtype 变量

    dtype变量,用来存放数据类型, 创建数组时可以同时指定

    import numpy
    print ('生成指定元素类型的数组:设置dtype属性')
    x = numpy.array([1,2.6,3],dtype = numpy.int64)
    print (x) # 元素类型为int64 [1 2 3]
    print (x.dtype) # int64
    x = numpy.array([1,2,3],dtype = numpy.float64)
    print (x) # 元素类型为float64 [1. 2. 3.]
    print (x.dtype)  float64
    
    print ('使用astype复制数组,并转换类型')
    x = numpy.array([1,2.6,3],dtype = numpy.float64)
    y = x.astype(numpy.int32)
    print (y) # [1 2 3] 
    print (x) # [ 1.   2.6  3. ]
    z = y.astype(numpy.float64)
    print (z) # [ 1.  2.  3.]
    
    print ('将字符串元素转换为数值元素')
    x = numpy.array(['1','2','3'],dtype = numpy.string_)
    y = x.astype(numpy.int32)
    print (x) # ['1' '2' '3']  #[b'1' b'2' b'3']
    print (y) # [1 2 3] 若转换失败会抛出异常
    
    print ('使用其他数组的数据类型作为参数')
    x = numpy.array([ 1., 2.6,3. ],dtype = numpy.float32)
    y = numpy.arange(3,dtype=numpy.int32)
    print (y) # [0 1 2]
    print (y.astype(x.dtype)) # [ 0.  1.  2.]
    print ('不带类型的数据') 若有精度不同的,会自动升级
    a = numpy.array([ 1, 2.6,3 ])
    print(a) # [1.  2.6 3. ]
    print ('不带类型的数据')  这里的数值自动识别为string
    a = numpy.array([ 1, 2.6,'3' ])
    print(a) # ['1' '2.6' '3']

    2.Numpy.array   shape变量, reshape 变量

       shape 是显示当前矩阵行列数(维度), reshap 是根据参数改变矩阵的布局。

    import numpy as np
    ex = np.arange(0,12,1) 
    print(ex)
    # 括号里的0可以省略,也可以换成其他起始数,1是步长。运行上述代码,我们
    # 发现ex只是一个序列并没有维数(形状)上的特征 
    #[ 0  1  2  3  4  5  6  7  8  9 10 11]
    
    # 接下来我们用reshape来更改数组的形状
    ex1 = np.arange(12).reshape(1,12) # 1是行数,2是列数
    print('reshape')
    print (ex1)
    ex2 = np.arange(12).reshape((1,12)) # 形状以数组形式传入
    print('reshape')
    print (ex2)
    ex3 = np.arange(12).reshape(1,-1) 
    print('reshape')
    print (ex3)
    # -1代表依据前面已经给定的行数来确定列数
    
    #b= array([[ 0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11]]) 
    # ex1,ex2,ex3 出来的数组相同,如上所示,跟ex区别的地方在于多了一个
    # 中括号,所以ex1有了形状,像是1*12的矩阵。当然要真正变成矩阵还需要
    # np.mat()函数
    #
    ex4 = ex.reshape(3, 4) # or ex4=ex.reshape(3,-1)
    print(ex4)
    print(ex4.shape)

    还可以用shape去改变形状

    import numpy as np
    ex = np.arange(0,12,1) 
    print('原来数据')
    print(ex)
    ex.shape = 3,4
    print('改变形状后的数据')
    print(ex)
    #原来数据
    #[ 0  1  2  3  4  5  6  7  8  9 10 11]
    #改变形状后的数据
    #[[ 0  1  2  3]
    # [ 4  5  6  7]
    # [ 8  9 10 11]]

    3. numpy.array的矢量化计算

    矢量(向量)运算: 相同大小的数组键间的运算应用在元素上

    矢量和标量运算:广播- 将标量广播到各个矢量元素

    import numpy 
    print ('array数组与标量/数组的运算')
    x = numpy.array([1,2,3]) 
    print (x*2) # [2 4 6]
    print ('array矢量和标量的运算')
    print (x>2) # [False False  True]
    y = numpy.array([3,4,5])
    print (x+y) # [4 6 8]
    print ('array矢量和矢量的运算')
    print (x>y) # [False False False]
    
    #array数组与标量/数组的运算
    #[2 4 6]
    #array矢量和标量的运算
    #[False False  True]
    #[4 6 8]
    #array矢量和矢量的运算
    #[False False False]

    4. 数组的index 和slicer

    如果是一维的,与python list 差不多,可以做参考

    index:

    import numpy 
    print ('array基本索引')
    a = numpy.arange(6)
    a.shape=(3,2)
    print(a)
    #[[0 1]
    # [2 3]
    # [4 5]]
    #
    print (a[0])#和普通数组一样,指向第一行数据
    #[0 1]
    print (a[:,0])#和普通数组一样,指向第一列数据,注意巧用:冒号
    #[0 2 4]
    print (a[0,0])#和普通数组一样,指向第一行第一列数据
    #0
    #下面展示一个三维的例子
    print('#下面展示一个三维的例子')
    b = numpy.arange(8)
    print(b)
    # [0 1 2 3 4 5 6 7]
    b.shape=(2,2,2)
    print(b)
    #[[[0 1]
    #  [2 3]]
    #
    # [[4 5]
    #  [6 7]]]
    print(b[0])
    #[[[0 1]
    #  [2 3]]
    # 用copy方法生成一个副本,这样不至于影响元数据,项目中经常用
    c = b[0].copy()
    print(c) 
    #[[[0 1]
    #  [2 3]]

    slicer(切片)

    import numpy 
    print ('ndarray的切片')
    print ('一维')
    x = numpy.array([1,2,3,4,5])
    print (x[1:3]) # [2,3] 右边开区间
    print (x[:3]) # [1,2,3] 左边默认为 0
    print (x[1:]) # [2,3,4,5] 右边默认为元素个数
    print (x[0:4:2]) # [1,3] 下标递增2
    print ('二维')
    x = numpy.array([[1,2],[3,4],[5,6]])
    print(x)
    print (x[:2]) # [[1 2],[3 4]] 左边从0右边到1因为右边开区间
    print (x[:2,:1]) # [[1],[3]] 就是对上面结果[:1]就是像是x[0]   Note:此处理解起来有点困难
    # x[:2] 结果[[1 2],[3 4]] 如果我们把这个结果作为C 那么第二步c[:1] 就会拿到[[1],[3]] 希望可以帮助理解
    x[:2,:1] = 0 # 用标量赋值
    print (x) # [[0,2],[0,4],[5,6]]
    x[:2,:1] = [[8],[6]] # 用数组赋值
    print (x) # [[8,2],[6,4],[5,6]

     布尔类型index

    import numpy 
    print ('ndarray的布尔型索引')
    x = numpy.array([3,2,3,1,3,0])
    # 布尔型数组的长度必须跟被索引的轴长度一致
    y = numpy.array([True,False,True,False,True,False]) 
    print (x[y]) # [3,3,3] 
    print (x[y==False]) # [2,1,0]
    print (x>=3) # [ True False  True False  True  False]
    print (x[(x>=3)]) # [3 3 3]
    print (x[~(x>=3)]) # [2,1,0]
    print ((x==2)|(x==1)) # [False  True False  True False False]
    print (x[(x==2)|(x==1)]) # [2 1]
    x[(x==2)|(x==1)] = 0
    print (x) # [3 0 3 0 3 0]

     其他

    import numpy 
    print ('ndarray的花式索引:使用整型数组作为索引')
    x = numpy.array([1,2,3,4,5,6])
    print (x[[0,1,2]]) # [1 2 3]
    print (x[[-1,-2,-3]]) # [6,5,4]
    x = numpy.array([[1,2],[3,4],[5,6]])
    print (x[[0,1]]) # [[1,2],[3,4]]
    print (x[[0,1],[0,1]]) # [1,4] 打印x[0][0]和x[1][1]
    print (x[[0,1]][:,[0,1]]) # 打印01行的01列 [[1,2],[3,4]]
    # 使用numpy.ix_()函数增强可读性
    print (x[numpy.ix_([0,1],[0,1])]) #同上 打印01行的01列 [[1,2],[3,4]]
    x[[0,1],[0,1]] = [0,0]
    print (x) # [[0,2],[3,0],[5,6]]

    矩阵的转置和轴变化

    import numpy 
    print ('array数组的转置和轴对换')
    k = numpy.arange(9) #[0,1,....8]
    m = k.reshape((3,3)) # 改变数组的shape复制生成2维的,每个维度长度为3的数组
    print (k) # [0 1 2 3 4 5 6 7 8]
    print (m) # [[0 1 2] [3 4 5] [6 7 8]]
    # 转置(矩阵)数组:T属性 : mT[x][y] = m[y][x]
    print (m.T) # [[0 3 6] [1 4 7] [2 5 8]]
    # 计算矩阵的内积 xTx
    print (numpy.dot(m,m.T)) # numpy.dot点乘
    # 高维数组的轴对象
    k = numpy.arange(8).reshape(2,2,2)
    print (k) # [[[0 1],[2 3]],[[4 5],[6 7]]]
    print (k[1][0][0]) #4
    # 轴变换 transpose 参数:由轴编号组成的元组
    m = k.transpose((1,0,2)) # m[y][x][z] = k[x][y][z]
    print (m) # [[[0 1],[4 5]],[[2 3],[6 7]]]
    print (m[0][1][0])
    # 轴交换 swapaxes (axes:轴),参数:一对轴编号
    m = k.swapaxes(0,1) # 将第一个轴和第二个轴交换 m[y][x][z] = k[x][y][z]
    print (m) # [[[0 1],[4 5]],[[2 3],[6 7]]]
    print (m[0][1][0])
    # 使用轴交换进行数组矩阵转置
    m = numpy.arange(9).reshape((3,3))
    print (m) # [[0 1 2] [3 4 5] [6 7 8]]
    print (m.swapaxes(1,0)) # [[0 3 6] [1 4 7] [2 5 8]]

    Where 条件

    import numpy 
    print ('where函数的使用')
    cond = numpy.array([True,False,True,False])
    x = numpy.where(cond,-2,2)
    print (x) # [-2  2 -2  2]
    cond = numpy.array([1,2,3,4])
    x = numpy.where(cond>2,-2,2)
    print (x) # [ 2  2 -2 -2]
    y1 = numpy.array([-1,-2,-3,-4])
    y2 = numpy.array([1,2,3,4])
    x = numpy.where(cond>2,y1,y2) # 长度须匹配
    print (x) # [1,2,-3,-4]
    
    print ('where函数的嵌套使用')
    y1 = numpy.array([-1,-2,-3,-4,-5,-6])
    y2 = numpy.array([1,2,3,4,5,6])
    y3 = numpy.zeros(6)
    cond = numpy.array([1,2,3,4,5,6])
    x = numpy.where(cond>5,y3,numpy.where(cond>2,y1,y2))
    print (x) # [ 1.  2. -3. -4. -5.  0.]

    Array 的计算函数

    import numpy 
    print ('numpy的基本统计方法')
    x = numpy.array([[1,2],[3,3],[1,2]]) #同一维度上的数组长度须一致
    print (x.mean()) # 2
    print (x.mean(axis=1)) # 对每一行的元素求平均 这个要注意
    print (x.mean(axis=0)) # 对每一列的元素求平均
    print (x.sum()) #同理 12
    print (x.sum(axis=1)) # [3 6 3]
    print (x.max()) # 3
    print (x.max(axis=1)) # [2 3 2]
    print (x.cumsum()) # [ 1  3  6  9 10 12] 所有元素的累加和
    print (x.cumprod()) # [ 1  2  6 18 18 36] 所有元素的累加积

    sum: 统计数组某个维度中的True的个数

    any: 统计数组某个维度是否存在一个或者多个True

    all: 统计数组中某个维度是否都是True

    Array 排序

    import numpy 
    print ('.sort的就地排序')
    x = numpy.array([[1,6,2],[6,1,3],[1,5,2]])
    x.sort(axis=1) 
    print (x) # [[1 2 6] [1 3 6] [1 2 5]]
    #非就地排序:numpy.sort()可产生数组的副本

    Array 的去重和集合计算

    import numpy 
    print ('array的唯一化和集合运算')
    x = numpy.array([[1,6,2],[6,1,3],[1,5,2]])
    print (numpy.unique(x)) # [1,2,3,5,6]
    y = numpy.array([1,6,5])
    print (numpy.in1d(x,y)) # [ True  True False  True  True False  True  True False]
    print (numpy.setdiff1d(x,y)) # [2 3]
    print (numpy.intersect1d(x,y)) # [1 5 6]

    Array 的线性代数操作

    import numpy
    import numpy.linalg as nla
    print ('矩阵点乘')
    x = numpy.array([[1,2],[3,4]])
    y = numpy.array([[1,3],[2,4]])
    print (x.dot(y)) # [[ 5 11][11 25]]
    print (numpy.dot(x,y)) # # [[ 5 11][11 25]]
    print ('矩阵求逆')
    x = numpy.array([[1,1],[1,2]])
    y = nla.inv(x) # 矩阵求逆(若矩阵的逆存在)
    print (x.dot(y)) # 单位矩阵 [[ 1.  0.][ 0.  1.]]
    print (nla.det(x)) # 求行列式

    array 的split  merge 拆分和合并

    import numpy
    print ('数组的合并与拆分')
    x = numpy.array([[1, 2, 3], [4, 5, 6]])
    y = numpy.array([[7, 8, 9], [10, 11, 12]])
    print (numpy.concatenate([x, y], axis = 0))  
    # 竖直组合 [[ 1  2  3][ 4  5  6][ 7  8  9][10 11 12]]
    print (numpy.concatenate([x, y], axis = 1))  
    # 水平组合 [[ 1  2  3  7  8  9][ 4  5  6 10 11 12]]
    print ('垂直stack与水平stack')
    print (numpy.vstack((x, y))) # 垂直堆叠:相对于垂直组合
    print (numpy.hstack((x, y))) # 水平堆叠:相对于水平组合
    # dstack:按深度堆叠
    print (numpy.split(x,2,axis=0)) 
    # 按行分割 [array([[1, 2, 3]]), array([[4, 5, 6]])]
    print (numpy.split(x,3,axis=1)) 
    # 按列分割 [array([[1],[4]]), array([[2],[5]]), array([[3],[6]])]
    # 堆叠辅助类
    import numpy as np
    arr = np.arange(6)
    arr1 = arr.reshape((3, 2))
    arr2 = np.random.randn(3, 2)
    print ('r_用于按行堆叠')
    print (np.r_[arr1, arr2])
    #'''
    #[[ 0.          1.        ]
    # [ 2.          3.        ]
    # [ 4.          5.        ]
    # [ 0.22621904  0.39719794]
    # [-1.2201912  -0.23623549]
    # [-0.83229114 -0.72678578]]
    #'''
    print ('c_用于按列堆叠')
    print (np.c_[np.r_[arr1, arr2], arr])
    #'''
    #[[ 0.          1.          0.        ]
    # [ 2.          3.          1.        ]
    # [ 4.          5.          2.        ]
    # [ 0.22621904  0.39719794  3.        ]
    # [-1.2201912  -0.23623549  4.        ]
    # [-0.83229114 -0.72678578  5.        ]]
    #'''
    print ('切片直接转为数组')
    print (np.c_[1:6, -10:-5])

    Array repeat 和title

    # 堆叠辅助类
    import numpy
    print ('数组的元素重复操作')
    x = numpy.array([[1,2],[3,4]])
    print (x.repeat(2)) # 按元素重复 [1 1 2 2 3 3 4 4]
    print (x.repeat(2,axis=0)) # 按行重复 [[1 2][1 2][3 4][3 4]]
    print (x.repeat(2,axis=1)) # 按列重复 [[1 1 2 2][3 3 4 4]]
    x = numpy.array([1,2])
    print (numpy.tile(x,2)) # tile瓦片:[1 2 1 2]
    print (numpy.tile(x, (2, 2)))  # 指定从低维到高维依次复制的次数。 
    # [[1 2 1 2][1 2 1 2]]
  • 相关阅读:
    iOS
    iOS
    iOS
    CS页面-Asp.net+Spring.Net.Framework--SNF快速开发平台3.0
    SNF快速开发平台3.0之-界面个性化配置+10种皮肤+7种菜单-Asp.net+MVC4.0+WebAPI+EasyUI+Knockout
    SNF快速开发平台3.0之BS页面展示和九大优点-部分页面显示效果-Asp.net+MVC4.0+WebAPI+EasyUI+Knockout
    MVC通用控件库展示-MVC4.0+WebAPI+EasyUI+Knockout--SNF快速开发平台3.0
    已有打开的与此 Command 相关联的 DataReader,必须首先将它关闭。
    转:ECharts图表组件之简单关系图:如何轻松实现另类站点地图且扩展节点属性实现点击节点页面跳转
    转:zTree树控件入门之checkbox:如何动态设置节点的checkbox选择框启用与禁用状态(chkDisabled)
  • 原文地址:https://www.cnblogs.com/Jesse-Li/p/8782376.html
Copyright © 2011-2022 走看看