python做数据分析的包_快速学习 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 importpandas as pd2 importnumpy as np3 import matplotlib.pyplot as plt

Series

Series 可以看做一个定长的有序字典,基本任意的一维数据都可以用来构造 Series 对象。

可以通过传递一个list对象来创建一个Series,pandas会默认创建整型索引

>>> s = pd.Series([1,2,3.0,'a','bc'])>>>s

01

1 2

2 3

3a4bc

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

01 2013-01-02 1 3test foo1 1 2013-01-02 1 3train foo2 1 2013-01-02 1 3test foo3 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

02013-01-02

1 2013-01-02

2 2013-01-02

3 2013-01-02Name: 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 D2013-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

01 2013-01-02 1 3test foo1 1 2013-01-02 1 3train foo>>> df.tail(2)

A B C D E F2 1 2013-01-02 1 3test foo3 1 2013-01-02 1 3 train foo

2. describe()快速统计

>>>df.describe()

A C D

count4 4 4mean1 1 3std 0 0 0

min1 1 3

25% 1 1 3

50% 1 1 3

75% 1 1 3max1 1 3

3. 转置

>>>df.T

01 2\

A1 1 1B2013-01-02 00:00:00 2013-01-02 00:00:00 2013-01-02 00:00:00C1 1 1D3 3 3E test train test

F foo foo foo3A1B2013-01-02 00:00:00C1D3E train

F foo

4. 按轴排序

>>> df.sort_index(axis=1,ascending=True)

A B C D E F

01 2013-01-02 1 3test foo1 1 2013-01-02 1 3train foo2 1 2013-01-02 1 3test foo3 1 2013-01-02 1 3train foo>>> df.sort_index(axis=1,ascending=False)

F E D C B A

0 foo test3 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 D2013-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 D2013-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][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 28117Freq: 5T, dtype: int32

日期和时间戳之间的转换

>>> prng = pd.period_range('1990Q1','2000Q4',freq='Q-NOV')>>> ts =pd.Series(np.random.randn(len(prng)),prng)>>>ts.head()

1990Q10.5983081990Q2-0.9212161990Q3-1.3706141990Q41.9626971991Q1-0.019205Freq: 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.019205Freq: H, dtype: float64

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值