zoukankan      html  css  js  c++  java
  • numpy最后一部分及pandas初识

    今日内容概要

    • numpy剩余的知识点
    • pandas模块

    今日内容详细

    二元函数

    加                   add
    减                   sub
    乘                   mul
    除                   div
    平方                 power
    

    数学统计方法

    sum                 求和
    cumsum              累计求和
    mean                对整体求平均数
    std                 标准差
    var                 方差
    min
    max
    argmin              求最小元素对应的索引 
    armax               求最大元素对应的索引
    

    随机数

    np.random.rand(2.5) # 随机0-1之间的小数
    array([[0.65863779, 0.9994306 , 0.35758039, 0.02292617, 0.70794499],
           [0.15469852, 0.97426284, 0.25622487, 0.20442957, 0.95286145]])
    np.random.randint(1,10) # 取给定的数之间的随机整数
    4
    np.random.choice([111,222,333,444,555]) # 从给定的数组中随机的取一个
    333
    res = [1,2,3,4,5,6,7,8,9,10,'J','Q','K','A']
    np.random.shuffle(res)  # 随机打乱顺序
    res
    [1, 'Q', 'J', 6, 8, 'K', 2, 3, 'A', 7, 10, 4, 9, 5]
    np.random.uniform([100,10,11,22]) # 指定数组位置产生对应的随机数
    array([83.53838005,  5.4824623 ,  4.85571734,  7.33774372])
    

    特殊值含义

    1、nan(Not a Number):不等于任何浮点数(nan != nan)
           表示的意思是缺失值(pandas里面)
    ---------------------------------------------
    
    2、inf(infinity):比任何浮点数都大
    ---------------------------------------------    
    

    Pandas模块

    1.非常强大的python数据分析包
    2.基于numpy构建的 所以学习起来会有一种似曾相识的感觉
    2.pandas奠定了python在数据分析领域的一哥地位
    

    主要功能

    1.具有两大非常灵活强大的数据类型
       series
       DataFrame
    2.集成时间模块
    3.提供丰富的数学运算和操作(基于numpy)
    4.针对缺失数据操作非常灵活
    

    两大数据结构

    python中的字典
         key:value的形式
                 key是对value的描述性信息
                 value就是具体的数据
         res = {
              'username':'jason',
              'password':123,
              'hobby':'read'
         }       
    
    • Series

      类似于字典的带有标签的数组
      
    • DataFrame

      其实类似于excel表格数据
      

      都是基于numpy构建出来的

      公司中使用频繁的是DataFrame,而Series是构成DataFrame的基础,即一个DataFrame可能由N个Series构成

    基本使用

    一定要先导入pandas,约定俗成的导入语句书写
    import pandas as pd
    

    数据结构之Series

    是一种类似于一维数组对象,由数据和相关的标签(索引)组成
    Series的创建方式总共有四种
    
    左侧In[*]  正在运行加载
    In[数字]   加载或者运行成功
    """
    在python中导入模块的时候 只会加载一次
    之后导入相同的模块不会继续加载而是直接使用
    上一次加载的结果
    python会将所有导入的模块单独存放到一个文件中
          导入模块的时候会自动去文件中查找  如果有则直接使用
    python解释器关闭之后该文件就会清空      
    """
    
    #第一种
    # Series的创建
    res = pd.Series([111,222,333,444,555])
    res
    0    111
    1    222
    2    333
    3    444
    4    555
    dtype: int64 # 默认会自动帮你用索引作为数据的标签
    
    # 第二种
    # 2.指定元素的标签:个数一定要一致
    res1 = pd.Series([111,222,333,444,555],index=['a','b','c','d','e'])
    res1
    a    111
    b    222
    c    333
    d    444
    e    555
    dtype: int64
    # 第三种
    # 3.直接放字典
    res2 = pd.Series({'username':'jason','password':123,'hobby':'read'})
    res2
    username    jason
    password      123
    hobby        read
    dtype: object
    # 第四种
    pd.Series(0,index=['a','b','c'])
    a    0
    b    0
    c    0
    dtype: int64
    '''
    Series的结构
        左侧是标签
        右侧是数据
    '''    
    

    缺失数据

    '''前戏'''
    # 第一步,创建一个字典,通过Series方式创建一个Series对象
    st = {"tony":18,"yang":19,"bella":20,"cloud":21}
    obj = pd.Series(st)
    obj
    tony     18
    yang     19
    bella    20
    cloud    21
    dtype: int64
    --------------------------------------------
    
    # 第二步
    a = {'tony','yang','cloud','satan'} # 定义一个索引变量
    -------------------------------------------
    
    # 第三步
    obj1 = pd.Series(st,index=a)
    obj1   # 将第二步定义的a变量作为索引传入
    
    yang     19.0
    tony     18.0
    satan     NaN
    cloud    21.0
    dtype: float64
    # 因为rocky没有出现在st的键中,所以返回的是缺失值    
    

    特殊值的处理

    1.isnull
    2.notnull
    3.dropna
    4.fillna
    
    obj1.isnull()
    yang     False
    tony     False
    satan     True
    cloud    False
    dtype: bool
    
    obj1.notnull()
    yang      True
    tony      True
    satan    False
    cloud     True
    dtype: bool
        
    3、
    过滤缺失值 # 布尔型索引
    obj1[obj1.notnull()]
    yang     19.0
    tony     18.0
    cloud    21.0
    dtype: float64
    
    obj1.dropna()   # 默认不会改变原来数据
    yang     19.0
    tony     18.0
    cloud    21.0
    dtype: float64
        
    obj1.dropna(inplace=True)  # 该参数默认是Flase不修改数据本身
    obj1
    tony     18.0
    yang     19.0
    cloud    21.0
    dtype: float64
        
    obj1.fillna(666)   # 默认也是不修改原来的数据的 要想直接修改加参数inplace=True即可
    yang     19.0
    tony     18.0
    cloud    21.0
    dtype: float64
    yang     19.0
    tony     18.0
    satan     NaN
    cloud    21.0
    dtype: float64
    
    '''
    上述四个方法中
         方法3和4是使用频率最高的
    '''    
        
    

    Series的各种特性

    基于跟Numpy操作一致
    1.ndarray直接创建Series:Series(array)
             Series可以直接将numpy中的一维数组转换(这里必须只能是一维)
             
            res = pd.Series(np.array([1,2,3,4,5,6]))
            res
            0    1
            1    2
            2    3
            3    4
            4    5
            5    6
            dtype: int32
                
            res1 = pd.Series(np.array([[1,2,3,4],[5,6,7,8]]))
            res1    # 报错
            Exception                                 Traceback (most recent call last)
    <ipython-input-30-e48b7149c3f9> in <module>
    ----> 1 res1 = pd.Series(np.array([[1,2,3,4],[5,6,7,8]]))
          2 res1
    
    C:ProgramDataAnaconda3libsite-packagespandascoreseries.py in __init__(self, data, index, dtype, name, copy, fastpath)
        309                     data = data.copy()
        310             else:
    --> 311                 data = sanitize_array(data, index, dtype, copy, raise_cast_failure=True)
        312 
        313                 data = SingleBlockManager(data, index, fastpath=True)
    
    C:ProgramDataAnaconda3libsite-packagespandascoreinternalsconstruction.py in sanitize_array(data, index, dtype, copy, raise_cast_failure)
        727     elif subarr.ndim > 1:
        728         if isinstance(data, np.ndarray):
    --> 729             raise Exception("Data must be 1-dimensional")
        730         else:
        731             subarr = com.asarray_tuplesafe(data, dtype=dtype)
    
    Exception: Data must be 1-dimensional
    
    2.与标量运算
        res = pd.Series([11,22,33,44,55])
        res
        0    11
        1    22
    	2    33
    	3    44
    	4    55
    	dtype: int64
        res * 2
        0     22
    	1     44
    	2     66
    	3     88
    	4    110
    	dtype: int64
    3.两个Series运算
          res * res
        0     121
    	1     484
    	2    1089
    	3    1936
    	4    3025
    	dtype: int64
            
      res1 = pd.Series([1,2,3,4],index=['a','b','c','d'])
      res * res1
      	0   NaN
    	1   NaN
    	2   NaN
    	3   NaN
    	4   NaN
    	a   NaN
    	b   NaN
    	c   NaN
    	d   NaN
    	dtype: float64  
    4.通用函数abs
       	res3 = pd.Series([-1,-2,-3,-4,5,6])
       	res3.abs()
       	0    1
    	1    2
    	2    3
    	3    4
    	4    5
    	5    6
    	dtype: int64
    5.布尔值索引
    6.统计函数
    7.从字典创建Series:Series(dic)
    8.In运算
        res4 = pd.Series({'username':'satan','password':987})
        res4
        username    satan
    	password      987
    	dtype: object
        'username' in res4
        True
        
        for i in res4: # 跟python中的字典不一样 这里直接拿数据而不是标签
        print(i)
        satan
    	987
    9.键索引与切片
    10.其他函数等
    

    小补充

    # 当你的机器下载了anaconda之后无法正常呼起一个jupyter界面
    1.先去你的cmd窗口检查是否可以正常运行
        ipython
        jupyter notebook
    2.anaconda软件需要的资源其实有点多
    3.你的默认浏览器没有设置好
    
    在你的cmd窗口中输入jupyter notebook启动一个服务端, 不借助于anaconda
    手动将网址复制到浏览器地址栏
    直接使用即可
    
    为了舒适的结果,眼前的坎坷路程即使再长都是值得的。
  • 相关阅读:
    Vue
    Vue
    Vue
    Vue
    Vue
    Vue
    Vue
    Vue
    Vue
    建立索引该如何选取字段
  • 原文地址:https://www.cnblogs.com/abudrSatan1998/p/13608385.html
Copyright © 2011-2022 走看看