zoukankan      html  css  js  c++  java
  • numpy

    一、numpy 数组对象(numpy.ndarray)

    ndarray 是一个多维的数组类:

      实际数据

      描述信息

    创建对象、索引、切片:

     1 #python
     2 
     3 import numpy as np
     4 
     5 # 创建ndarray 对象
     6 a = np.arange(6)
     7 print(a.shape)
     8 print(a.dtype)
     9 type(a)
    10 
    11 b = np.array([1,1,2,4,5,6,0,7])
    12 
    13 c = np.array([np.arange(3),np.arange(3)])
    14 print(c.shape)
    15 print(c.dtype)
    16 
    17 d = np.array([[[1,2,3],[4,5,6]],[[7,8,9],[0,4,6]]] , dtype=np.float32)
    18 print(d.shape)
    19 print(d.dtype)
    20 
    21 e = np.zeros(5)
    22 print(e.shape)
    23 print(e.dtype)    #dtype('float64')
    24 
    25 f = np.ones([2,6],dtype=np.int64)
    26 print(f.shape)   #(2, 6)
    27 print(f.dtype)
    28 
    29 
    30 #---- 索引和切片
    31 a = np.arange(9)
    32 a[3:7]    # array([3, 4, 5, 6])    包含左边的索引,不包含右边的索引
    33 a[0:7:2]  #array([0, 2, 4, 6])    以2为步长
    34 a[7::-1]   #array([7, 6, 5, 4, 3, 2, 1, 0])  以-1为步长
    35 a[7:0:-1]  #array([7, 6, 5, 4, 3, 2, 1]) 
    36 
    37 b = np.array([[[1,2,3],[4,5,6]],[[7,8,9],[0,4,6]]])
    38 b[0,1:,:]
    View Code

    数据类型

      np.sctypeDict.keys()   查看完整的数据类型列表

      dtype.itemsize  属性可以查看占用数据类型字节数,f.dtype.itemsize

    二、ndarray一些常用的成员函数(reshape、ravel、flatten、transpose、resize)

    ravel 和 flatten:将数组展平, flatten 会申请内存保存结果,ravel 返回视图

    reshape 和 resize : 改变数组维度,resize 会直接修改所操作的数组

    transpose: 转置矩阵

     1 # python
     2 
     3 import numpy as np
     4 b = np.arange(24).reshape(2,3,4)
     5 print(b)
     6 
     7 print(b.flatten())
     8 
     9 b.shape = (6,4)  # 可以直接改变维度
    10 
    11 b.transpose()
    12 b.resize((2,12))
    13 
    14  
    View Code

    三、数组组合、分割

     1 import numpy as np
     2 
     3 # ----- 组合 np.concatenate 更加灵活
     4 a = np.arange(9).reshape(3,3)
     5 
     6 b = a**2
     7 
     8 # 水平组合
     9 c = np.hstack((a,b))
    10 c2 = np.concatenate((a,b),axis=1)
    11 
    12 # 垂直组合
    13 d = np.vstack((a,b))
    14 d2 = np.concatenate((a,b),axis=0)
    15 print(d2)
    16 
    17 # 深度组合
    18 e = np.dstack((a,b))
    19 
    20 #----- 分割 np.split() 更加灵活
    21 a = np.array([[1,4,6],[2,4,12],[3,9,22]])
    22 print(a)
    23 
    24 # 分割
    25 print( np.split(a,3,axis=0) )
    26 print( np.split(a,3,axis=1) )
    View Code

     

  • 相关阅读:
    [洛谷P1886]滑动窗口 (单调队列)(线段树)
    树状数组详细解析
    离散化
    kettle使用总结(一)
    springBoot开发的web项目打war包部署到已有的tomcat容器中
    集群时钟同步
    linux服务器安装nginx
    Tomcat学习之体系架构
    码云新建仓库上传项目
    linux系统安装mysql yum方式
  • 原文地址:https://www.cnblogs.com/feihu-h/p/11827509.html
Copyright © 2011-2022 走看看