Python之Numpy操作基础

本文主要介绍了Python的NumPy库的基础操作,包括创建ndarray数组、指定元素类型、矢量化计算、索引与切片、转置、通用函数、统计方法、线性代数、随机数生成、数组重塑、拆分合并等核心概念。
摘要由CSDN通过智能技术生成

NumPy(Numerical Python) 是 Python 语言的一个扩展程序库,支持大量的维度数组与矩阵运算,此外也针对数组运算提供大量的数学函数库。
NumPy 的前身 Numeric 最早是由 Jim Hugunin 与其它协作者共同开发,2005 年,Travis Oliphant 在 Numeric 中结合了另一个同性质的程序库 Numarray 的特色,并加入了其它扩展而开发了 NumPy。NumPy 为开放源代码并且由许多协作者共同维护开发。 注:以上是题外话,方便进入主题,本文重在基础的操作。

一、总述:
NumPy的基础,方便查阅。

二、创建ndarray数组:

    # -*- coding:utf-8 -*-
    # author:
    import numpy
    data = [1,2,3,4,5,6]
    x = numpy.array(data)#列表生成一维数组
    print(x)#打印数组
    print(x.dtype)#打印数组元素的类型
    data = [[1,2],[3,4],[5,6]]
    x = numpy.array(data)#列表生成二维数组
                                      
                                       我这里还整理了更多有关Python的学习资料
                                          
                                          在这里也不好一一放出
                                            
                                             QQ 688244617
                                             
                                             自己来拿,免费
                                        
                                        还有很多小伙伴跟你一起学习


    print(x )#打印数组
    print(x.ndim )#打印数组的维度
    print(x.shape) #打印数组各个维度的长度。shape是一个元组
    x = numpy.zeros(6) #创建一维长度为6的,元素都是0一维数组
    x = numpy.zeros((2,3)) #创建一维长度为2,二维长度为3的二维0数组
    x = numpy.ones((2,3)) #创建一维长度为2,二维长度为3的二维1数组
    x = numpy.empty((3,3)) #创建一维长度为2,二维长度为3,未初始化的二维数组
    print(numpy.arange(6)) # [0,1,2,3,4,5,] 开区间生成连续元素

print(numpy.arange(0,6,2) ) # [0, 2,4]生成连续元素

三、指定ndarray数组元素的类型:

    # -*- coding:utf-8 -*-
    # author:
    import numpy
    x = numpy.array([1,2.6,3],dtype = numpy.int64)#生成指定元素类型的数组:设置dtype属性
    x = numpy.array([1,2,3],dtype = numpy.float64)
    print(x )# 元素类型为float64
    print(x.dtype)
    x = numpy.array([1,2.6,3],dtype = numpy.float64)#使用astype复制数组,并转换类型
    y = x.astype(numpy.int32)
    z = y.astype(numpy.float64)
    x = numpy.array(['1','2','3'],dtype = numpy.string_)#将字符串元素转换为数值元素
    y = x.astype(numpy.int32)
    x = numpy.array([ 1., 2.6,3. ],dtype = numpy.float32)#使用其他数组的数据类型作为参数
    y = numpy.arange(3,dtype=numpy.int32)
    print(y)
    print(y.astype(x.dtype))

四、ndarray的矢量化计算:

    # -*- coding:utf-8 -*-
    # author:
    import numpy
    '''ndarray数组与标量/数组的运算'''
    x = numpy.array([1,2,3])
    print(x*2)
    print(x>2)
    y = numpy.array([3,4,5])
    print(x+y)
    print(x>y)

五、ndarray数组的基本索引和切片:

    # -*- coding:utf-8 -*-
    # author:
    import numpy
    '''ndarray的基本索引'''
    x = numpy.array([[1,2],[3,4],[5,6]])
    print(x[0]) # [1,2]
    print(x[0][1]) # 2,普通python数组的索引
    print(x[0,1]) # 同x[0][1],ndarray数组的索引
    x = numpy.array([[[1, 2], [3,4]], [[5, 6], [7,8]]])
    print(x[0]) # [[1 2],[3 4]]
    y = x[0].copy() # 生成一个副本
    z = x[0] # 未生成一个副本
    print(y) #  [[1 2],[3 4]]
    print(y[0,0] )# 1
    y[0,0] = 0 
    z[0,0] = -1
    print(y )# [[0 2],[3 4]]
    print(x[0]) # [[-1 2],[3 4]]
    print(z) # [[-1 2],[3 4]]
    '''ndarray的切片'''
    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
    x = numpy.array([[1,2],[3,4],[5,6]])
    print(x[:2] )# [[1 2],[3 4]]
    print(x[:2,: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]]

六、ndarray数组的布尔索引和其他索引:

    # -*- coding:utf-8 -*-
    # author:
    import numpy
    '''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)]) # [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]

七、ndarray数组的转置和轴对换:

    # -*- coding:utf-8 -*-
    # author:
    import numpy
    '''ndarray数组的转置和轴对换'''
    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])
    # 轴变换 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]]

八、ndarray通用函数:

在这里插入图片描述

九、NumPy的where函数使用:

    # -*- coding:utf-8 -*-
    # author:
    import numpy
    '''where函数的使用'''
    cond = numpy.array([True,False,True,False])
    x = numpy.where(cond,-2,2)
                                 我这里还整理了更多有关Python的学习资料
                                          
                                          在这里也不好一一放出
                                            
                                             QQ 688244617
                                             
                                             自己来拿,免费
                                        
                                        还有很多小伙伴跟你一起学习
    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]
     
    '''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.]

十、ndarray常用的统计方法:
在这里插入图片描述

十一、ndarray数组的去重以及集合运算:

    # -*- coding:utf-8 -*-
    # author:
    import numpy
    '''ndarray的唯一化和集合运算'''
    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]

十二、numpy中的线性代数:

在这里插入图片描述
十三、numpy中的随机数生成:

    # -*- coding:utf-8 -*-
    # author:
    import numpy as np
    a=np.random.randint(0,10,100)#范围内的整数
    print(a)
    b=np.random.rand(40)#0到1的均匀分布
    print(b)
    c=np.random.randn(10)#标准正态分布
    print(c)
    d=np.random.normal(0,1,100)#生成指定正态分布
    print(d)
    e=np.random.random(20)#0到1的均匀分布
    print(e)
    f=np.random.ranf(20)#0到1的均匀分布
    print(f)
    g=np.random.uniform(-1,1,100)#指定均匀分布
    print(g)

十四、ndarray数组重塑:

    # -*- coding:utf-8 -*-
    # author:
    import numpy
    '''ndarray数组重塑'''
    x = numpy.arange(0,6) #[0 1 2 3 4]
    print(x) #[0 1 2 3 4]
    print(x.reshape((2,3))) #) [[0 1 2][3 4 5]]
    print(x )#[0 1 2 3 4]
    print(x.reshape((2,3)).reshape((3,2))) # [[0 1][2 3][4 5]]
    y = numpy.array([[1,1,1],[1,1,1]])
    x = x.reshape(y.shape)
    print(x )# [[0 1 2][3 4 5]]
    print(x.flatten() )# [0 1 2 3 4 5]
    x.flatten()[0] = -1 # flatten返回的是拷贝
    print(x )# [[0 1 2][3 4 5]]
    print(x.ravel()) # [0 1 2 3 4 5]
    x.ravel()[0] = -1 # ravel返回的是视图(引用) 
    print(x) # [[-1 1 2][3 4 5]]
    '''"维度大小自动推导"'''
    arr = numpy.arange(15)
    print(arr.reshape((5, -1))) # 15 / 5 = 3

十五、ndarray数组的拆分与合并:

在这里插入图片描述
十六、数组的元素重复操作:
在这里插入图片描述

    # -*- coding:utf-8 -*-
    # author:
    import numpy
    '''数组的元素重复操作'''
    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]]

参考:
NumPy 官网 http://www.numpy.org/
NumPy 源代码:https://github.com/numpy/numpy
SciPy 官网:https://www.scipy.org/
SciPy 源代码:https://github.com/scipy/scipy
Matplotlib 官网:https://matplotlib.org/
Matplotlib 源代码:https://github.com/matplotlib/matplotlib
https://blog.csdn.net/cxmscb/article/details/54583415
---------------------

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值