zoukankan      html  css  js  c++  java
  • python 数据分析----pandas

    pandas是一个强大的Python数据分析的工具包。

    pandas是基于NumPy构建的。

    pandas的主要功能

    • 具备对其功能的数据结构DataFrame、Series
    • 集成时间序列功能
    • 提供丰富的数学运算和操作
    • 灵活处理缺失数据

    安装方法:pip install pandas

    引用方法:import pandas as pd

    Series:

    是带有标签的一维数组,可以保存任何数据类型(整数,字符串,浮点数,Python对象等)。轴标签统称为索引创建Series的基本方法是调用:

    s = pd.Series(data, index=index)

    data 可以是:

    • Python dict(字典)
    • ndarray
    • 数字

    如果data是ndarray,则索引必须与数据长度相同。如果没有传递索引,将创建值为[0, ..., len(data) 1]的索引。

    In [125]: import pandas as pd
    
    In [126]: a = pd.Series([4,7,-5,3],index=['a','b','c','d'])
    
    In [127]: a
    Out[127]: 
    a    4
    b    7
    c   -5
    d    3
    dtype: int64
    
    
    In [130]: b = pd.Series({'a':1,'b':2})
    
    In [131]: b
    Out[131]: 
    a    1
    b    2
    dtype: int64

    获取值数组和索引数组:values属性和index属性

    In [133]: a.values
    Out[133]: array([ 4,  7, -5,  3])
    
    In [134]: a.index
    Out[134]: Index(['a', 'b', 'c', 'd'], dtype='object')

    Series特性:

    • 从ndarray创建Series:Series(arr)
      In [140]: arr = np.array([1,2,3,4,5]) #必须是一维数组
      
      In [141]: a = pd.Series(arr)
      
      In [142]: a
      Out[142]: 
      0    1
      1    2
      2    3
      3    4
      4    5
      dtype: int64
    • 与标量运算:sr*2
      In [142]: a
      Out[142]: 
      0    1
      1    2
      2    3
      3    4
      4    5
      dtype: int64
      
      In [143]: a*2
      Out[143]: 
      0     2
      1     4
      2     6
      3     8
      4    10
      dtype: int64
    • 两个Series运算:sr1+sr2. 注意索引得一样,否则报NaN错误(not a number)
      In [145]: b
      Out[145]: 
      a    4
      b    7
      c   -5
      d    3
      e    0
      dtype: int64
      
      In [146]: a
      Out[146]: 
      0    1
      1    2
      2    3
      3    4
      4    5
      dtype: int64
      
      In [147]: b+a
      Out[147]: 
      a   NaN
      b   NaN
      c   NaN
      d   NaN
      e   NaN
      0   NaN
      1   NaN
      2   NaN
      3   NaN
      4   NaN
      dtype: float64
      
      
      In [150]: b = pd.Series(np.arange(5))
      
      In [151]: a
      Out[151]: 
      0    1
      1    2
      2    3
      3    4
      4    5
      dtype: int64
      
      In [152]: b
      Out[152]: 
      0    0
      1    1
      2    2
      3    3
      4    4
      dtype: int64
      
      In [153]: a+b
      Out[153]: 
      0    1
      1    3
      2    5
      3    7
      4    9
      dtype: int64
    • 索引:sr[0], sr[[1,2,4]]
      In [157]: b
      Out[157]: 
      a    4
      b    7
      c   -5
      d    3
      e    0
      dtype: int64
      
      In [158]: b[0]
      Out[158]: 4
      
      In [159]: b['a']
      Out[159]: 4
    • 切片:sr[0:2](切片依然是视图形式,浅拷贝)
      In [161]: b[1:3]
      Out[161]: 
      b    7
      c   -5
      dtype: int64
      
      In [162]: b['b':'d']
      Out[162]: 
      b    7
      c   -5
      d    3
      dtype: int64
      
      In [163]: b['b':'c']
      Out[163]: 
      b    7
      c   -5
      dtype: int64
    • 通用函数:np.abs(sr)
    • 布尔值过滤:sr[sr>0]
      In [164]: b
      Out[164]: 
      a    4
      b    7
      c   -5
      d    3
      e    0
      dtype: int64
      
      In [165]: b[b>3]
      Out[165]: 
      a    4
      b    7
      dtype: int64
    • 统计函数:mean() sum() cumsum()
      In [169]: b
      Out[169]: 
      a    4
      b    7
      c   -5
      d    3
      e    0
      dtype: int64
      
      In [170]: b.mean()
      Out[170]: 1.8
      
      In [171]: b.sum()
      Out[171]: 9
      
      In [173]: b.cumsum(). #每个数字与这列之前的数据的和
      Out[173]: 
      a     4
      b    11
      c     6
      d     9
      e     9
      dtype: int64
    • Series支持字典的特性(标签):
      • 从字典创建Series:Series(dic), 
      • in运算:’a’ in sr、for x in sr
      • 键索引:sr['a'], sr[['a', 'b', 'd']]
      • 键切片:sr['a':'c']
      • 其他函数:get('a', default=0)等

    整数索引:

    如果索引是整数类型,则根据整数进行数据操作时总是面向标签的。

    • loc属性 以标签解释
    • iloc属性 以下标解释 
    In [178]: sr = pd.Series(np.arange(4.))
    
    In [179]: sr
    Out[179]: 
    0    0.0
    1    1.0
    2    2.0
    3    3.0
    dtype: float64
    
    In [185]: sr.iloc[0]
    Out[185]: 0.0
    
    In [186]: sr.loc[0]
    Out[186]: 0.0

    Series数据对齐

      pandas在运算时,会按索引进行对齐然后计算。如果存在不同的索引,则结果的索引是两个操作数索引的并集。

    • sr1.add(sr2, fill_value=0)
    • 灵活的算术方法:add, sub, div, mul
    In [189]: sr1
    Out[189]: 
    c    12
    a    23
    d    34
    dtype: int64
    
    In [190]: sr2
    Out[190]: 
    d    11
    c    20
    a    10
    dtype: int64
    
    In [191]: sr1+sr2
    Out[191]: 
    a    33
    c    32
    d    45
    dtype: int64
    
    In [192]: sr3 = pd.Series([11,20,10,14], index=['d','c','a','b'])
    
    In [193]: sr2+sr3
    Out[193]: 
    a    20.0
    b     NaN
    c    40.0
    d    22.0
    dtype: float64
    
    
    In [194]: sr2.add(sr3,fill_value = 0)
    Out[194]: 
    a    20.0
    b    14.0
    c    40.0
    d    22.0
    dtype: float64
    • 缺失数据:使用NaN(Not a Number)来表示缺失数据。其值等于np.nan。内置的None值也会被当做NaN处理。
    • 处理缺失数据的相关方法:
      • dropna() 过滤掉值为NaN的行
      • fillna() 填充缺失数据
      • isnull() 返回布尔数组,缺失值对应为True
      • notnull() 返回布尔数组,缺失值对应为False
    • 过滤缺失数据:sr.dropna() 或 sr[data.notnull()]
    • 填充缺失数据:fillna(0)

    DataFrame

    DataFrame是一个表格型的数据结构,含有一组有序的列。

    DataFrame可以被看做是由Series组成的字典,并且共用一个索引。

    创建方式:

    • pd.DataFrame({'one':[1,2,3,4],'two':[4,3,2,1]})
    • pd.DataFrame({'one':pd.Series([1,2,3],index=['a','b','c']), 'two':pd.Series([1,2,3,4],index=['b','a','c','d'])})
    In [195]: df = pd.DataFrame({'one':pd.Series([1,2,3],index=['a','b','c']), 'two'
         ...: :pd.Series([1,2,3,4],index=['b','a','c','d'])})
    
    In [196]: df
    Out[196]: 
       one  two
    a  1.0    2
    b  2.0    1
    c  3.0    3
    d  NaN    4

    csv文件读取与写入:

    • df.read_csv('filename.csv')
    • df.to_csv()

    常用属性及方法:

    • T 转置
    • index 获取索引
    • columns 获取列索引
    • values 获取值数组
      In [213]: df
      Out[213]: 
         one  two
      a  1.0    2
      b  2.0    1
      c  3.0    3
      d  NaN    4
      
      In [214]: df.index
      Out[214]: Index(['a', 'b', 'c', 'd'], dtype='object')
      
      In [215]: df.columns
      Out[215]: Index(['one', 'two'], dtype='object')
      
      In [216]: df.values
      Out[216]: 
      array([[  1.,   2.],
             [  2.,   1.],
             [  3.,   3.],
             [ nan,   4.]])

    索引和切片:

    In [196]: df
    Out[196]: 
       one  two
    a  1.0    2
    b  2.0    1
    c  3.0    3
    d  NaN    4
    
    In [197]: df['one'] #只能是列名
    Out[197]: 
    a    1.0
    b    2.0
    c    3.0
    d    NaN
    Name: one, dtype: float64
    In [221]: df
    Out[221]: 
       one  two
    a  1.0    2
    b  2.0    1
    c  3.0    3
    d  NaN    4
    
    In [222]: df.loc['a',df.columns[1]] #行和列
    Out[222]: 2

    通过位置获取:

    • df.iloc[3]
    • df.iloc[3,3]
    • df.iloc[0:3,4:6]
    • df.iloc[1:5,:]
    • df.iloc[[1,2,4],[0,3]]

    通过布尔值过滤:

    • df[df['A']>0]
    • df[df['A'].isin([1,3,5])]
      In [237]: df['one'].isin([1.0,3.0])
      Out[237]: 
      a     True
      b    False
      c     True
      d    False
      Name: one, dtype: bool
    • df[df<0] = 0

    DataFrame数据对齐与缺失数据:

    DataFrame处理缺失数据的方法:

    • dropna(axis=0, how='any',…) #默认删一行,axis = o 删行,axis = 1 删列
    • In [261]: df
      Out[261]: 
         one  two    1
      a  1.0  2.0  NaN
      b  2.0  1.0  1.0
      c  3.0  3.0  NaN
      d  NaN  NaN  NaN
      3  1.0  1.0  1.0
      
      In [262]: df.dropna()
      Out[262]: 
         one  two    1
      b  2.0  1.0  1.0
      3  1.0  1.0  1.0
      
      In [263]: df.dropna(axis=1)
      Out[263]: 
      Empty DataFrame
      Columns: []
      Index: [a, b, c, d, 3]
    • fillna()
    • isnull()
    • notnull()
    In [223]: df
    Out[223]: 
       one  two
    a  1.0    2
    b  2.0    1
    c  3.0    3
    d  NaN    4
    
    In [224]: df.fillna(11)
    Out[224]: 
        one  two
    a   1.0    2
    b   2.0    1
    c   3.0    3
    d  11.0    4

    pandas常用方法(适用Series和DataFrame):

    • mean(axis=0,skipna=False)
    • sum(axis=1)
    • sort_index(axis, …, ascending) 按行或列索引排序
    • sort_values(by, axis, ascending) 按值排序
    • NumPy的通用函数同样适用于pandas 
    • apply(func, axis=0) 将自定义函数应用在各行或者各列上 ,func可返回标量或者Series
    • applymap(func) 将函数应用在DataFrame各个元素上
    • map(func) 将函数应用在Series各个元素上

    层次化索引

    • 层次化索引是Pandas的一项重要功能,它使我们能够在一个轴上拥有多个索引级别。
    • 例:data=pd.Series(np.random.rand(9), index=[['a', 'a', 'a', 'b', 'b', 'b', 'c', 'c', 'c'], [1,2,3,1,2,3,1,2,3]])

    从文件读取

    • 读取文件:从文件名、URL、文件对象中加载数据
      • read_csv 默认分隔符为csv
      • read_table 默认分隔符为
      • read_excel 读取excel文件
    • 读取文件函数主要参数:
      • sep 指定分隔符,可用正则表达式如's+'
      • header=None 指定文件无列名
      • name 指定列名
      • index_col 指定某列作为索引
      • skip_row 指定跳过某些行
      • na_values 指定某些字符串表示缺失值
      • parse_dates 指定某些列是否被解析为日期,布尔值或列表
    • 写入到文件:
      • to_csv
    • 写入文件函数的主要参数:
      • sep
      • na_rep 指定缺失值转换的字符串,默认为空字符串
      • header=False 不输出列名一行
      • index=False 不输出行索引一列
    • 其他文件类型:json, XML, HTML, 数据库
    • pandas转换为二进制文件格式(pickle):
      • save
      • load

    时间对象处理(常作为索引):

    • 第三方包:dateutil
      • dateutil.parser.parse()
    • 成组处理日期:pandas
      • pd.to_datetime(['2001-01-01', '2002-02-02'])
    • 产生时间对象数组:date_range
      • start 开始时间
      • end 结束时间
      • periods 时间长度
      • freq 时间频率,默认为'D',可选H(our),W(eek),B(usiness),S(emi-)M(onth),(min)T(es), S(econd), A(year),…

    时间序列就是以时间对象为索引的Series或DataFrame。

    • datetime对象作为索引时是存储在DatetimeIndex对象中的。
    • 时间序列特殊功能:
      • 传入“年”或“年月”作为切片方式
      • 传入日期范围作为切片方式
    df = pd.read_csv('601318.csv',index_col='date',parse_dates=['date'],)


    In [266]: df

    Out[266]: 

                Unnamed: 0    open   close    high     low      volume    code

    date                                                                      

    2007-03-01           0  22.074  20.657  22.503  20.220  1977633.51  601318

    2007-03-02           1  20.750  20.489  20.944  20.256   425048.32  601318

    2007-03-05           2  20.300  19.593  20.384  19.218   419196.74  601318

    2007-03-06           3  19.426  19.977  20.308  19.315   297727.88  601318

    2007-03-07           4  19.995  20.520  20.706  19.827   287463.78  601318

    2007-03-08           5  20.353  20.273  20.454  20.167   130983.83  601318

    2007-03-09           6  20.264  20.101  20.353  19.735   160887.79  601318

    2007-03-12           7  19.999  19.739  19.999  19.646   145353.06  601318

    2007-03-13           8  19.783  19.818  19.982  19.699   102319.68  601318

    2007-03-14           9  19.558  19.841  19.911  19.333   173306.56  601318

    2007-03-15          10  20.097  19.849  20.525  19.779   152521.90  601318

    2007-03-16          11  19.863  19.960  20.286  19.602   227547.24  601318

    2007-03-20          12  20.662  20.211  20.715  20.088   222026.87  601318

    2007-03-21          13  20.220  19.911  20.308  19.823   136728.32  601318

    2007-03-22          14  20.066  20.026  20.273  19.969   167509.84  601318

    2007-03-23          15  20.017  19.938  20.101  19.739   139810.14  601318

    2007-03-26          16  19.955  20.282  20.397  19.946   223266.79  601318

    2007-03-27          17  20.216  20.269  20.467  20.145   139338.19  601318

    2007-03-28          18  20.264  20.565  20.706  20.123   258263.69  601318

    df[df['close']>df['open']] #时间索引的好处
  • 相关阅读:
    PostgreSQL数据库管理:定期vacuum
    关于压力测试的思路
    作业自动提示功能设计思路
    This system is not registered with RHN
    读《高性能建站指南》(上)
    Ubuntu下PostgreSQL数据库集群(PL/Proxy)配置方法
    PG SQL数据库读写分离的思路
    ASP.NET知识点的明晰(非原创,东拼西凑的,向这些内容的原创者致敬)
    [转]Effective C#原则4:用条件属性而不是#if
    如何在Word文档中插入一条分隔线?
  • 原文地址:https://www.cnblogs.com/mona524/p/7755395.html
Copyright © 2011-2022 走看看