zoukankan      html  css  js  c++  java
  • 快速学习 Python 数据分析包 之 pandas

      最近在看时间序列分析的一些东西,中间普遍用到一个叫pandas的包,因此单独拿出时间来进行学习。

      参见 pandas 官方文档 http://pandas.pydata.org/pandas-docs/stable/index.html

      以及相关博客 http://www.cnblogs.com/chaosimple/p/4153083.html

    Pandas介绍

      Pandas是python的一个数据分析包,最初由AQR Capital Management于2008年4月开发,并于2009年底开源出来,目前由专注于Python数据包开发的PyData开发team继续开发和维护,属于PyData项目的一部分。Pandas最初被作为金融数据分析工具而开发出来,因此,pandas为时间序列分析提供了很好的支持。 

      Pandas 是基于 Numpy 构建的含有更高级数据结构和工具的数据分析包,类似于 Numpy 的核心是 ndarray,pandas 也是围绕着 Series 和 DataFrame 两个核心数据结构展开的 。

      Series 和 DataFrame 分别对应于一维的序列和二维的表结构。

      通常用下列方式来引入需要的包

    1 import pandas as pd
    2 import numpy as np
    3 import matplotlib.pyplot as plt

    Series 

      Series 可以看做一个定长的有序字典,基本任意的一维数据都可以用来构造 Series 对象。
      可以通过传递一个list对象来创建一个Series,pandas会默认创建整型索引
     
    >>> s = pd.Series([1,2,3.0,'a','bc'])
    >>> s
    0     1
    1     2
    2     3
    3     a
    4    bc
    dtype: object

      Series 对象包含两个主要的属性:index 和 values,分别为上例中左右两列。因为传给构造器的是一个List,所以 index 的值是从 0 起递增的整数,如果传入的是一个类字典的键值对结构,就会生成 index-value 对应的 Series;或者在初始化的时候以关键字参数显式指定一个 index 对象。

    
    

    >>> s = pd.Series(data=[1,2,3.0,'a','bc'],index = ['a','b','c','d','e'])
    >>> s.name = 'example'
    >>> s.index.name='New_index'
    >>> s
    New_index
    a 1
    b 2
    c 3
    d a
    e bc
    Name: example, dtype: object

    >>> s.index
    Index([u'a', u'b', u'c', u'd', u'e'], dtype='object')
    >>> s.values
    array([1, 2, 3.0, 'a', 'bc'], dtype=object)

      Series 对象的元素会严格依照给出的 index 构建,这意味着:如果 data 参数是有键值对的,那么只有 index 中含有的键会被使用;以及如果 data 中缺少响应的键,即使给出 NaN 值,这个键也会被添加。

      注意 Series 的 index 和 values 的元素之间虽然存在对应关系,但这与字典的映射不同。index 和 values 实际仍为互相独立的 ndarray 数组,因此 Series 对象的性能完全 ok。

      Series 这种使用键值对的数据结构最大的好处在于,Series 间进行算术运算时,index 会自动对齐。

      Series 与 index 都有 name 属性。

    DataFrame

      DataFrame 是一个表格型的数据结构,它含有一组有序的列(类似于 index),每列可以是不同的值类型(不像 ndarray 只能有一个 dtype)。基本上可以把 DataFrame 看成是共享同一个 index 的 Series 的集合。

      DataFrame 的构造方法与 Series 类似,只不过可以同时接受多条一维数据源,每一条都会成为单独的一列

      可以通过传递一个能够被转换成类似序列结构的字典对象来创建一个DataFrame

    data_dic = ({ 'A' : 1.,
                'B' : pd.Timestamp('20130102'),
                'C' : pd.Series(1,index=list(range(4)),dtype='float32'),
                'D' : np.array([3] * 4,dtype='int32'),
                'E' : pd.Categorical(["test","train","test","train"]),
                'F' : 'foo' })
    df = pd.DataFrame(data_dic)
    >>> df
       A          B  C  D      E    F
    0  1 2013-01-02  1  3   test  foo
    1  1 2013-01-02  1  3  train  foo
    2  1 2013-01-02  1  3   test  foo
    3  1 2013-01-02  1  3  train  foo

      虽然data_dic 是个字典,但字典的键 A B C D 并非充当 DataFrame 中的 index 的角色,而是 Series 的 “name” 属性。这里生成的 DataFrame 的index 是 0 1 2 3。

    >>> df.index
    Int64Index([0, 1, 2, 3], dtype='int64')
    >>> df.B
    0   2013-01-02
    1   2013-01-02
    2   2013-01-02
    3   2013-01-02
    Name: B, dtype: datetime64[ns]

      可以通过 df.B 这样的形式访问 A B C D 代表的不同的 Series

      也可以通过传递一个numpy array,时间索引以及列标签来创建一个DataFrame

    dates = pd.date_range('20130101', periods=6)
    df2 = pd.DataFrame(np.random.randn(6,4), index=dates, columns=list('ABCD'))
    >>> df2
                       A         B         C         D
    2013-01-01 -0.941915 -1.304691 -0.837790 -0.805101
    2013-01-02 -0.665522 -2.935955  1.249425  0.902390
    2013-01-03 -0.419268  0.750735 -0.547377 -0.075151
    2013-01-04  1.362527 -1.059686 -1.564129 -1.267506
    2013-01-05  0.719452 -0.152727  0.319914 -0.448535
    2013-01-06 -0.863264 -0.548317  0.277112  1.233825
    >>> df.index
    Int64Index([0, 1, 2, 3], dtype='int64')
    >>> df.values
    array([[1.0, Timestamp('2013-01-02 00:00:00'), 1.0, 3, 'test', 'foo'],
           [1.0, Timestamp('2013-01-02 00:00:00'), 1.0, 3, 'train', 'foo'],
           [1.0, Timestamp('2013-01-02 00:00:00'), 1.0, 3, 'test', 'foo'],
           [1.0, Timestamp('2013-01-02 00:00:00'), 1.0, 3, 'train', 'foo']], dtype=object)

     基本操作

       1. head()和tail()查看头和尾部的某几行

    >>> df.head(2)
       A          B  C  D      E    F
    0  1 2013-01-02  1  3   test  foo
    1  1 2013-01-02  1  3  train  foo
    
    >>> df.tail(2)
       A          B  C  D      E    F
    2  1 2013-01-02  1  3   test  foo
    3  1 2013-01-02  1  3  train  foo

      2.  describe()快速统计

    >>> df.describe()
           A  C  D
    count  4  4  4
    mean   1  1  3
    std    0  0  0
    min    1  1  3
    25%    1  1  3
    50%    1  1  3
    75%    1  1  3
    max    1  1  3

      3. 转置

    >>> df.T
                         0                    1                    2  
    A                    1                    1                    1   
    B  2013-01-02 00:00:00  2013-01-02 00:00:00  2013-01-02 00:00:00   
    C                    1                    1                    1   
    D                    3                    3                    3   
    E                 test                train                 test   
    F                  foo                  foo                  foo   
    
                         3  
    A                    1  
    B  2013-01-02 00:00:00  
    C                    1  
    D                    3  
    E                train  
    F                  foo  

      4. 按轴排序

    >>> df.sort_index(axis=1,ascending=True)
       A          B  C  D      E    F
    0  1 2013-01-02  1  3   test  foo
    1  1 2013-01-02  1  3  train  foo
    2  1 2013-01-02  1  3   test  foo
    3  1 2013-01-02  1  3  train  foo
    >>> df.sort_index(axis=1,ascending=False)
         F      E  D  C          B  A
    0  foo   test  3  1 2013-01-02  1
    1  foo  train  3  1 2013-01-02  1
    2  foo   test  3  1 2013-01-02  1
    3  foo  train  3  1 2013-01-02  1

      5. 按值进行排序

    >>> df2.sort(columns='B',ascending=True)
                       A         B         C         D
    2013-01-02 -0.665522 -2.935955  1.249425  0.902390
    2013-01-01 -0.941915 -1.304691 -0.837790 -0.805101
    2013-01-04  1.362527 -1.059686 -1.564129 -1.267506
    2013-01-06 -0.863264 -0.548317  0.277112  1.233825
    2013-01-05  0.719452 -0.152727  0.319914 -0.448535
    2013-01-03 -0.419268  0.750735 -0.547377 -0.075151
    >>> df2.sort(columns='B',ascending=False)
                       A         B         C         D
    2013-01-03 -0.419268  0.750735 -0.547377 -0.075151
    2013-01-05  0.719452 -0.152727  0.319914 -0.448535
    2013-01-06 -0.863264 -0.548317  0.277112  1.233825
    2013-01-04  1.362527 -1.059686 -1.564129 -1.267506
    2013-01-01 -0.941915 -1.304691 -0.837790 -0.805101
    2013-01-02 -0.665522 -2.935955  1.249425  0.902390

     时间序列

      Pandas在对频率转换进行重新采样时拥有简单、强大且高效的功能(如将按秒采样的数据转换为按5分钟为单位进行采样的数据)。这种操作在金融领域非常常见。

    >>> rng = pd.date_range('1/1/2011', periods=100, freq='S')
    >>> rng[:2]
    <class 'pandas.tseries.index.DatetimeIndex'>
    [2011-01-01 00:00:00, 2011-01-01 00:00:01]
    Length: 2, Freq: S, Timezone: None
    >>> ts = pd.Series(np.random.randint(0,500,len(rng)),index=rng)
    >>> ts.resample('5Min',how='sum')
    2011-01-01    28117
    Freq: 5T, dtype: int32

      日期和时间戳之间的转换

    >>> prng = pd.period_range('1990Q1','2000Q4',freq='Q-NOV')
    >>> ts = pd.Series(np.random.randn(len(prng)),prng)
    >>> ts.head()
    1990Q1    0.598308
    1990Q2   -0.921216
    1990Q3   -1.370614
    1990Q4    1.962697
    1991Q1   -0.019205
    Freq: Q-NOV, dtype: float64
    >>> ts.index = (prng.asfreq('M','e')+1).asfreq('H','s')+9
    >>> ts.head()
    1990-03-01 09:00    0.598308
    1990-06-01 09:00   -0.921216
    1990-09-01 09:00   -1.370614
    1990-12-01 09:00    1.962697
    1991-03-01 09:00   -0.019205
    Freq: H, dtype: float64
  • 相关阅读:
    断点续传的原理
    中国无线音乐搜索综合测评结果
    从头开始学jsp
    SQLServer和Oracle常用函数对比
    Asp.net程序重启自己
    What Can I do if "The type initializer for 'Emgu.CV.CvInvoke' threw an exception"?
    C++Builder2010多线程调用WebService的问题
    Desmon and Penny
    C#显示摄像头预览
    甲骨文78亿美金并购全球第二芯片商AMD
  • 原文地址:https://www.cnblogs.com/zhubinwang/p/5072950.html
Copyright © 2011-2022 走看看