zoukankan      html  css  js  c++  java
  • 数据分析学习02-numpy

    简介

    NumPy是Python中科学计算的基础包。它是一个Python库,提供多维数组对象,各种派生对象(如掩码数组和矩阵),以及用于数组快速操作的各种API,有包括数学、逻辑、形状操作、排序、选择、输入输出、离散傅立叶变换、基本线性代数,基本统计运算和随机模拟等等。

    使用

    我们仅需要简单的通过import numpy as np就可以使用numpy了。

    为什么要用numpy?

    如果我们希望两个列表对应项相加,则我们需要这样做,使用Python列表这样的代码是冗余的,而使用numpy则大大减少了代码的冗余。

    基本操作

    数组的形状

    import numpy as np
    
    t1 = np.arange(12) #生成数组
    print(t1)
    # [ 0  1  2  3  4  5  6  7  8  9 10 11]
    
    print(t1.shape) # 查看数组的形状
    # (12,) # 表示12个数
    
    t2 = np.array([[1,2,3],[4,5,6]])
    print(t2)
    # [[1 2 3]
    #  [4 5 6]]
    
    print(t2.shape)# 查看数组的形状
    # (2, 3) 表示2行3列
    
    t3 = np.array([[[1,2,3],[4,5,6]],[[7,8,9],[10,11,12]]])
    print(t3)
    # [[[ 1  2  3]
    #   [ 4  5  6]]
    #
    #  [[ 7  8  9]
    #   [10 11 12]]]
    print(t3.shape) # 查看数组的形状
    # (2, 2, 3)
    
    
    import numpy as np
    
    t4 = np.arange(12)
    print(t4)
    # [ 0  1  2  3  4  5  6  7  8  9 10 11]
    
    print(t4.reshape((3,4))) # 把t4 变成3行4列
    # [[ 0  1  2  3]
    #  [ 4  5  6  7]
    #  [ 8  9 10 11]]
    
    import numpy as np
    
    t5 = np.arange(24).reshape((2,3,4))
                        # 2块 每块3行4列
    print(t5)
    # [[[ 0  1  2  3]
    #   [ 4  5  6  7]
    #   [ 8  9 10 11]]
    #
    #  [[12 13 14 15]
    #   [16 17 18 19]
    #   [20 21 22 23]]]
    
    print(t5.reshape(4,6)) # 修改数组的形状
    # [[ 0  1  2  3  4  5]
    #  [ 6  7  8  9 10 11]
    #  [12 13 14 15 16 17]
    #  [18 19 20 21 22 23]]
    
    print(t5.flatten()) #展开把数组转化为1维度的数据
    # [ 0  1  2  3  4  5  6  7  8  9 10 11 12 13 14 15 16 17 18 19 20 21 22 23]
    
    

    数组的运算

    当两个数组的形状并不相同的时候,我们可以通过扩展数组的方法来实现相加、相减、相乘等操作,这种机制叫做广播(broadcasting)

    import numpy as np
    
    t5 = np.arange(24).reshape((2,3,4))
                        # 2块 每块3行4列
    #print(t5)
    # [[[ 0  1  2  3]
    #   [ 4  5  6  7]
    #   [ 8  9 10 11]]
    #
    #  [[12 13 14 15]
    #   [16 17 18 19]
    #   [20 21 22 23]]]
    print(t5+2) # 数组里面所有数均加2
    # [[[ 2  3  4  5]
    #   [ 6  7  8  9]
    #   [10 11 12 13]]
    # 
    #  [[14 15 16 17]
    #   [18 19 20 21]
    #   [22 23 24 25]]]
    
    import numpy as np
    
    t5 = np.arange(24).reshape((2,3,4))
                        # 2块 每块3行4列
    #print(t5)
    # [[[ 0  1  2  3]
    #   [ 4  5  6  7]
    #   [ 8  9 10 11]]
    #
    #  [[12 13 14 15]
    #   [16 17 18 19]
    #   [20 21 22 23]]]
    print(t5*2) # 数组里面所有数均乘2
    # [[[ 0  2  4  6]
    #   [ 8 10 12 14]
    #   [16 18 20 22]]
    # 
    #  [[24 26 28 30]
    #   [32 34 36 38]
    #   [40 42 44 46]]]
    
    
    import numpy as np
    
    t5 = np.arange(24).reshape((2,3,4))
                        # 2块 每块3行4列
    #print(t5)
    # [[[ 0  1  2  3]
    #   [ 4  5  6  7]
    #   [ 8  9 10 11]]
    #
    #  [[12 13 14 15]
    #   [16 17 18 19]
    #   [20 21 22 23]]]
    print(t5/2) # 数组里面所有数均除2
    # [[[ 0.   0.5  1.   1.5]
    #   [ 2.   2.5  3.   3.5]
    #   [ 4.   4.5  5.   5.5]]
    # 
    #  [[ 6.   6.5  7.   7.5]
    #   [ 8.   8.5  9.   9.5]
    #   [10.  10.5 11.  11.5]]]
    
    

    数组相加,乘,除

    import numpy as np
    
    t5 = np.arange(24).reshape((4,6))
    # print(t5)
    # [[ 0  1  2  3  4  5]
    #  [ 6  7  8  9 10 11]
    #  [12 13 14 15 16 17]
    #  [18 19 20 21 22 23]]
    t6 = np.arange(100,124).reshape((4,6))
    # print(t6)
    # [[100 101 102 103 104 105]
    #  [106 107 108 109 110 111]
    #  [112 113 114 115 116 117]
    #  [118 119 120 121 122 123]]
    print(t5+t6)
    # [[100 102 104 106 108 110]
    #  [112 114 116 118 120 122]
    #  [124 126 128 130 132 134]
    #  [136 138 140 142 144 146]]
    
    import numpy as np
    
    t5 = np.arange(24).reshape((4,6))
    # print(t5)
    # [[ 0  1  2  3  4  5]
    #  [ 6  7  8  9 10 11]
    #  [12 13 14 15 16 17]
    #  [18 19 20 21 22 23]]
    t6 = np.arange(100,124).reshape((4,6))
    # print(t6)
    # [[100 101 102 103 104 105]
    #  [106 107 108 109 110 111]
    #  [112 113 114 115 116 117]
    #  [118 119 120 121 122 123]]
    print(t5*t6)
    # [[   0  101  204  309  416  525]
    #  [ 636  749  864  981 1100 1221]
    #  [1344 1469 1596 1725 1856 1989]
    #  [2124 2261 2400 2541 2684 2829]]
    
    
    import numpy as np
    
    t5 = np.arange(24).reshape((4,6))
    # print(t5)
    # [[ 0  1  2  3  4  5]
    #  [ 6  7  8  9 10 11]
    #  [12 13 14 15 16 17]
    #  [18 19 20 21 22 23]]
    t6 = np.arange(100,124).reshape((4,6))
    # print(t6)
    # [[100 101 102 103 104 105]
    #  [106 107 108 109 110 111]
    #  [112 113 114 115 116 117]
    #  [118 119 120 121 122 123]]
    print(t6/t5)
    # [[         inf 101.          51.          34.33333333  26.
    #    21.        ]
    #  [ 17.66666667  15.28571429  13.5         12.11111111  11.
    #    10.09090909]
    #  [  9.33333333   8.69230769   8.14285714   7.66666667   7.25
    #     6.88235294]
    #  [  6.55555556   6.26315789   6.           5.76190476   5.54545455
    #     5.34782609]]
    
    import numpy as np
    
    t5 = np.arange(24).reshape((4,6))
    # print(t5)
    # [[ 0  1  2  3  4  5]
    #  [ 6  7  8  9 10 11]
    #  [12 13 14 15 16 17]
    #  [18 19 20 21 22 23]]
    t7 = np.arange(0,6)
    #print(t7)
    # [0 1 2 3 4 5]
    print(t5-t7)
    # [[ 0  0  0  0  0  0]
    #  [ 6  6  6  6  6  6]
    #  [12 12 12 12 12 12]
    #  [18 18 18 18 18 18]]
    
    import numpy as np
    
    t5 = np.arange(24).reshape((4,6))
    # print(t5)
    # [[ 0  1  2  3  4  5]
    #  [ 6  7  8  9 10 11]
    #  [12 13 14 15 16 17]
    #  [18 19 20 21 22 23]]
    
    t8 = np.arange(4).reshape((4,1))
    # print(t8)
    # [[0]
    #  [1]
    #  [2]
    #  [3]]
    print(t5-t8)
    # [[ 0  1  2  3  4  5]
    #  [ 5  6  7  8  9 10]
    #  [10 11 12 13 14 15]
    #  [15 16 17 18 19 20]]
    
    

    轴(axis)

    在numpy中可以理解为方向,使用0,1,2…数字表示,对于一个一维数组,只用一个0轴,对于2维数组(shape(2,2)),有0轴和1轴,对于一个三维数组(shape(2,2,3)),有0,1,2轴。
    1轴表示列 0轴表示行
    在这里插入图片描述

    1轴表示列 0轴表示行 2轴表示块在这里插入图片描述

    有了轴的概念之后,我们在计算会更加方便,比如计算一个2维数据的平均值,必须指定是计算哪个方向上面的数字的平均值

    numpy读取文件数据与转置

    在这里插入图片描述
    在这里插入图片描述
    在这里插入图片描述

    import numpy as np
    data = "D:/py/数据分析学习/numpy学习/数据.csv"
    t1 = np.loadtxt(data,delimiter=",",dtype="int") #delimiter=","按照逗号进行分割,dtype="int"指定数字类型
    print(t1)
    print("*"*50+"分割符"+"*"*50)
    t2 = np.loadtxt(data,delimiter=",",dtype="int",unpack=True) # 【转置】旋转列变行 默认unpack=False
    print(t2)
    

    在这里插入图片描述
    转置是一种变换,对于numpy中的数组来说,就是在对角线方向交换数据,目的也是为了更方便的处理数据
    在这里插入图片描述

    numpy索引和切片

    对于上述加载出来的数据,我们如果只想选择其中某一列(行)如下
    取行

    import numpy as np
    data = "D:/py/数据分析学习/numpy学习/数据.csv"
    t1 = np.loadtxt(data,delimiter=",",dtype="int") #delimiter=","按照逗号进行分割,dtype="int"指定数字类型
    print(t1) #所有数据
    print("*"*50+"取一行"+"*"*50)
    print(t1[2])
    print("*"*50+"取多行"+"*"*50)
    print(t1[2:])
    print("*"*50+"取指定行"+"*"*50)
    print(t1[[0,2,4]])
    

    在这里插入图片描述
    取列

    # -*- coding: utf-8 -*-
    import numpy as np
    
    data = "C:/Users/gpc/Desktop/python/其他/test01.csv"
    t1 = np.loadtxt(data,delimiter=",",dtype="int") #delimiter=","按照逗号进行分割,dtype="int"指定数字类型
    print(t1) #所有数据
    print("*"*50+"取一列"+"*"*50)
    print(t1[:,1])
    print("*"*50+"取连续多列"+"*"*50)
    print(t1[:,2:])
    print("*"*50+"取指定列"+"*"*50)
    print(t1[:,[0,2,4]])
    

    在这里插入图片描述
    在这里插入图片描述

    # -*- coding: utf-8 -*-
    import numpy as np
    
    data = "C:/Users/gpc/Desktop/python/其他/test01.csv"
    t1 = np.loadtxt(data,delimiter=",",dtype="int") #delimiter=","按照逗号进行分割,dtype="int"指定数字类型
    print(t1) #所有数据
    print("*"*20+"取多行和多列,取第3行,第4列得值"+"*"*20)
    print(t1[2,3])
    print("*"*20+"取多行和多列,取第3行到第5行,第2列到第4列得结果"+"*"*20)
    print(t1[2:5,1:4])
    print("*"*20+"取多个不相邻的点"+"*"*20)
    # (0,0),(2,1),(2,3)
    print(t1[[0,2,2],[0,1,3]])
    

    在这里插入图片描述
    在这里插入图片描述
    在这里插入图片描述

    numpy数值的修改

    # -*- coding: utf-8 -*-
    import numpy as np
    
    t1 = np.arange(24).reshape((4,6))
    print(t1)
    
    print("-"*50)
    
    t1[[2],[1]]=100
    print(t1)
    

    在这里插入图片描述

    numpy中布尔值索引

    # -*- coding: utf-8 -*-
    import numpy as np
    
    t1 = np.arange(24).reshape((4,6))
    print(t1)
    
    print("-"*50)
    
    print(t1<10)
    
    print("-"*50)
    
    t1[t1<10] = 3
    
    print(t1)
    
    

    在这里插入图片描述

    numpy中三元运算符

    # -*- coding: utf-8 -*-
    import numpy as np
    
    t1 = np.arange(24).reshape((4,6))
    print(t1)
    print(np.where(t1<=11,0,100))#t1中小于等于11的替换成0其余的全部替换成100
    

    在这里插入图片描述

    # -*- coding: utf-8 -*-
    import numpy as np
    
    t1 = np.arange(24).reshape((4,6))
    print(t1)
    print("-"*50)
    print(t1.clip(11,18)) # 小于11的替换成11,大于18的替换成18
    

    在这里插入图片描述

    # -*- coding: utf-8 -*-
    import numpy as np
    
    t1 = np.arange(24).reshape((4,6))
    print(t1)
    print("-"*50)
    t1 =t1.astype(float)#浮点数
    t1[3,3]=np.nan
    print(t1)
    
    

    在这里插入图片描述

    numpy中nan和inf

    • nan(NAN,Nan):not a number 表示不是一个数字
      • 当我们读取本地的文件为float的时候,如果有缺失,就会出现nan当做了一个不适合的计算的时候(比如无穷大(inf)减去无穷大)
    • inf(-inf,inf):infinity.inf表示正无穷,-inf表示负无穷
      • 比如一个数字除以0,(python中会直接报错,numpy中是一个inf或者-inf)
    # -*- coding: utf-8 -*-
    import numpy as np
    
    print(np.nan == np.nan)
    # False
    print(np.nan != np.nan)
    # True
    t1 = np.arange(24).reshape((4,6))
    t1 =t1.astype(float)#浮点数
    t1[3,3]=np.nan
    print(t1)
    t1[:,0]=0
    print(t1)
    print(np.count_nonzero(t1))
    # 20  # 不为0的个数是20个
    print(np.isnan(t1)) # 判断那些值是nan的
    print(np.count_nonzero(np.isnan(t1))) # 统计nan的个数
    # nan和任何值计算都为nan
    print(np.sum(t1))
    # nan
    t2 = np.arange(12).reshape(3,4)
    print(np.sum(t2))
    # 66
    # 横行竖列
    print(np.sum(t2,axis=0)) # 每列的和
    # [12 15 18 21]
    print(np.sum(t2,axis=1))# 每行的和
    # [ 6 22 38]
    print(np.sum(t1,axis=0)) # nan和任何值计算都为nan
    # [ 0. 40. 44. nan 52. 56.]
    

    在这里插入图片描述
    在这里插入图片描述

    # -*- coding: utf-8 -*-
    import numpy as np
    
    t1 = np.arange(24).reshape((4,6))
    t1 =t1.astype(float)#浮点数
    t1[3,3]=np.nan
    print(t1)
    # 横行竖列
    print(t1.sum(axis=0)) # 没列的和
    # [36. 40. 44. nan 52. 56.]
    print(t1.mean(axis=0)) # 计算每列的均值
    # [ 9. 10. 11. nan 13. 14.]
    print(np.median(t1,axis=0)) # 计算每列的中值
    # [ 9. 10. 11. nan 13. 14.]
    print(t1.max(axis=0)) # 数组中最大值的一列
    # [18. 19. 20. nan 22. 23.]
    print(t1.min(axis=0)) # 最小值的一列
    # [ 0.  1.  2. nan  4.  5.]
    print(np.ptp(t1,axis=0)) # 极值 按列计算数组中最大值和最小值的差
    # [18. 18. 18. nan 18. 18.]
    print(t1.std(axis=0)) # 标准差
    # [6.70820393 6.70820393 6.70820393        nan 6.70820393 6.70820393]
    

    在这里插入图片描述

    数组的拼接

    # -*- coding: utf-8 -*-
    import numpy as np
    
    t1 = np.arange(1,13).reshape((2,6))
    print(t1)
    print("-"*50)
    t2 = np.arange(13,25).reshape(2,6)
    print(t2)
    print("-"*50)
    print(np.vstack((t1,t2)))# 竖直拼接
    print("-"*50)
    print(np.hstack((t1,t2)))# 水平拼接
    

    在这里插入图片描述

    # -*- coding: utf-8 -*-
    import numpy as np
    
    
    # t1 = np.arange(12).reshape(3,4).astype("float")
    # t1[1,2:]=np.nan
    #print(t1)
    def fill_ndarray(t1):
        for i in range(t1.shape[1]): # 遍历没列
            temp_col = t1[:,i] # 当前的一列
            nan_num = np.count_nonzero(temp_col!=temp_col)
            if nan_num != 0: # 不为0,说明当前这一列中有nan
                temp_not_nan_col = temp_col[temp_col==temp_col] # 当前一列不为nan的array
                #temp_not_nan_col.mean()
                temp_col[np.isnan(temp_col)]=temp_not_nan_col.mean() # 选中当前为nan的位置,把值赋值为不为nan的均值
        return t1
    
    if __name__=='__main__':
        t1 = np.arange(12).reshape(3, 4).astype("float")
        t1[1, 2:] = np.nan
        print(t1)
        t1 = fill_ndarray(t1)
        print(t1)
    
    

    在这里插入图片描述

    数组交换

    # -*- coding: utf-8 -*-
    import numpy as np
    
    t1 = np.arange(1,25).reshape((4,6))
    print(t1)
    print("-"*50)
    t1[[1,2],:]=t1[[2,1],:]#行交换
    print(t1)
    print("-"*50)
    t1[:,[0,5]]=t1[:,[5,0]]#列交换
    print(t1)
    

    在这里插入图片描述

    # -*- coding: utf-8 -*-
    import numpy as np
    
    print(np.ones((2,3))) #创建全为1的数据
    print(np.zeros((2,3))) #全为0的数据
    

    在这里插入图片描述
    在这里插入图片描述

    # -*- coding: utf-8 -*-
    import numpy as np
    
    
    # 加载文件数据
    data1 = "C:/Users/gpc/Desktop/python/其他/test01.csv"
    data2 = "C:/Users/gpc/Desktop/python/其他/test02.csv"
    
    t1 = np.loadtxt(data1,delimiter=",",dtype="int") #delimiter=","按照逗号进行分割,dtype="int"指定数字类型
    t2 = np.loadtxt(data2,delimiter=",",dtype="int")
    
    
    # 添加信息
    # 构造全为0的数据
    zeros_data = np.zeros((t1.shape[0],1))
    ones_data = np.ones((t2.shape[0],1))
    
    # 分别添加一列全为0,1的数组
    t1 = np.hstack((t1,zeros_data)).astype(int)
    t2 = np.hstack((t2,ones_data)).astype(int)
    # 拼接两组数据
    t3= np.vstack((t1,t2))
    print(t3)
    
    

    在这里插入图片描述

    numpy生成随机数

    在这里插入图片描述

    # -*- coding: utf-8 -*-
    import numpy as np
    
    
    t1 = np.random.randint(10,20,(4,5))
    print(t1)
    
    

    在这里插入图片描述

    # -*- coding: utf-8 -*-
    import numpy as np
    
    np.random.seed(10) # 随机生成种子,每次随机得到的结果和上次一样
    t1 = np.random.randint(10,20,(4,5)) # 生成10-20的随机数,4列5行
    print(t1)
    

    在这里插入图片描述

    # -*- coding: utf-8 -*-
    import numpy as np
    
    np.random.seed(10) # 随机生成种子,每次随机得到的结果和上次一样
    t1 = np.random.randint(10,20,(4,5)) # 生成10-20的随机数,4列5行
    print(t1)
    t2 = t1[:]# 视图操作,一种切片会创建新的对象,但是t2的数据完全由t1保管,数据变化一致
    print(t2)
    t3 = t1.copy()  # 复制,t3,t1互不影响
    print(t3)
    

    在这里插入图片描述

    在这里插入图片描述
    在这里插入图片描述

  • 相关阅读:
    【Teradata】DSA服务器tdactivemq重启清理消息队列步骤
    什么是5G
    【时序数据库】十分钟系列
    16_Android的数据存储_ SharedPreference、XML和JSON
    15_Android文件读写操作
    14_TTS
    13_拍照、录像和音频
    12_Sensor简单实例
    11_SurfaceView绘图
    10_多点触摸交互处理
  • 原文地址:https://www.cnblogs.com/gemoumou/p/14186299.html
Copyright © 2011-2022 走看看