• numpy学习


    NumPy是高性能科学计算和数据分析的基础包。

    读取文件

    world_alcohol.txt的文件,文件格式如下

    Year,WHO region,Country,Beverage Types,Display Value
    1986,Western Pacific,Viet Nam,Wine,0
    1986,Americas,Uruguay,Other,0.5
    1985,Africa,Cte d'Ivoire,Wine,1.62
    1986,Americas,Colombia,Beer,4.27
    1987,Americas,Saint Kitts and Nevis,Beer,1.98
    ……

    文件内容的含义:(这是一份全球的饮料消耗记录表,第一列的意思是记录的年份,第二列指的是饮料的出产地,第三列指的是饮料的消耗地,第四列指的是饮料的类型,第五列指的是饮料的每人平均消耗量)

    读取文件:

    genfromtxt()读取该文件,delimiter参数是用来指定每一行用来分隔数据的分隔符

    skip_header=1 表示略过第一行表头

    import numpy as np
    
    world_alcohol = np.genfromtxt("world_alcohol.txt", delimiter=",",skip_header=1)
    # 读取txt文件,使用逗号分隔,略过表头
    print(world_alcohol)

    读取到的内容如下:

    [[1.986e+03       nan       nan       nan 0.000e+00]
     [1.986e+03       nan       nan       nan 5.000e-01]
     [1.985e+03       nan       nan       nan 1.620e+00]
    ……

    这是因为numpy在读取元素时,默认是按照float格式来读取的,对于不能转换为float类型的数据会读取为nan(not a number),

    对于留空的数据则显示为na(not available),为了正确的读取数据,可以通过增加参数:

    1. dtype参数用来指定读取数据的格式,这里的U75表示将每一个数据都读取为75个byte的unicode数据格式

           NumPy函数和属性:

    类型 类型代码 说明
    int8、uint8 i1、u1 有符号和无符号8位整型(1字节)
    int16、uint16 i2、u2 有符号和无符号16位整型(2字节)
    int32、uint32 i4、u4 有符号和无符号32位整型(4字节)
    int64、uint64 i8、u8 有符号和无符号64位整型(8字节)
    float16 f2 半精度浮点数
    float32 f4、f 单精度浮点数
    float64 f8、d 双精度浮点数
    float128 f16、g 扩展精度浮点数
    string Sn 固定长度字符串,每个字符1字节,如S10
    unicode Un 固定长度Unicode,字节数由系统决定,如U10
    bool 布尔型
    import numpy as np
    
    world_alcohol = np.genfromtxt("world_alcohol.txt",dtype='U75',delimiter=",",skip_header=1)
    # 读取txt文件,使用逗号分隔,略过表头
    print(world_alcohol)

    读取结果

    [['1986' 'Western Pacific' 'Viet Nam' 'Wine' '0']
     ['1986' 'Americas' 'Uruguay' 'Other' '0.5']
     ['1985' 'Africa' "Cte d'Ivoire" 'Wine' '1.62']
     ...

    数组

    创建ndarray:np.array()

    ndarray是多维数组结构

    • 数组对象内的元素类型必须相同
    • 数组大小不可修改
    # 创建一个向量
    vector = np.array([10, 20, 30])
    # 创建一个矩阵
    matrix = np.array([[5,10,15],[20,25,30],[35,40,45]])
    print(vector)
    print(matrix)

    属性

    dtype:
    print(vector.dtype)  # 描述了元素的数据类型 int32
    shape
    print(matrix.shape)  # 描述了该数组的结构 (4, 3) 4行3列
    print(vector.shape)  # (3,)这是一个元组,表示vector变量是一个只有一行的向量,具有3个元素
    

     ndim

    print(matrix.ndim)  # 用于返回数组的维数,等于秩。2
    print(vector.ndim)  # 用于返回数组的维数,等于秩。1
    

     size

    print(matrix.size)  # 用于返回数组的元素个数 12
    print(vector.size)  # 用于返回数组的元素个数 3
    

     T

    print(matrix.T)  # 用于返回数组数组的转置
    # [[ 5 20 35 45]
    #  [10 25 40 50]
    #  [15 30 45 55]]
    

    索引和分片

    数组的索引是从0开始的

    print(matrix)
    # [[ 5 10 15]
    #  [20 25 30]
    #  [35 40 45]
    #  [45 50 55]]
    print(matrix[1,1])   # 这里索引的是第二行第二个 25
    
    print(matrix[:,0])  # 输出全部行,第一列的数据 [ 5 20 35 45]
    
    print(matrix[0,:])  # 输出第一行,全部列的数据 [ 5 10 15]
    
    print(matrix[:,0:2])  # 输出全部行,前2列的数据[  [5, 10],  [20, 25],  [35, 40], [45 50] ]
    
    print(matrix[1:3,:])  # 输出第2和第3行的全部列的数据 [  [20, 25, 30],  [35, 40, 45]  ]
    
    print(matrix[1:3,1])  # 输出第2,3行的第2列数据 [ [25],  [40] ]

      

    数组比较

    将数组与一个值相比较的时候,实际上是把数组内的每个值都与该值比较,然后返回一个布尔值列表

    print(vector == 30)  # 等于30 的值为True
    # [False False  True]
    print(matrix == 45)  # 等于45 的值为True
    # [[False False False]
    #  [False False False]
    #  [False False  True]
    #  [ True False False]]
    
    # 多种条件组合
    print((vector == 30)| (vector == 20))  # 等于30 或20的值为True
    # [False  True  True]
    print((vector < 30) & (vector > 10))  # 小于30 且大于10的值为True
    # [False  True  True]

    数组比较用处:

    一、选择数组或矩阵中的元素

    second_column_25 = (matrix[:, 1] == 25)
    
    print(matrix[second_column_25, :])  # 取出matrix中第二列中等于25的所有行,结果为[20, 25, 30]
    print(matrix[second_column_25, 0:2])  # 取出matrix中第二列中等于25的第一到二行,结果为[20, 25]

    二、替换元素

    vector = np.array([5, 10, 15, 20])
    
    vector_replace = (vector == 20) | (vector == 10)
    
    vector[vector_replace] = 50
    # 把等于20或10的值替换为50
    print(vector) # [ 5 50 15 50]
    # 将world_alcohol中的第五列中的留空的数据都替换为字符串0:
    is_value_empty = world_alcohol[:, 4] == ' '
    
    world_alcohol[is_value_empty, 4] = '0'

     常用方法

    一、数据类型转换

    vector = np.array(["1.1", "2", "3"])
    vector = vector.astype(float)
    print(vector)

    二、创建数组

    # numpy.zeros
    # 创建指定大小的数组,数组元素以0 来填充
    print(np.zeros(5))
    # [0. 0. 0. 0. 0.]
    print(np.zeros((2,2),dtype=int))
    # [[0 0],[0 0]]
    
    # numpy.ones
    # 创建指定大小的数组,数组元素以1来填充
    print(np.ones(5))
    # [1. 1. 1. 1. 1.]
    print(np.ones((2,2),dtype=int))
    # [[1 1],[1 1]]
    
    # numpy.empty
    # 创建指定大小的数组,数组元素为随机值
    print(np.empty(3))
    # [1.1 2.  3. ]
    print(np.empty((2,2),dtype=int))
    # [[994 0],[0 0]]
    
    print(np.arange( 0, 2, 0.3 )) # 创建以0开始,小于2,步长为0.3的向量
    # [0.  0.3 0.6 0.9 1.2 1.5 1.8]
    print(np.random.random((2,3)))  # 创建随机矩阵
    from numpy import pi
    print(np.linspace( 0, 2*pi, 10 ))
    # 返回在指定范围内的均匀间隔的数字(组成的数组),也即返回一个等差数列
    #start - 起始点,stop - 结束点 num - 元素个数,默认为50,
    # [0.  0.6981317  1.3962634  2.0943951  2.7925268  3.4906585 4.1887902  4.88692191 5.58505361 6.28318531]

    三、形状变换方法

    # numpy.reshape 函数可以在不改变数据的条件下修改形状
    a = np.arange(8)
    print('原始数组:')
    print(a)
    b = a.reshape(4, 2)
    print('修改后的数组:')
    print(b)
    
    # numpy.ndarray.flat 是一个数组元素迭代器
    a = np.arange(9).reshape(3, 3)
    print('原始数组:')
    for row in a:
        print(row)
    
    # 对数组中每个元素都进行处理,可以使用flat属性,该属性是一个数组元素迭代器:
    print('迭代后的数组:')
    for element in a.flat:
        print(element)
    
    
    # numpy.transpose 函数用于对换数组的维度
    a = np.arange(12).reshape(3, 4)
    print('原数组:')
    print(a)
    print('对换数组:')
    print(np.transpose(a))

    输出

    原始数组:
    [0 1 2 3 4 5 6 7]
    修改后的数组:
    [[0 1]
     [2 3]
     [4 5]
     [6 7]]
    原始数组:
    [0 1 2]
    [3 4 5]
    [6 7 8]
    迭代后的数组:
    0
    1
    2
    3
    4
    5
    6
    7
    8
    原数组:
    [[ 0  1  2  3]
     [ 4  5  6  7]
     [ 8  9 10 11]]
    对换数组:
    [[ 0  4  8]
     [ 1  5  9]
     [ 2  6 10]
     [ 3  7 11]]

     四、矩阵算法乘积

    # numpy.dot()
    # 对于两个一维的数组,计算的是这两个数组对应下标元素的乘积和(数学上称之为内积);
    # 对于二维数组,计算的是两个数组的矩阵乘积;
    import numpy as np
    
    a = np.array([1, 2])
    b = np.array([3, 4])
    print(np.dot(a, b))
    # 11 = 1*3+2*4
    a = np.array([[1, 2], [3, 4]])
    b = np.array([[11, 12], [13, 14]])
    print('原始数组:a')
    for row in a:
        print(row)
    print('原始数组:b')
    for row in b:
        print(row)
    print('乘积:')
    print(np.dot(a, b))
    # [[37 40]
    #  [85 92]]
    # =[[1*11+2*13, 1*12+2*14],[3*11+4*13, 3*12+4*14]]

    赋值与拷贝

    #Simple assignments make no copy of array objects or of their data.
    a = np.arange(12)
    b = a
    # a and b are two names for the same ndarray object
    b is a
    b.shape = 3,4
    print(a.shape)
    print(id(a))
    print(id(b))
    
    (3, 4)
    93762224
    93762224
    
    #The copy method makes a complete copy of the array and its data.
    d = a.copy() 
    d is a
    d[0,0] = 9999
    print(d)
    print(a)
    
    [[9999    1    2    3]
     [   4    5    6    7]
     [   8    9   10   11]]
    [[ 0  1  2  3]
     [ 4  5  6  7]
     [ 8  9 10 11]]

    常用函数及使用

    numpy.sqrt(array)                   平方根函数   
    numpy.exp(array)                    e^array[i]的数组
    numpy.abs/fabs(array)               计算绝对值
    numpy.square(array)                 计算各元素的平方 等于array**2
    numpy.log/log10/log2(array)         计算各元素的各种对数
    numpy.sign(array)                   计算各元素正负号
    numpy.isnan(array)                  计算各元素是否为NaN
    numpy.isinf(array)                  计算各元素是否为NaN
    numpy.cos/cosh/sin/sinh/tan/tanh(array) 三角函数
    numpy.modf(array)                   将array中值得整数和小数分离,作两个数组返回
    numpy.ceil(array)                   向上取整,也就是取比这个数大的整数 
    numpy.floor(array)                  向下取整,也就是取比这个数小的整数
    numpy.rint(array)                   四舍五入
    numpy.trunc(array)                  向0取整 
    numpy.cos(array)                       正弦值
    numpy.sin(array)                    余弦值 
    numpy.tan(array)                    正切值
    
    numpy.add(array1,array2)            元素级加法
    numpy.subtract(array1,array2)       元素级减法
    numpy.multiply(array1,array2)       元素级乘法
    numpy.divide(array1,array2)         元素级除法 array1./array2
    numpy.power(array1,array2)          元素级指数 array1.^array2
    numpy.maximum/minimum(array1,aray2) 元素级最大值
    numpy.fmax/fmin(array1,array2)      元素级最大值,忽略NaN
    numpy.mod(array1,array2)            元素级求模
    numpy.copysign(array1,array2)       将第二个数组中值得符号复制给第一个数组中值
    numpy.greater/greater_equal/less/less_equal/equal/not_equal (array1,array2)

     使用举例

    matrix = np.array([
                    [5, 10, 15],
                    [20, 25, 30],
                    [35, 40, 45]
                 ])
    print(matrix.sum(axis=1)) # axis=1 按行sum
    # [ 30  75 120]
    print(matrix.sum(axis=0)) # axis=0 按列sum
    # [60 75 90]
    # 如果axis=0,则沿着纵轴进行操作;axis=1,则沿着横轴进行操作
    
    B = np.arange(3)
    print(np.sqrt(B))
    # [0.         1.         1.41421356]
    
    #Return the floor of the input
    a = np.floor(10*np.random.random((3,4)))
    print(a)
    # [[7. 5. 6. 3.]
    #  [3. 2. 2. 6.]
    #  [4. 1. 1. 8.]]
    a.resize(2,6)
    print(a)
    # [[7. 5. 6. 3. 3. 2.]
    #  [2. 6. 4. 1. 1. 8.]]
    c = a.ravel()  # 拉长
    print(c)
    # [0. 7. 5. 5. 0. 6. 3. 5. 2. 0. 9. 0.]
    
    
    a = np.floor(10*np.random.random((2,2)))
    b = np.floor(10*np.random.random((2,2)))
    print(a)
    print('---')
    # [[7. 6.]
    #  [0. 4.]]
    # ---
    print(b)
    print('---')
    # [[0. 1.]
    #  [0. 0.]]
    # ---
    print(np.hstack((a,b)))  # 横向拼接
    # [[7. 6. 0. 1.]
    #  [0. 4. 0. 0.]]
    print(np.vstack((a,b)))  # 竖向拼接
    # [[7. 6.]
    #  [0. 4.]
    #  [0. 1.]
    #  [0. 0.]]
  • 相关阅读:
    php的基础知识(三)
    php的基础知识(二)
    css的基础用法(下)
    css的基础用法(上)
    Conceptual blockbusting--chap7 Kinds of blockbusters
    Conceptual blockbusting--chap6 Alternate thinking languages
    Conceptual blockbusting--chap5 Intellectual and Expressive blocks
    Conceptual blockbusting--chap4 Cultural and Environmental blocks
    Conceptual blockbusting
    Conceptual blockbusting- chap2 perceptual blocks
  • 原文地址:https://www.cnblogs.com/xiao-apple36/p/11103488.html
Copyright © 2020-2023  润新知