zoukankan      html  css  js  c++  java
  • 12_3numpy的索引以及pandas的两个数据结构。

    一。索引与切片。

      nump的索引和python中的索引差不多,都是左开右闭区间。

      如一个普通的array的索引,是由0开始的:

    res = np.array([1,2,3,4,5]) #### nparray索引是从0开始
    res[1]
    2

      一个二维数组的索引有两种

    res = np.array([[1,2,3,5],[6,7,8,9]])
    res[1,1]
    7

      或者(推荐):

    res[1][1]
    7

      切片

      一维数组的切片:

    res = np.array([1,2,3,4,5])
    res[1:4]
    array([2, 3, 4])

      二维数组的切片

    res = np.array([[1,2,3,4],[5,6,7,8], [9,10,11,12]])
    res[1:3, 1:3]
    array([[ 6,  7],
           [10, 11]])

      布尔索引

      首先生成一个随机数组:

    import random
    li = [random.randint(1,10) for _ in range(20)]
    res = np.array(li)

      如果需要选出数组中大于5的数,一般需要遍历数组,但是使用布尔型索引就很方便。

      首先将其大于5的部分变成布尔型:

    res > 5
    array([False,  True,  True,  True, False, False, False, False,  True,
           False,  True, False,  True,  True,  True, False, False,  True,
           False,  True])

      再直接将其作为索引条件方如该索引中:

    res[res>5]
    array([ 8,  6,  8,  9,  9,  8,  7, 10,  9,  9])

      二维数组也可以这样操作:

    res = np.array([[1,2,3,4], [5,6,7,8]])
    res[res > 5]
    array([6, 7, 8])

      花式索引:

      可以将需要索引的值的下标放入列表中 ,将列表作为索引值,取出对应下标的值:

    res = np.array([1,2,3,4,5,6,7,8,9,10])
    res[[1,3,6,8]]
    array([2, 4, 7, 9])

      reshape

      将一个数组的形状改变,改成二维或者一维,但是所有的值加起来不能变:

    s = res.reshape(2,5)
    s.reshape(10)
    array([ 1,  2,  3,  4,  5,  6,  7,  8,  9, 10])

    二。通用函数

      1.abs 求绝对值

    np.abs(-2)  ### 求绝对值
    2

      绝对值可以是数组:

    np.abs([-2,-4,-5,-10])
    array([ 2,  4,  5, 10])

      2.fabs 浮点数绝对值。

      用来计算浮点数的绝对值:

    np.fabs([-1.3,-2.5,-3.4])
    array([1.3, 2.5, 3.4])

      3.sqrt 求平方根

    np.sqrt(4)
    2.0
    np.sqrt(2)
    1.4142135623730951:

      4.square 求平方

    np.square(2)  ### 求平方
    4

      5.exp 求e**x

    np.exp(2) 
    7.38905609893065

      6.log 求log

    np.log(2)
    0.6931471805599453

      7.ceil()向上取整

    np.ceil(5.4)  #### 向上取整
    6.0

      8.floor 向下取整

    np.floor(4.6)
    4.0

      9.rint 四舍五入:

    np.rint(3.5)
    4.0
    np.rint(3.2)
    3.0

      10.modf 将其整数与小数分离:

    np.modf([1.2,3.5,4.7])
    (array([0.2, 0.5, 0.7]), array([1., 3., 4.]))

      11.nan  

      nan是一个特殊的数字,它的数据类型位float,是用来替换数据中什么都没有的数据。

      它连它自己也不等于:

    np.nan
    nan
    np.nan == np.nan
    False

      当判断是否是nan的时候可以使用isnan进行判断:

    np.isnan(np.nan)
    True

      12.sum 求一个数组的和

    np.sum([1,2,3,4,5])
    15

      13.cumsum 求该列表之前的所有数的和:
      14.var方差和std平均差

    li = [1,2,3,4,5]
    ### 方差: ((1-平均数)**2 + (2-平均数)**2 + ....) / 5
    ### 标准差: 方差开根号

      15.max 最大值  argmax最大索引值

    np.max(res)
    5
    np.argmax(res)
    4

      

    函数功能 
    sum 求和  
    cumsum 求前缀和  
    mean 求平均数  
    std 求标准差  
    var 求方差  
    min 求最小值  
    max 求最大值  
    argmin 求最小值索引  
    argmax 求最大值索引

    三。随机数

      1.rand  生成一个0-1之间的随机数

    np.random.rand()  ### 生成一个0-1之间的随机数
    0.9407811145107979

      2.randint生成这个区间里的一个数

    np.random.randint(1,10)
    4

      3.choice  从前面的数中选几个数

    np.random.choice(12,5)
    array([8, 0, 1, 4, 9])

      4,uniform 给定形状正太分步,可以给二维数组

    np.random.uniform(0,10,[10,10])  #### 正态分布
    array([[5.55467182, 1.74301923, 4.2272649 , 9.71388574, 6.62650629,
            0.84804251, 6.97707852, 1.32037512, 8.87127644, 4.81503186],
           [7.32022186, 2.88828494, 9.89366413, 8.16468677, 8.48887315,。。。。。

     四。pandas中值series

      pandas 是一个强大的python数据分析包,它是基于numpy构建的。

      安装方法:

    pip install pandas

      引用方法:

    import pandas as pd

      series

      series是一种类似于以为数组的对象,它可以是一个有序的字典。

      1.不给索引创建,会自动创建索引。

    s1 = pd.Series([1,2,3,4])
    0    1
    1    2
    2    3
    3    4
    dtype: int64

      对其索引也是使用该索引:

    s1[1]
    2

      2.指定索引创建:

    s2 = pd.Series([1,2,3,4], index=['a', 'b', 'c', 'd'])
    a    1
    b    2
    c    3
    d    4
    dtype: int64

      索引:

    s2['b']
    2

      可以使用字典的方式创建:

    pd.Series({"a":1, "b":2})
    a    1
    b    2
    dtype: int64

      缺失数据处理

      当使用字典发输入数据的时候,可以给定索引,索引必须与字典的key值对应否则该数据就是nan型:

    st = {"sean":18,"yang":19,"bella":20,"cloud":21}
    obj = pd.Series(st)
    obj
    sean     18
    yang     19
    bella    20
    cloud    21
    dtype: int64

      缺失数据:

    st = {"sean":18,"yang":19,"bella":20,"cloud":21}
    s3 = pd.Series(st, index={'sean','yang','cloud','rocky'})
    s3
    yang     19.0
    rocky     NaN
    cloud    21.0
    sean     18.0
    dtype: float64

      要想过滤这个数据,有两种方法:

      1.dropna

    s3.dropna(inplace=True)
    sean     18.0
    yang     19.0
    cloud    21.0
    dtype: float64

      这个函数会将这数据中的所有nan过滤排除,

      如果其中的参数inplace为true,则原来数据中的nan也会被排除。

      2.fillna

      fillna会将该数字替换成指定的数,并且也有inplace参数

    #### fillna
    s3.fillna(0, inplace=True)
    sean     18.0
    rocky     0.0
    yang     19.0
    cloud    21.0
    dtype: float64

      数据的计算

      支持标量:

    s3 * 2
    yang     38.0
    rocky     0.0
    cloud    42.0
    sean     36.0
    dtype: float64

      支持相加:

    s3 + s4
    yang     38.0
    rocky    20.0
    cloud    42.0
    sean     36.0
    dtype: float64

      支持布尔型索引

    s3[s3>0]

      支持字典索引:

    s3['rocky']
    0.0

      iloc

      iloc索引的是该数字的位置下表

    s3.iloc[1]  ##### iloc : 索引位置下标
    0.0

      loc索引的是index:

    s3.loc['rocky']
    0.0

      数据对对齐

      当两个数字进行相加的时候,会自动根据索引进行相加,

    sr1 = pd.Series([12,23,34], index=['c','a','d'])
    sr2 = pd.Series([11,20,10], index=['d','c','a',])
    sr1+sr2
    a    33
    c    32
    d    45
    dtype: int64

      如果相加的时候有以方没有该索引,就会是nan

    sr3
    d    11
    c    20
    a    10
    b    14
    dtype: int64
    sr1 + sr3
    a    33.0
    b     NaN
    c    32.0
    d    45.0
    dtype: float64

    四。pandas中的datafarme

      创建dataframe

      创建dataframe使用字典+列表的方式:

    df = pd.DataFrame( {'one':[1,2,3,4],'two':[4,3,2,1]} )
        one    two
    0    1    4
    1    2    3
    2    3    2
    3    4    1

      创建之后会自动补上索引。

      使用columns可以选择字典中的kv进行显示:

    data = pd.DataFrame({'one':[1,2,3,4],'two':[4,3,2,1]})
    pd.DataFrame(data,columns=['two','one'])
        two    one
    0    4    1
    1    3    2
    2    2    3
    3    1    4

      索引:

      将这个头部+索引的方式定位元素:

    df['one'][0]
    1

      使用index可以查看该data的索引和步长:

    df.index
    RangeIndex(start=0, stop=4, step=1)

      使用columns查看其行标:

    df.columns
    Index(['one', 'two'], dtype='object')

      使用values可以查看其值:

    df.values
    array([[1, 4],
           [2, 3],
           [3, 2],
           [4, 1]], dtype=int64)

      describe()  查看dataframe的明细:

    df.describe()
    
          one      two
    count    4.000000    4.000000
    mean    2.500000    2.500000
    std    1.290994    1.290994
    min    1.000000    1.000000
    25%    1.750000    1.750000
    50%    2.500000    2.500000
    75%    3.250000    3.250000
    max    4.000000    4.000000

    五。获取数据的方式:

      在真实的数据分析中,常用的数据都是通过外部导入。

      1.导入csv格式的数据:

    df = pd.read_csv('./douban_movie.csv')
    df
        名字    投票人数    类型    产地    上映时间    时长    年代    评分    首映地点
    0    肖申克的救赎    692795.0    剧情/犯罪    美国    1994-09-10 00:00:00    142.0    1994    9.6    多伦多电影节
    1    控方证人    42995.0    剧情/悬疑/犯罪    美国    1957-12-17 00:00:00    116.0    1957    9.5    美国
    2    美丽人生    327855.0    剧情/喜剧/爱情    意大利    1997-12-20 00:00:00    116.0    1997    9.5    意大利
    3    阿甘正传    580897.0    剧情/爱情    美国    1994-06-23 00:00:00    142.0    1994    9.4    洛杉矶首映
    。。。。

      head() tail()

      可以查看数据的开头部分和结尾部分。

      读取的数据可以通过to_csv保存到csv格式:

    df.to_csv('./a.csv', index=False)

      加上index就可以避免重复的index

  • 相关阅读:
    WPF-模拟动态更换logo的过程(3),图片正在使用中,下载同名图片无法覆盖的问题。
    WPF-模拟动态更换logo的过程(2),如何把网上的图片下载到指定目录。
    WPF-模拟动态更换logo的过程(1),如何获取程序的根目录。
    Prism——Window 必须是树的根目录。不能将 Window 添加为 Visual 的子目录。
    一款常用的截图工具(能够截gif动图)
    WPF-带有GridView的ListView样式
    WPF-自定义实现步骤条控件
    分页总页数计算公式
    FileZilla:425 Can't open data connection for transfer of解决办法
    查看window重启日志
  • 原文地址:https://www.cnblogs.com/LZXlzmmddtm/p/11978798.html
Copyright © 2011-2022 走看看