当前位置 博文首页 > 文章内容

    Python NumPy使用

    作者: 栏目:未分类 时间:2020-07-20 14:00:14

    本站于2023年9月4日。收到“大连君*****咨询有限公司”通知
    说我们IIS7站长博客,有一篇博文用了他们的图片。
    要求我们给他们一张图片6000元。要不然法院告我们

    为避免不必要的麻烦,IIS7站长博客,全站内容图片下架、并积极应诉
    博文内容全部不再显示,请需要相关资讯的站长朋友到必应搜索。谢谢!

    另祝:版权碰瓷诈骗团伙,早日弃暗投明。

    相关新闻:借版权之名、行诈骗之实,周某因犯诈骗罪被判处有期徒刑十一年六个月

    叹!百花齐放的时代,渐行渐远!



    以下学习参考菜鸟教程https://www.runoob.com/numpy/numpy-advanced-indexing.html

    1、一维(多维)数组

    # -*- encoding=utf-8 -*-
    
    import numpy
    
    
    def f1():  # 一维数组
        print(numpy.array([1, 2, 3]))
        print(numpy.array(['1', '2', '3']))
        print(numpy.array(['a', 'b', 'c']))
    
    
    def f2():  # 二维数组
        print(numpy.array([[1, 2, 3], [4, 5, 6]]))
        print(numpy.array([[1, 2, 3], ['a', 'b', 'c']]))
    
    
    def f3():  # 指定最小维度
        print(numpy.array([1, 2, 3], ndmin=2))
    
    
    def f4():  # 指定数据类型
        print(numpy.array([1, 2, 3], dtype=complex))
    
    
    if __name__ == '__main__':
        pass
        f1()
        f2()
        f3()
        f4()

    运行

    [1 2 3]
    ['1' '2' '3']
    ['a' 'b' 'c']
    [[1 2 3]
     [4 5 6]]
    [['1' '2' '3']
     ['a' 'b' 'c']]
    [[1 2 3]]
    [1.+0.j 2.+0.j 3.+0.j]

    2、映射C语言中的结构体

    # -*- encoding=utf-8 -*-
    
    import numpy
    
    
    def f1():
        pass
        print(numpy.dtype(numpy.int8))  # 8位int型,即字节型
        print(numpy.dtype(numpy.int16))  # 16位int型
        print(numpy.dtype(numpy.int32))  # 32位int型
        print(numpy.dtype(numpy.int64))  # 64位int型
        print(numpy.dtype(numpy.int_))  # 32或64位int型
        print(numpy.dtype('i1'))  # 对应int8
        print(numpy.dtype('i2'))  # 对应int16
        print(numpy.dtype('i4'))  # 对应int32
        print(numpy.dtype('i8'))  # 对应int64
    
    
    def f2():
        dt = numpy.dtype([('age', numpy.int8)])  # 定义年龄age,类型是int8
        print(dt)
        data = numpy.array([[(10,), (20,), (30,)]], dtype=dt)  # 指定类型为age,int8型
        print(data)
        print(data['age'])  # 取出所有的age
        pass
    
    
    def f3():
        # 定义学生结构体,姓名name String 20,年龄age int8,分数grade int16
        stu = numpy.dtype([('name', 'S20'), ('age', numpy.int8), ('grade', numpy.int16)])
        # 添加三个学生数据
        data = numpy.array([('xiao', 20, 80), ('hong', 21, 88), ('lan', 20, 90)], dtype=stu)
        print(data)
        print(data['name'])
        print(data['age'])
        print(data['grade'])
        print(type(data['grade']))
        pass
    
    
    def f4():
        pass
    
    
    if __name__ == '__main__':
        pass
        f1()
        f2()
        f3()
        f4()

    运行

    int8
    int16
    int32
    int64
    int32
    int8
    int16
    int32
    int64
    [('age', 'i1')]
    [[(10,) (20,) (30,)]]
    [[10 20 30]]
    [(b'xiao', 20, 80) (b'hong', 21, 88) (b'lan', 20, 90)]
    [b'xiao' b'hong' b'lan']
    [20 21 20]
    [80 88 90]
    <class 'numpy.ndarray'>

    3、更改数组的行列数(例如2行3列变为3行二列,1行12列变为2行6列)

    # -*- encoding=utf-8 -*-
    
    import numpy
    
    
    def f1():
        pass
        a = numpy.array([[2, 3, 1], [4.5, 5, 1], [2, 3, 1]])
        print(a)
        print(a.ndim)  # 表示维度,例如二维数组
        print(a.shape)  # 返回数组的行和列,例如3行3列
    
    
    def f2():
        pass
        a = numpy.array([[2, 3, 1], [4.5, 5, 1]])
        print(a)
        print(a.ndim)  # 表示维度,
        print(a.shape)  # 原来是2行三列
        a.shape = (3, 2)  # 调整为3行两列
        print(a)
        print(a.shape)
        b = a.reshape(2, 3)  # 也可通过reshape调整
        print(b)
        print(b.shape)
    
    
    def f3():
        pass
        '''itemsize 以字节的形式返回数组中每一个元素的大小。
        例如,一个元素类型为 float64 的数组 itemsiz 属性值为 8
        (float64 占用 64 个 bits,每个字节长度为 8,所以 64/8,占用 8 个字节),
        又如,一个元素类型为 complex32 的数组 item 属性为 4(32/8)。'''
        # 数组的 dtype 为 int8(一个字节)
        x = numpy.array([1, 2, 3, 4, 5], dtype=numpy.int8)
        print(x.itemsize)
    
        # 数组的 dtype 现在为 float64(八个字节)
        y = numpy.array([1, 2, 3, 4, 5], dtype=numpy.float64)
        print(y.itemsize)
    
    
    def f4():
        pass
    
    
    if __name__ == '__main__':
        pass
        f1()
        f2()
        f3()
        f4()

    运行

    [[2.  3.  1. ]
     [4.5 5.  1. ]
     [2.  3.  1. ]]
    2
    (3, 3)
    [[2.  3.  1. ]
     [4.5 5.  1. ]]
    2
    (2, 3)
    [[2.  3. ]
     [1.  4.5]
     [5.  1. ]]
    (3, 2)
    [[2.  3.  1. ]
     [4.5 5.  1. ]]
    (2, 3)
    1
    8

    4、创建数组

    
    
    # -*- encoding=utf-8 -*-

    import numpy


    def f1():
    pass
    # 创建未初始化的数组
    print(numpy.empty(3)) # 默认浮点型,未初始化,所以用随机数填充
    # 使用arange创建
    print(numpy.arange(0, 10, 2, dtype=float))


    def f2():
    pass
    # 创建初始化为0的数组
    a = numpy.zeros(shape=[2, 2], dtype=int) # 创建2行2列的int型数组,
    print(a)
    b = numpy.zeros(shape=[2, 3],
    dtype=[('name', int), ('age', int), ('grade', int)]) # 创建2行3列的student型数组,
    print(b)
    # 创建初始化为1的数组
    a = numpy.ones(shape=[2, 2], dtype=int) # 创建2行2列的int型数组,
    print(a)
    b = numpy.ones(shape=[2, 3],
    dtype=[('name', int), ('age', int), ('grade', int)]) # 创建2行3列的student型数组,
    print(b)


    def f3():
    pass
    # 字符串转ndarray
    my_str = b'hello world1'
    a = numpy.frombuffer(my_str, dtype='S1')
    print(a)
    print(type(a))
    print(a.shape) # 转为3维数组
    a.shape = (3, 4)
    print(a)


    def f4():
    pass


    if __name__ == '__main__':
    pass
    f1()
    f2()
    f3()
    f4()
     

    运行

    [0. 0. 0.]
    [0. 2. 4. 6. 8.]
    [[0 0]
    [0 0]]
    [[(0, 0, 0) (0, 0, 0) (0, 0, 0)]
    [(0, 0, 0) (0, 0, 0) (0, 0, 0)]]
    [[1 1]
    [1 1]]
    [[(1, 1, 1) (1, 1, 1) (1, 1, 1)]
    [(1, 1, 1) (1, 1, 1) (1, 1, 1)]]
    [b'h' b'e' b'l' b'l' b'o' b' ' b'w' b'o' b'r' b'l' b'd' b'1']
    <class 'numpy.ndarray'>
    (12,)
    [[b'h' b'e' b'l' b'l']
    [b'o' b' ' b'w' b'o']
    [b'r' b'l' b'd' b'1']]

    5、等比,等差数列

    # -*- encoding=utf-8 -*-
    
    import numpy
    
    
    def f1():
        pass
        # 创建等差数列
        # linspace(start, stop, num=50, endpoint=True, retstep=False, dtype=None,axis=0)
        # 参数依次为起始值,终止值,需要的个数,是否包含终止值,是否显示间距,数据类型,
        a = numpy.linspace(1, 10, 5, )
        print(a)
        b = numpy.linspace(1, 10, 5, endpoint=False, retstep=True)  # 不包含终止值且显示步长
        print(b)
    
    
    def f2():
        pass
        # 等比数列,默认log底数为10,起始值和终止值为底数的次方
        a = numpy.logspace(1, 2, 5, dtype=int)  # 定义由10-100的5个等比(10**1至10**2)
        print(a)
        # 定义由2-2的十次方的5个等比,设置底数为2(2**1至2**10)
        a = numpy.logspace(1, 10, 5, dtype=int, base=2)
        print(a)
    
    
    def f3():
        pass
    
    
    def f4():
        pass
    
    
    if __name__ == '__main__':
        pass
        f1()
        f2()
        f3()
        f4()

    运行

    [ 1.    3.25  5.5   7.75 10.  ]
    (array([1. , 2.8, 4.6, 6.4, 8.2]), 1.8)
    [ 10  17  31  56 100]
    [   2    9   45  215 1024]

    6、切片(同string split一样)

    # -*- encoding=utf-8 -*-

    import numpy


    def f1():
    pass
    a = numpy.array([0, 1, 2, 3, 4])
    print(a[1:3]) # 切片和string spilt一样
    print(a[0:5:2]) # 步长为2,从0切到5


    def f2():
    pass
    a = numpy.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
    print(a)
    print(a.shape) # 3行3列
    print(a[1, ...]) # 切第二行
    print(a[1:]) # 第二行以及以后
    print(a[..., 1]) # 切第二列
    print(a[..., 1:]) # 切第二列以及以后


    def f3():
    pass
    a = numpy.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
    print(a[0, 0]) # 取0,0,
    print(a[[0, 0, 2], [1, 2, 2]]) # 取0,1和0,2和2,2
    print(a[[[0, 0], [2, 2]], [[0, 2], [0, 2]]]) # 0,0 0,2, 2,0, 2,2取四个角
    # 可以看做是前一个list元素+后一个list元素


    def f4():
    pass
    x = numpy.arange(32).reshape((8, 4))
    print(x)
    print(x[[4, 2, 1, 7]]) # 取1,2,4,7行
    print((x[x > 5])) # 取元素大于5的


    if __name__ == '__main__':
    pass
    f1()
    f2()
    f3()
    f4()

    运行

    [1 2]
    [0 2 4]
    [[1 2 3]
    [4 5 6]
    [7 8 9]]
    (3, 3)
    [4 5 6]
    [[4 5 6]
    [7 8 9]]
    [2 5 8]
    [[2 3]
    [5 6]
    [8 9]]
    1
    [2 3 9]
    [[1 3]
    [7 9]]
    [[ 0 1 2 3]
    [ 4 5 6 7]
    [ 8 9 10 11]
    [12 13 14 15]
    [16 17 18 19]
    [20 21 22 23]
    [24 25 26 27]
    [28 29 30 31]]
    [[16 17 18 19]
    [ 8 9 10 11]
    [ 4 5 6 7]
    [28 29 30 31]]
    [ 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
    30 31]

    7、还可计算方差,加权平均值,标准差等,需要可参考菜鸟教程