├── 10min.html ├── CNAME ├── advanced.html ├── api.html ├── basics.html ├── categorical.html ├── comparison_with_r.html ├── comparison_with_sas.html ├── comparison_with_sql.html ├── computation.html ├── contributing.html ├── cookbook.html ├── dsintro.html ├── ecosystem.html ├── enhancingperf.html ├── faq.html ├── gotchas.html ├── groupby.html ├── index.html ├── indexing.html ├── install.html ├── internals.html ├── io.html ├── merging.html ├── missing_data.html ├── options.html ├── overview.html ├── r_interface.html ├── release.html ├── remote_data.html ├── reshaping.html ├── sparse.html ├── style.html ├── text.html ├── timedeltas.html ├── timeseries.html ├── tutorials.html ├── visualization.html └── whatsnew.html /CNAME: -------------------------------------------------------------------------------- 1 | pandas.apachecn.org -------------------------------------------------------------------------------- /ecosystem.html: -------------------------------------------------------------------------------- 1 | 2 |

pandas Ecosystem

3 |
4 |

原文:http://pandas.pydata.org/pandas-docs/stable/ecosystem.html

5 |

译者:飞龙 UsyiyiCN

6 |

校对:(虚位以待)

7 |
8 | 9 |

越来越多的软件包在大熊猫上构建,以满足数据准备,分析和可视化的特定需求。这是令人鼓舞的,因为它意味着熊猫不仅帮助用户处理他们的数据任务,而且它为开发者提供了一个更好的起点,构建强大和更集中的数据工具。创建补充熊猫功能的图书馆也允许熊猫开发继续专注于它的原始要求。

10 |

11 |

我们希望让用户更容易找到这些项目,如果您知道您认为应该在此列表中的其他实质性项目,请告诉我们。

12 |
13 |

Statistics and Machine Learning

14 |
15 |

Statsmodels

16 |

Statsmodels是着名的python“统计和计量经济学图书馆”,它与熊猫有着长期的特殊关系。Statsmodels提供强大的统计,计量经济学,分析和建模功能,超出了熊猫的范围。Statsmodels利用pandas对象作为计算的基础数据容器。

17 |
18 |
19 |

sklearn-pandas

20 |

scikit-learn ML管道中使用pandas DataFrames。

21 |
22 |
23 |
24 |

Visualization

25 |
26 |

Bokeh

27 |

Bokeh是一个用于大型数据集的Python交互式可视化库,本地使用最新的Web技术。其目标是以Protovis / D3的风格提供优雅,简洁的新颖图形构造,同时为大型数据向瘦客户端提供高性能交互性。

28 |
29 |
30 |

yhat/ggplot

31 |

Hadley Wickham的ggplot2是R语言的基础探索性可视化包。基于“图形语法”它提供了一个强大的,声明性和极其一般的方式来生成任何类型的数据的定制图。这真的很不可思议。各种实现到其他语言是可用的,但一个忠实的实现python用户长期以来一直缺失。虽然仍然年轻(截至2014年1月),yhat / ggplot项目已经在这个方向上迅速发展。

32 |
33 |
34 |

Seaborn

35 |

虽然熊猫有相当多的“只是绘图”的功能内置,可视化,特别是统计图形是一个广泛的领域,具有悠久的传统和大量的地面覆盖。Seaborn项目构建在pandas和matplotlib之上,以便于绘制更多高级类型的数据,然后提供由pandas提供的数据。

36 |
37 |
38 |

Vincent

39 |

Vincent项目利用Vega(进而利用d3)创建图表。虽然功能,从2016年夏天Vincent项目在两年内没有更新,不太可能收到进一步更新

40 |
41 |
42 |

IPython Vega

43 |

像Vincent一样,IPython Vega项目利用Vega创建图,但主要针对IPython Notebook环境。

44 |
45 |
46 |

Plotly

47 |

Plotly的 Python API可提供互动数字和网页分享功能。使用WebGL和D3.js来呈现地图,2D,3D和实况流图。该库支持直接从pandas DataFrame和基于云的协作绘制。matplotlib,ggplot for Python和Seaborn的用户可以将图形转换为基于Web的互动图。绘图可以在IPython笔记本中绘制,使用R或MATLAB编辑,在GUI中修改,或嵌入在应用程序和仪表板中。Plotly可免费无限制分享,且拥有离线内部帐户供私人使用。

48 |
49 |
50 |

Pandas-Qt

51 |

从主熊猫库跳出,Pandas-Qt库可以在PyQt4和PySide应用程序中实现DataFrame可视化和操作。

52 |
53 |
54 |
55 |

IDE

56 |
57 |

IPython

58 |

IPython是一个交互式命令shell和分布式计算环境。IPython Notebook是一个用于创建IPython笔记本的Web应用程序。IPython notebook是一个JSON文档,包含输入/输出单元格的有序列表,其中可以包含代码,文本,数学,图表和富媒体。IPython Notebook可以通过Web界面中的“下载为”和ipython t1转换为多种开放标准输出格式(HTML,HTML演示文稿幻灯片,LaTeX,PDF,ReStructuredText,Markdown, > nbconvert

59 |

Pandas DataFrames实现了IPython Notebook用于显示(缩写)HTML表的_repr_html_方法。(注意:HTML表格可能与非HTML IPython输出格式兼容,也可能不兼容)。

60 |
61 |
62 |

quantopian/qgrid

63 |

qgrid是“用于排序和过滤IPython Notebook中的DataFrames的交互式网格”,使用SlickGrid构建。

64 |
65 |
66 |

Spyder

67 |

Spyder是一个跨平台的基于Qt的开源Python IDE,具有编辑,测试,调试和内省功能。Spyder现在可以内省和显示Pandas DataFrames,并显示“列方式最小/最大值和全局最小/最大着色”。

68 |
69 |
70 |
71 |

API

72 |
73 |

pandas-datareader

74 |

pandas-datareader是用于pandas的远程数据访问库。pandas.io from pandas < 0.17.0 is now refactored/split-off to and importable from pandas_datareader (PyPI:pandas-datareader). 许多/大多数支持的API在pandas-datareader docs中至少有一个文档段落:

75 |

以下数据Feed可用:

76 |
77 |
    78 |
  • 雅虎金融
  • 79 |
  • Google财经
  • 80 |
  • FRED
  • 81 |
  • Fama /法语
  • 82 |
  • 世界银行
  • 83 |
  • 经合组织
  • 84 |
  • 欧洲统计局
  • 85 |
  • EDGAR索引
  • 86 |
87 |
88 |
89 |
90 |

quandl/Python

91 |

Quandl API for Python包装Quandl REST API以返回带有时间序列索引的Pandas DataFrames。

92 |
93 |
94 |

pydatastream

95 |

PyDatastream是Thomson Dataworks Enterprise(DWE / Datastream) SOAP API的Python接口,用于返回带有财务数据的带索引的Pandas DataFrames或面板。此程序包需要此API的有效凭据(非免费)。

96 |
97 |
98 |

pandaSDMX

99 |

pandaSDMX是一个可扩展的库,用于检索和获取在SDMX 2.1中传播的统计数据和元数据。本标准目前由欧洲统计局(欧盟统计局)和欧洲中央银行(欧洲中央银行)支持。数据集可以作为pandas系列或多索引的DataFrames返回。

100 |
101 |
102 |

fredapi

103 |

fredapi是由圣路易斯联邦储备银行提供的联邦储备经济数据(FRED)的Python接口。它与包含时间点数据(即历史数据修订)的FRED数据库和ALFRED数据库一起工作。fredapi在python中为FRED HTTP API提供了一个包装器,并且还提供了几种方便的方法来解析和分析来自ALFRED的时间点数据。fredapi使用pandas并返回一个Series或DataFrame中的数据。此模块需要FRED API密钥,您可以在FRED网站上免费获取。

104 |
105 |
106 |
107 |

Domain Specific

108 |
109 |

Geopandas

110 |

地理空间扩展了熊猫数据对象,以包括支持几何操作的地理信息。如果你的工作需要地图和地理坐标,你喜欢大熊猫,你应该仔细看看地球圈。

111 |
112 |
113 |

xarray

114 |

xarray通过提供核心熊猫数据结构的N维变量将大熊猫的标记数据功率带到物理科学。它旨在提供一个用于多维数组分析的熊猫和熊猫兼容工具包,而不是熊猫擅长的表格数据。

115 |
116 |
117 |
118 |

Out-of-core

119 |
120 |

Dask

121 |

Dask是一个用于分析的灵活的并行计算库。Dask允许熟悉的DataFrame接口用于核外,并行和分布式计算。

122 |
123 |
124 |

Blaze

125 |

Blaze提供了一个标准API,用于使用各种内存和磁盘后端进行计算:NumPy,Pandas,SQLAlchemy,MongoDB,PyTables,PySpark。

126 |
127 |
128 |

Odo

129 |

Odo提供了用于在不同格式之间移动数据的统一API。它使用pandas自己的read_csv来获取CSV IO,并利用许多现有的包(如PyTables,h5py和pymongo)在非熊猫格式之间移动数据。它的基于图的方法也可以由最终用户扩展自定义格式,可能太具体的odo的核心。

130 |
131 |
132 | -------------------------------------------------------------------------------- /faq.html: -------------------------------------------------------------------------------- 1 | 2 |

Frequently Asked Questions (FAQ)

3 |
4 |

原文:http://pandas.pydata.org/pandas-docs/stable/faq.html

5 |

译者:飞龙 UsyiyiCN

6 |

校对:(虚位以待)

7 |
8 | 9 |
10 |

DataFrame memory usage

11 |

对于pandas版本0.15.0,当使用info方法访问结构数据时,将输出结构数据(包括索引)的内存使用情况。配置选项display.memory_usage(请参阅Options and Settings)指定在调用df.info()

12 |

例如,调用df.info()时会显示以下结构数据的内存使用情况:

13 |
In [1]: dtypes = ['int64', 'float64', 'datetime64[ns]', 'timedelta64[ns]',
 14 |    ...:           'complex128', 'object', 'bool']
 15 |    ...: 
 16 | 
 17 | In [2]: n = 5000
 18 | 
 19 | In [3]: data = dict([ (t, np.random.randint(100, size=n).astype(t))
 20 |    ...:                 for t in dtypes])
 21 |    ...: 
 22 | 
 23 | In [4]: df = pd.DataFrame(data)
 24 | 
 25 | In [5]: df['categorical'] = df['object'].astype('category')
 26 | 
 27 | In [6]: df.info()
 28 | <class 'pandas.core.frame.DataFrame'>
 29 | RangeIndex: 5000 entries, 0 to 4999
 30 | Data columns (total 8 columns):
 31 | bool               5000 non-null bool
 32 | complex128         5000 non-null complex128
 33 | datetime64[ns]     5000 non-null datetime64[ns]
 34 | float64            5000 non-null float64
 35 | int64              5000 non-null int64
 36 | object             5000 non-null object
 37 | timedelta64[ns]    5000 non-null timedelta64[ns]
 38 | categorical        5000 non-null category
 39 | dtypes: bool(1), category(1), complex128(1), datetime64[ns](1), float64(1), int64(1), object(1), timedelta64[ns](1)
 40 | memory usage: 284.1+ KB
 41 | 
42 |
43 |

+符号表示真正的内存使用率可能更高,因为pandas不会计算dtype=object的列中使用的内存。

44 |
45 |

版本0.17.1中的新功能。

46 |
47 |

传递memory_usage='deep'参数,将输出更准确的内存使用情况报告,包含结构数据内存的完全使用情况。这是参数是可选的,因为做更深入的内存检查需要付出更多。

48 |
In [7]: df.info(memory_usage='deep')
 49 | <class 'pandas.core.frame.DataFrame'>
 50 | RangeIndex: 5000 entries, 0 to 4999
 51 | Data columns (total 8 columns):
 52 | bool               5000 non-null bool
 53 | complex128         5000 non-null complex128
 54 | datetime64[ns]     5000 non-null datetime64[ns]
 55 | float64            5000 non-null float64
 56 | int64              5000 non-null int64
 57 | object             5000 non-null object
 58 | timedelta64[ns]    5000 non-null timedelta64[ns]
 59 | categorical        5000 non-null category
 60 | dtypes: bool(1), category(1), complex128(1), datetime64[ns](1), float64(1), int64(1), object(1), timedelta64[ns](1)
 61 | memory usage: 401.2 KB
 62 | 
63 |
64 |

默认情况下,display选项设置为True,但是可以在调用df.info()时传递memory_usage参数来显式覆盖。

65 |

通过调用memory_usage方法可以找到每列的内存使用情况。这将返回一个具有以字节表示的列的名称和内存使用情况的索引。对于上面的数据帧,可以使用memory_usage方法找到每列数据的内存使用情况和结构数据的总内存使用情况:

66 |
In [8]: df.memory_usage()
 67 | Out[8]: 
 68 | Index                 72
 69 | bool                5000
 70 | complex128         80000
 71 | datetime64[ns]     40000
 72 | float64            40000
 73 | int64              40000
 74 | object             40000
 75 | timedelta64[ns]    40000
 76 | categorical         5800
 77 | dtype: int64
 78 | 
 79 | # total memory usage of dataframe
 80 | In [9]: df.memory_usage().sum()
 81 | Out[9]: 290872
 82 | 
83 |
84 |

默认情况下,结构数据索引的内存使用情况显示在返回的Series中,可以通过传递index=False参数来去除索引的内存使用情况:

85 |
In [10]: df.memory_usage(index=False)
 86 | Out[10]: 
 87 | bool                5000
 88 | complex128         80000
 89 | datetime64[ns]     40000
 90 | float64            40000
 91 | int64              40000
 92 | object             40000
 93 | timedelta64[ns]    40000
 94 | categorical         5800
 95 | dtype: int64
 96 | 
97 |
98 |

info方法显示的内存使用情况利用memory_usage方法来确定结构数据的内存使用情况,同时还以人类可读单位格式化输出(base-2表示;即1KB = 1024字节)。

99 |

另请参见Categorical Memory Usage

100 |
101 |
102 |

Byte-Ordering Issues

103 |

有时,您可能必须处理在机器上创建的数据具有与运行Python不同的字节顺序。要处理这个问题,应该使用类似于以下内容的方法将底层NumPy数组转换为本地系统字节顺序之后传递给Series / DataFrame / Panel构造函数:

104 |
In [11]: x = np.array(list(range(10)), '>i4') # big endian
105 | 
106 | In [12]: newx = x.byteswap().newbyteorder() # force native byteorder
107 | 
108 | In [13]: s = pd.Series(newx)
109 | 
110 |
111 |

有关详细信息,请参阅有关字节顺序的NumPy文档

112 |
113 |
114 |

Visualizing Data in Qt applications

115 |

在pandas中没有这种可视化的支持。但是,外部模块pandas-qt提供这样的功能。

116 |
117 | -------------------------------------------------------------------------------- /index.html: -------------------------------------------------------------------------------- 1 | 2 |

pandas:强大的Python数据分析工具包

3 |
4 |

原文:http://pandas.pydata.org/pandas-docs/stable/index.html

5 |

译者:飞龙 UsyiyiCN

6 |

校对:(虚位以待)

7 |
8 | 9 |

日期:2016年12月24日版本:0.19.2

10 |

二进制安装: http://pypi.python.org/pypi/pandas

11 |

源代码仓库: http://github.com/pydata/pandas

12 |

问题&想法: https://github.com/pydata/pandas/issues

13 |

Q&A支持: http://stackoverflow.com/questions/tagged/pandas

14 |

开发人员邮件列表: http://groups.google.com/group/pydata

15 |

文档 EPUB 格式

16 |

pandas是一个提供快速,灵活和表达性数据结构的Python包,旨在使“关系”或“标记”数据变得简单直观。它旨在成为在Python中进行实用的真实世界数据分析的基本高级构建块。此外,它的更广泛的目标是成为最强大和最灵活的任何语言的开源数据分析/操作工具。它已经很好地朝着这个目标前进了。

17 |

pandas非常适合许多不同类型的数据:

18 |
19 |
25 |
26 |

pandas的两个主要数据结构Series(一维)和DataFrame(二维)处理了金融,统计,社会中的绝大多数典型用例科学,以及许多工程领域。对于R用户,DataFrame提供R的data.frame所有功能及其他功能。pandas建立在NumPy之上,旨在包含更多其他第三方库并与之集成为优秀的科学计算环境。

27 |

这里只是几个pandas做得很好的事情:

28 |
29 |
42 |
43 |

许多此处原则是为了解决在使用其他语言/科学研究环境时常常所遇到的不足。对于数据科学家,处理数据通常分为多个阶段:清理和清理数据,分析/建模,然后将分析的结果组织成适合于绘图或表格显示的形式。pandas是处理所有这些任务的理想工具。

44 |

其他一些注释

45 |
46 |
51 |
52 |
53 |

注意

54 |

本文档假定你熟悉NumPy。如果你还没有熟练使用NumPy或者根本没用过numpy,请先花一些时间学习NumPy

55 |
56 |

有关库中的内容的更多详细信息,请参阅软件包概述。

57 |
58 | 97 |
98 | -------------------------------------------------------------------------------- /install.html: -------------------------------------------------------------------------------- 1 | 2 |

Installation

3 |
4 |

原文:http://pandas.pydata.org/pandas-docs/stable/install.html

5 |

译者:飞龙 UsyiyiCN

6 |

校对:(虚位以待)

7 |
8 | 9 |

大多数用户安装 pandas 的最简单的方法是将其安装为 Anaconda 发行版的一部分,这是一个用于数据分析和科学计算的跨平台发行版。这是大多数 pandas 用户选择的安装方式

10 |

此外这里还提供了从源码,PyPI,各种Linux发行版或开发版本安装的说明。

11 |
12 |

支持的 Python 版本

13 |

官方Python 2.7,3.4,3.5和3.6

14 |
15 |
16 |

安装 pandas

17 |
18 |

最简单的使用pandas的方法(无需安装)!

19 |

最简单开始尝试pandas方式,不需要安装pandas,方式如下

20 |

Wakari是一项免费服务,可在云中提供托管的IPython Notebook服务。

21 |

只需创建一个帐户,即可在几分钟内通过IPython Notebook在浏览器中访问pandas。

22 |
23 |
24 |

在 Anaconda 中安装 pandas

25 |

对于没有经验的用户安装Pandas、NumPySciPy数据科学分析体系的其余部分可能有点困难。

26 |

最简单的方法不仅安装pandas,而且还安装Python和构成SciPy辅助(IPythonNumPyMatplotlib,...)与用于数据分析和科学计算的跨平台(Linux,Mac OS X,Windows)Python分发版Anaconda

27 |

运行简单的安装程序后,用户将可以访问pandas和SciPy体系的其余部分,而无需安装任何其他内容,无需等待任何软件编译。

28 |

可在此处找到Anaconda 的安装说明

29 |

作为Anaconda分发一部分的软件包的完整列表可在此处找到

30 |

安装Anaconda的另一个好处是,你不需要管理员权限安装它,它会安装在用户的主目录,这也使得在日后删除Anaconda(只是删除该文件夹)变得简单。

31 |
32 |
33 |

在 Miniconda 中安装 pandas

34 |

上一节概述了如何将 pandas 安装为Anaconda发行版的一部分。然而,这种方法意味着您将安装超过一百个软件包,并且涉及下载大小为几百兆字节的安装程序。

35 |

如果您想要更多地控制哪些软件包或者有限的互联网带宽,那么使用Miniconda安装 pandas 可能是一个更好的解决方案。

36 |

Conda是基于Anaconda分发的软件包管理器。它是一个跨平台和语言不可知的包管理器(它可以扮演类似于pip和virtualenv组合的角色)。

37 |

Miniconda允许创建最小的自包含Python安装,然后使用Conda命令安装其他软件包。

38 |

首先,您需要安装Conda并下载并运行​​ Miniconda才能为您完成此操作。可在此处找到安装程序

39 |

下一步是创建一个新的conda环境(这些类似于virtualenv,但它们也允许您精确指定要安装的Python版本)。从终端窗口运行以下命令:

40 |
conda create -n name_of_my_env python
 41 | 
42 |
43 |

这将创建一个只安装了Python的最小环境。要将你自己放在这个环境中运行:

44 |
source activate name_of_my_env
 45 | 
46 |
47 |

在Windows上,命令是:

48 |
activate name_of_my_env
 49 | 
50 |
51 |

所需的最后一步是安装pandas。可以使用以下命令完成:

52 |
conda install pandas
 53 | 
54 |
55 |

要安装特定的pandas版本:

56 |
conda install pandas=0.13.1
 57 | 
58 |
59 |

要安装其他软件包,例如IPython:

60 |
conda install ipython
 61 | 
62 |
63 |

要安装完整的Anaconda发行版:

64 |
conda install anaconda
 65 | 
66 |
67 |

如果你需要任何可用的pip,但不能conda,只需安装pip,并使用pip安装这些软件包:

68 |
conda install pip
 69 | pip install django
 70 | 
71 |
72 |
73 |
74 |

从 PyPI 安装

75 |

pandas还可以通过pip从PyPI安装。

76 |
pip install pandas
 77 | 
78 |
79 |

这可能需要安装一些依赖项,包括NumPy,将需要一个编译器来编译所需的代码位,并且可能需要几分钟时间才能完成。

80 |
81 |
82 |

Installing using your Linux distribution’s package manager.

83 |

此表中的命令将从您的分发中安装用于Python 2的pandas。要为Python 3安装pandas,您可能需要使用包python3-pandas

84 | 85 | 86 | 87 | 88 | 89 | 90 | 91 | 92 | 93 | 94 | 95 | 96 | 97 | 98 | 99 | 100 | 101 | 102 | 103 | 104 | 105 | 106 | 107 | 108 | 109 | 110 | 111 | 112 | 113 | 114 | 115 | 116 | 117 | 118 | 119 | 120 | 121 | 122 | 123 | 124 | 125 | 126 | 127 | 128 | 129 | 130 | 131 | 132 | 133 | 134 | 135 |
分配状态下载/ Repository链接安装方法
Debian稳定官方Debian存储库sudo apt-get 安装 python-pandas
Debian和Ubuntuunstable(最新软件包)NeuroDebiansudo apt-get 安装 python-pandas
Ubuntu稳定官方Ubuntu存储库sudo apt-get 安装 python-pandas
Ubuntu不稳定(每日构建)PythonXY PPA; activate by:sudo add-apt-repository ppa:pythonxy / pythonxy-devel &amp;&amp; > sudo apt-get 更新 sudo apt-get 安装 python-pandas
OpenSuse稳定OpenSuse存储库zypper python-pandas
Fedora稳定官方Fedora存储库dnf 安装 python-pandas
Centos / RHEL稳定EPEL存储库yum 安装 python-pandas
136 |
137 |
138 |

Installing from source

139 |

有关从git源代码树构建的完整说明,请参阅contributing documentation此外,如果您要创建pandas开发环境,请参阅creating a development environment

140 |
141 |
142 |

Running the test suite

143 |

pandas配备了一套详尽的单元测试,涵盖了大约97%的代码库。要在您的计算机上运行它以验证一切是否正常(并且已经安装了所有依赖项,软硬件安装),请确保您已经察觉并运行:

144 |
>>> import pandas as pd
145 | >>> pd.test()
146 | Running unit tests for pandas
147 | pandas version 0.18.0
148 | numpy version 1.10.2
149 | pandas is installed in pandas
150 | Python version 2.7.11 |Continuum Analytics, Inc.|
151 |    (default, Dec  6 2015, 18:57:58) [GCC 4.2.1 (Apple Inc. build 5577)]
152 | nose version 1.3.7
153 | ..................................................................S......
154 | ........S................................................................
155 | .........................................................................
156 | 
157 | ----------------------------------------------------------------------
158 | Ran 9252 tests in 368.339s
159 | 
160 | OK (SKIP=117)
161 | 
162 |
163 |
164 |
165 |
166 |

Dependencies

167 | 173 | 184 |
185 |

可选依赖关系

186 | 254 |
255 |

注意

256 |

没有可选的依赖项,许多有用的功能将不工作。因此,强烈建议您安装这些。AnacondaEnthought Canopy的打包分发可能值得考虑。

257 |
258 |
259 |
260 | -------------------------------------------------------------------------------- /internals.html: -------------------------------------------------------------------------------- 1 | 2 |

Internals

3 |
4 |

原文:http://pandas.pydata.org/pandas-docs/stable/internals.html

5 |

译者:飞龙 UsyiyiCN

6 |

校对:(虚位以待)

7 |
8 | 9 |

本节将介绍一些大熊猫内部。

10 |
11 |

Indexing

12 |

在大熊猫中有一些实现的对象可以作为轴标签的有效容器:

13 | 22 |

有一些功能使得创建常规索引变得容易:

23 | 27 |

首先具有Index类的动机是启用不同的索引实现。这意味着,用户可以实现一个自定义Index子类,它可能更适合于特定应用程序,而不是在pandas中提供的。

28 |

从内部实现的角度来看,Index必须定义的相关方法是以下一个或多个(取决于新对象内部与Index功能):

29 | 41 |
42 |

MultiIndex

43 |

在内部,MultiIndex包含以下几项内容:级别,整数标签和级别名称

44 |
In [1]: index = pd.MultiIndex.from_product([range(3), ['one', 'two']], names=['first', 'second'])
 45 | 
 46 | In [2]: index
 47 | Out[2]: 
 48 | MultiIndex(levels=[[0, 1, 2], [u'one', u'two']],
 49 |            labels=[[0, 0, 1, 1, 2, 2], [0, 1, 0, 1, 0, 1]],
 50 |            names=[u'first', u'second'])
 51 | 
 52 | In [3]: index.levels
 53 | Out[3]: FrozenList([[0, 1, 2], [u'one', u'two']])
 54 | 
 55 | In [4]: index.labels
 56 | Out[4]: FrozenList([[0, 0, 1, 1, 2, 2], [0, 1, 0, 1, 0, 1]])
 57 | 
 58 | In [5]: index.names
 59 | Out[5]: FrozenList([u'first', u'second'])
 60 | 
61 |
62 |

您可能猜测标签确定在索引的每个层上用该位置标识哪个唯一元素。It’s important to note that sortedness is determined solely from the integer labels and does not check (or care) whether the levels themselves are sorted. 幸运的是,构造函数from_tuplesfrom_arrays确保这是真的,但如果你自己计算级别和标签,请小心。

63 |
64 |
65 |
66 |

Subclassing pandas Data Structures

67 |
68 |

警告

69 |

在考虑子类化pandas数据结构之前,有一些更简单的替代方法。

70 |
    71 |
  1. 具有pipe
  2. 72 |
  3. 使用组合请参阅此处
  4. 73 |
74 |
75 |

本节介绍如何子类化pandas数据结构以满足更具体的需求。有2分需要注意:

76 |
    77 |
  1. 覆盖构造函数属性。
  2. 78 |
  3. 定义原始属性
  4. 79 |
80 |
81 |

注意

82 |

你可以在geopandas项目中找到一个很好的例子。

83 |
84 |
85 |

Override Constructor Properties

86 |

每个数据结构都具有指定数据构造函数的构造函数属性。通过覆盖这些属性,您可以通过pandas数据操作来保留定义类。

87 |

有3个构造函数要定义:

88 | 93 |

下表显示了默认情况下pandas数据结构如何定义构造函数属性。

94 | 95 | 96 | 97 | 98 | 99 | 100 | 101 | 102 | 103 | 104 | 105 | 106 | 107 | 108 | 109 | 110 | 111 | 112 | 113 | 114 | 115 | 116 | 117 | 118 | 119 | 120 | 121 | 122 | 123 | 124 | 125 |
属性属性SeriesDataFramePanel
_constructorSeriesDataFramePanel
_constructor_slicedNotImplementedErrorSeriesDataFrame
_constructor_expanddimDataFramePanelNotImplementedError
126 |

下面的示例显示如何定义SubclassedSeriesSubclassedDataFrame覆盖构造函数属性。

127 |
class SubclassedSeries(Series):
128 | 
129 |     @property
130 |     def _constructor(self):
131 |         return SubclassedSeries
132 | 
133 |     @property
134 |     def _constructor_expanddim(self):
135 |         return SubclassedDataFrame
136 | 
137 | class SubclassedDataFrame(DataFrame):
138 | 
139 |     @property
140 |     def _constructor(self):
141 |         return SubclassedDataFrame
142 | 
143 |     @property
144 |     def _constructor_sliced(self):
145 |         return SubclassedSeries
146 | 
147 |
148 |
>>> s = SubclassedSeries([1, 2, 3])
149 | >>> type(s)
150 | <class '__main__.SubclassedSeries'>
151 | 
152 | >>> to_framed = s.to_frame()
153 | >>> type(to_framed)
154 | <class '__main__.SubclassedDataFrame'>
155 | 
156 | >>> df = SubclassedDataFrame({'A', [1, 2, 3], 'B': [4, 5, 6], 'C': [7, 8, 9]})
157 | >>> df
158 |    A  B  C
159 | 0  1  4  7
160 | 1  2  5  8
161 | 2  3  6  9
162 | 
163 | >>> type(df)
164 | <class '__main__.SubclassedDataFrame'>
165 | 
166 | >>> sliced1 = df[['A', 'B']]
167 | >>> sliced1
168 |    A  B
169 | 0  1  4
170 | 1  2  5
171 | 2  3  6
172 | >>> type(sliced1)
173 | <class '__main__.SubclassedDataFrame'>
174 | 
175 | >>> sliced2 = df['A']
176 | >>> sliced2
177 | 0    1
178 | 1    2
179 | 2    3
180 | Name: A, dtype: int64
181 | >>> type(sliced2)
182 | <class '__main__.SubclassedSeries'>
183 | 
184 |
185 |
186 |
187 |

Define Original Properties

188 |

要让原始数据结构具有其他属性,您应该让pandas知道添加了什么属性。pandas将未知属性映射到覆盖__getattribute__的数据名称。定义原始属性可以通过以下两种方式之一完成:

189 |
    190 |
  1. 为不会传递到操作结果的临时属性定义_internal_names_internal_names_set
  2. 191 |
  3. 为将传递到操作结果的正常属性定义_metadata
  4. 192 |
193 |

下面是一个定义2个原始属性的示例,“internal_cache”作为临时属性,“added_property”作为正常属性

194 |
class SubclassedDataFrame2(DataFrame):
195 | 
196 |     # temporary properties
197 |     _internal_names = pd.DataFrame._internal_names + ['internal_cache']
198 |     _internal_names_set = set(_internal_names)
199 | 
200 |     # normal properties
201 |     _metadata = ['added_property']
202 | 
203 |     @property
204 |     def _constructor(self):
205 |         return SubclassedDataFrame2
206 | 
207 |
208 |
>>> df = SubclassedDataFrame2({'A', [1, 2, 3], 'B': [4, 5, 6], 'C': [7, 8, 9]})
209 | >>> df
210 |    A  B  C
211 | 0  1  4  7
212 | 1  2  5  8
213 | 2  3  6  9
214 | 
215 | >>> df.internal_cache = 'cached'
216 | >>> df.added_property = 'property'
217 | 
218 | >>> df.internal_cache
219 | cached
220 | >>> df.added_property
221 | property
222 | 
223 | # properties defined in _internal_names is reset after manipulation
224 | >>> df[['A', 'B']].internal_cache
225 | AttributeError: 'SubclassedDataFrame2' object has no attribute 'internal_cache'
226 | 
227 | # properties defined in _metadata are retained
228 | >>> df[['A', 'B']].added_property
229 | property
230 | 
231 |
232 |
233 |
234 | -------------------------------------------------------------------------------- /overview.html: -------------------------------------------------------------------------------- 1 | 2 |

包概述

3 |
4 |

原文:http://pandas.pydata.org/pandas-docs/stable/overview.html

5 |

译者:飞龙 UsyiyiCN

6 |

校对:(虚位以待)

7 |
8 | 9 |

pandas包含以下内容

10 |
11 |
21 |
22 |
23 |

数据结构一览

24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 |
维度名称描述
1Series1维标记同类型数组
2DataFrame普通2维标记大小可变的表格结构,且列能有不同类型
3Panel普通3维标记,大小可变
51 |
52 |

为什么有不止一种数据结构?

53 |

学习 pandas 数据结构的最好方法是将其作为低维数据的灵活容器。例如,DataFrame 是 Series 的容器,Panel 是 DataFrame 对象的容器。我们希望能够以类似字典的方式从这些容器中插入和删除对象。

54 |

此外,我们将对通用API函数(其考虑时间序列和横截面数据集的典型取向)采取明智的默认行为。当使用ndarrays存储2维和3维数据时,用户在编写函数时会考虑数据集的方向,轴被认为或多或少相等(除非C-或Fortran连续性对性能至关重要)。在pandas中,轴旨在为数据提供更多的语义意义;即,对于特定数据集,可能存在定向数据的“正确”方式。因此,目标是减少在下游功能中编码数据转换所需的精神努力量。

55 |

例如,对于表格数据(DataFrame),考虑索引(行)和而不是轴0和轴1更具语义上的帮助。并且遍历DataFrame的列,因此导致更可读的代码:

56 |
for col in df.columns:
 57 |     series = df[col]
 58 |     # do something with series
 59 | 
60 |
61 |
62 |
63 |
64 |

Mutability and copying of data

65 |

所有的pandas数据结构都是值可变的(它们包含的值可以改变),但不总是size-mutable。Series的长度不可更改,但是,可以将列插入到DataFrame中。然而,绝大多数方法产生新对象并且保持输入数据不变。一般来说,我们喜欢有利于不变性

66 |
67 |
68 |

获得支持

69 |

Pandas问题和想法的第一站是Github问题跟踪器如果你有一个一般的问题,pandas社区专家可以通过Stack Overflow回答。

70 |

更长的讨论发生在开发人员邮件列表上,而Lambda Foundry的商业支持查询应发送到:支持@ lambdafoundry

71 |
72 |
73 |

Credits

74 |

pandas于2008年4月由AQR资本管理它是在2009年年底开源的。2011年底,AQR继续为发展提供资源,并继续提供今天的错误报告。

75 |

自2012年1月起,Lambda Foundry一直提供开发资源,以及商业支持,培训和pandas咨询。

76 |

pandas只是由一组世界各地的人像你一样,贡献了新的代码,错误报告,修复,评论和想法。完整的列表可以在Github上找到

77 |
78 |
79 |

开发团队

80 |

pandas是PyData项目的一部分。PyData开发团队是专注于改进Python数据库的开发人员的集合。协调开发的核心团队可以在Github上找到。如果您有兴趣参与,请访问项目网站

81 |
82 |
83 |

License

84 |
=======
 85 | License
 86 | =======
 87 | 
 88 | pandas is distributed under a 3-clause ("Simplified" or "New") BSD
 89 | license. Parts of NumPy, SciPy, numpydoc, bottleneck, which all have
 90 | BSD-compatible licenses, are included. Their licenses follow the pandas
 91 | license.
 92 | 
 93 | pandas license
 94 | ==============
 95 | 
 96 | Copyright (c) 2011-2012, Lambda Foundry, Inc. and PyData Development Team
 97 | All rights reserved.
 98 | 
 99 | Copyright (c) 2008-2011 AQR Capital Management, LLC
100 | All rights reserved.
101 | 
102 | Redistribution and use in source and binary forms, with or without
103 | modification, are permitted provided that the following conditions are
104 | met:
105 | 
106 |     * Redistributions of source code must retain the above copyright
107 |        notice, this list of conditions and the following disclaimer.
108 | 
109 |     * Redistributions in binary form must reproduce the above
110 |        copyright notice, this list of conditions and the following
111 |        disclaimer in the documentation and/or other materials provided
112 |        with the distribution.
113 | 
114 |     * Neither the name of the copyright holder nor the names of any
115 |        contributors may be used to endorse or promote products derived
116 |        from this software without specific prior written permission.
117 | 
118 | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER AND CONTRIBUTORS
119 | "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
120 | LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
121 | A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
122 | OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
123 | SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
124 | LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
125 | DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
126 | THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
127 | (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
128 | OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
129 | 
130 | About the Copyright Holders
131 | ===========================
132 | 
133 | AQR Capital Management began pandas development in 2008. Development was
134 | led by Wes McKinney. AQR released the source under this license in 2009.
135 | Wes is now an employee of Lambda Foundry, and remains the pandas project
136 | lead.
137 | 
138 | The PyData Development Team is the collection of developers of the PyData
139 | project. This includes all of the PyData sub-projects, including pandas. The
140 | core team that coordinates development on GitHub can be found here:
141 | http://github.com/pydata.
142 | 
143 | Full credits for pandas contributors can be found in the documentation.
144 | 
145 | Our Copyright Policy
146 | ====================
147 | 
148 | PyData uses a shared copyright model. Each contributor maintains copyright
149 | over their contributions to PyData. However, it is important to note that
150 | these contributions are typically only changes to the repositories. Thus,
151 | the PyData source code, in its entirety, is not the copyright of any single
152 | person or institution. Instead, it is the collective copyright of the
153 | entire PyData Development Team. If individual contributors want to maintain
154 | a record of what changes/contributions they have specific copyright on,
155 | they should indicate their copyright in the commit message of the change
156 | when they commit the change to one of the PyData repositories.
157 | 
158 | With this in mind, the following banner should be used in any source code
159 | file to indicate the copyright and license terms:
160 | 
161 | #-----------------------------------------------------------------------------
162 | # Copyright (c) 2012, PyData Development Team
163 | # All rights reserved.
164 | #
165 | # Distributed under the terms of the BSD Simplified License.
166 | #
167 | # The full license is in the LICENSE file, distributed with this software.
168 | #-----------------------------------------------------------------------------
169 | 
170 | Other licenses can be found in the LICENSES directory.
171 | 
172 |
173 |
174 | -------------------------------------------------------------------------------- /r_interface.html: -------------------------------------------------------------------------------- 1 | 2 |

rpy2 / R interface

3 |
4 |

原文:http://pandas.pydata.org/pandas-docs/stable/r_interface.html

5 |

译者:飞龙 UsyiyiCN

6 |

校对:(虚位以待)

7 |
8 | 9 |
10 |

警告

11 |

在v0.16.0中,pandas.rpy接口已弃用,将在未来版本中删除。类似的功能可以通过rpy2项目访问。有关将代码从pandas.rpy移至rpy2函数的指南,请参阅updating部分。

12 |
13 |
14 |

Updating your code to use rpy2 functions

15 |

在v0.16.0中,pandas.rpy模块已弃用,用户指向rpy2本身)。

16 |

不要将导入 pandas.rpy.common 作为 com导入,应该做到激活rpy2中的pandas转换支持:

17 |
from rpy2.robjects import pandas2ri
 18 | pandas2ri.activate()
 19 | 
20 |
21 |

在rpy2和pandas之间来回转换数据帧应该在很大程度上自动化(不需要显式转换,它将在大多数rpy2函数中即时完​​成)。

22 |

要显式转换,函数为pandas2ri.py2ri()pandas2ri.ri2py()所以这些函数可以用来替换pandas中的现有函数:

23 | 27 |

注意:这些函数用于最新版本(rpy2 2.5.x),之前称为pandas2ri.pandas2ri()pandas2ri.ri2pandas()

28 |

pandas.rpy中的一些其他功能也可以轻松替换。例如,使用load_data函数加载R数据,当前方法:

29 |
df_iris = com.load_data('iris')
 30 | 
31 |
32 |

可替换为:

33 |
from rpy2.robjects import r
 34 | r.data('iris')
 35 | df_iris = pandas2ri.ri2py(r[name])
 36 | 
37 |
38 |

convert_to_r_matrix函数可以替换为正常的pandas2ri.py2ri以转换数据帧,随后调用R as.matrix函数。

39 |
40 |

警告

41 |

并不是rpy2中的所有转换函数都与pandas中的当前方法完全相同。如果您遇到与大熊猫相比的问题或限制,请在问题跟踪器上报告此问题。

42 |
43 |

另请参见rpy2项目的文档。

44 |
45 |
46 |

R interface with rpy2

47 |

如果您的计算机安装了R和rpy2(> 2.2)(将留给读者),您将能够利用以下功能。在Windows上,这样做是相当痛苦的,但在类Unix系统上的用户应该很容易。rpy2在时间上演变,目前达到2.3版本,而当前接口是为2.2.x系列设计的。我们建议使用2.2.x比其他系列,除非你准备修复部分代码,但rpy2-2.3.0引入了改进,如更好的R-Python桥内存管理层,因此它可能是一个好主意子弹和提交修补程序的一些小的差异,需要修复。

48 |
# if installing for the first time
 49 | hg clone http://bitbucket.org/lgautier/rpy2
 50 | 
 51 | cd rpy2
 52 | hg pull
 53 | hg update version_2.2.x
 54 | sudo python setup.py install
 55 | 
56 |
57 |
58 |

注意

59 |

要通过此接口使用R程序包,您需要自己在R中安装它们。目前它无法为您安装它们。

60 |
61 |

安装完R和rpy2后,您应该可以轻松导入pandas.rpy.common

62 |
63 |
64 |

Transferring R data sets into Python

65 |

load_data函数检索R数据集并将其转换为适当的pandas对象(很可能是DataFrame):

66 |
In [1]: import pandas.rpy.common as com
 67 | 
 68 | In [2]: infert = com.load_data('infert')
 69 | 
 70 | In [3]: infert.head()
 71 | Out[3]: 
 72 |   education   age  parity  induced  case  spontaneous  stratum  pooled.stratum
 73 | 1    0-5yrs  26.0     6.0      1.0   1.0          2.0        1             3.0
 74 | 2    0-5yrs  42.0     1.0      1.0   1.0          0.0        2             1.0
 75 | 3    0-5yrs  39.0     6.0      2.0   1.0          0.0        3             4.0
 76 | 4    0-5yrs  34.0     4.0      2.0   1.0          0.0        4             2.0
 77 | 5   6-11yrs  35.0     3.0      1.0   1.0          1.0        5            32.0
 78 | 
79 |
80 |
81 |
82 |

Converting DataFrames into R objects

83 |
84 |

版本0.8中的新功能。

85 |
86 |

从pandas 0.8开始,有实验支持将DataFrames转换为等效的R对象(即data.frame):

87 |
In [4]: import pandas.rpy.common as com
 88 | 
 89 | In [5]: df = pd.DataFrame({'A': [1, 2, 3], 'B': [4, 5, 6], 'C':[7,8,9]},
 90 |    ...:                   index=["one", "two", "three"])
 91 |    ...: 
 92 | 
 93 | In [6]: r_dataframe = com.convert_to_r_dataframe(df)
 94 | 
 95 | In [7]: print(type(r_dataframe))
 96 | <class 'rpy2.robjects.vectors.DataFrame'>
 97 | 
 98 | In [8]: print(r_dataframe)
 99 |       A B C
100 | one   1 4 7
101 | two   2 5 8
102 | three 3 6 9
103 | 
104 |
105 |

DataFrame的索引存储为data.frame实例的rownames属性。

106 |

您还可以使用convert_to_r_matrix获取Matrix实例,但是请记住,它只适用于均匀类型的DataFrames(因为R矩阵不包含数据类型的信息):

107 |
In [9]: import pandas.rpy.common as com
108 | 
109 | In [10]: r_matrix = com.convert_to_r_matrix(df)
110 | 
111 | In [11]: print(type(r_matrix))
112 | <class 'rpy2.robjects.vectors.Matrix'>
113 | 
114 | In [12]: print(r_matrix)
115 |       A B C
116 | one   1 4 7
117 | two   2 5 8
118 | three 3 6 9
119 | 
120 |
121 |
122 |
123 |

使用pandas对象调用R函数

124 |
125 |
126 |

到R估计器的高级接口

127 |
128 | -------------------------------------------------------------------------------- /remote_data.html: -------------------------------------------------------------------------------- 1 | 2 |

Remote Data Access

3 |
4 |

原文:http://pandas.pydata.org/pandas-docs/stable/remote_data.html

5 |

译者:飞龙 UsyiyiCN

6 |

校对:(虚位以待)

7 |
8 | 9 |
10 |

DataReader

11 |

删除子包pandas.io.data以支持可单独安装的pandas-datareader包这将允许数据模块独立更新到您的pandas安装。pandas-datareader v0.1.1的API与pandas v0 .16.1GH8961

12 |
13 |

您应该替换以下的导入:

14 |
from pandas.io import data, wb
15 | 
16 |
17 |

使用:

18 |
from pandas_datareader import data, wb
19 | 
20 |
21 |
22 |
23 |
24 |

Google Analytics

25 |

ga模块为Google Analytics API提供了一个包装,以简化检索流量数据。结果集将解析为具有从源表派生的形状和数据类型的pandas DataFrame。

26 |
27 |

Configuring Access to Google Analytics

28 |

您需要做的第一件事是设置对Google Analytics(分析)API的访问。请按照以下步骤操作:

29 |
    30 |
  1. 31 |
    Google Developers Console
    32 |
      33 |
    1. 启用Google Analytics(分析)API
    2. 34 |
    3. 创建一个新项目
    4. 35 |
    5. 为“已安装的应用程序”创建一个新的客户端ID(在新创建的项目的“APIs&auth / Credentials部分”中)
    6. 36 |
    7. 下载它(JSON文件)
    8. 37 |
    38 |
    39 |
    40 |
  2. 41 |
  3. 42 |
    在您的机器上
    43 |
      44 |
    1. 将其重命名为client_secrets.json
    2. 45 |
    3. 将其移动到pandas/io模块目录
    4. 46 |
    47 |
    48 |
    49 |
  4. 50 |
51 |

第一次使用read_ga()函数时,将打开一个浏览器窗口,要求您对Google API进行身份验证。请继续。

52 |
53 |
54 |

Using the Google Analytics API

55 |

以下内容将从特定媒体资源获取2014年第一季度每周的每日用户和浏览量(指标)数据。

56 |
import pandas.io.ga as ga
57 | ga.read_ga(
58 |     account_id  = "2360420",
59 |     profile_id  = "19462946",
60 |     property_id = "UA-2360420-5",
61 |     metrics     = ['users', 'pageviews'],
62 |     dimensions  = ['dayOfWeek'],
63 |     start_date  = "2014-01-01",
64 |     end_date    = "2014-08-01",
65 |     index_col   = 0,
66 |     filters     = "pagePath=~aboutus;ga:country==France",
67 | )
68 | 
69 |
70 |

唯一的强制参数是metrics, dimensionsstart_date我们强烈建议您始终指定account_idprofile_idproperty_id,以避免在Google Analytics(分析)中访问错误的数据桶。

71 |

index_col参数指示必须将哪个维度用作索引。

72 |

filters参数指示要应用于查询的过滤。在上面的示例中,网页网址必须包含aboutus,访问者国家必须是法国。

73 |

详细信息如下:

74 | 79 |
80 |
81 | -------------------------------------------------------------------------------- /sparse.html: -------------------------------------------------------------------------------- 1 | 2 |

Sparse data structures

3 |
4 |

原文:http://pandas.pydata.org/pandas-docs/stable/sparse.html

5 |

译者:飞龙 UsyiyiCN

6 |

校对:(虚位以待)

7 |
8 | 9 |
10 |

注意

11 |

在0.19.0中已删除SparsePanel

12 |
13 |

我们实现了“稀疏”版本的Series和DataFrame。这些在典型的“大多为0”中不稀疏。相反,您可以将这些对象视为“压缩”,其中省略任何匹配特定值(NaN /缺失值,尽管可以选择任何值)的数据。特殊的SparseIndex对象跟踪数据已被“稀疏化”的位置。在一个例子中,这将更有意义。所有标准的熊猫数据结构都有一个to_sparse方法:

14 |
In [1]: ts = pd.Series(randn(10))
 15 | 
 16 | In [2]: ts[2:-2] = np.nan
 17 | 
 18 | In [3]: sts = ts.to_sparse()
 19 | 
 20 | In [4]: sts
 21 | Out[4]: 
 22 | 0    0.469112
 23 | 1   -0.282863
 24 | 2         NaN
 25 | 3         NaN
 26 | 4         NaN
 27 | 5         NaN
 28 | 6         NaN
 29 | 7         NaN
 30 | 8   -0.861849
 31 | 9   -2.104569
 32 | dtype: float64
 33 | BlockIndex
 34 | Block locations: array([0, 8], dtype=int32)
 35 | Block lengths: array([2, 2], dtype=int32)
 36 | 
37 |
38 |

to_sparse方法采用kind参数(对于稀疏索引,请参见下文)和fill_value所以如果我们有一个大多数为零的系列,我们可以将它转换为稀疏与fill_value=0

39 |
In [5]: ts.fillna(0).to_sparse(fill_value=0)
 40 | Out[5]: 
 41 | 0    0.469112
 42 | 1   -0.282863
 43 | 2    0.000000
 44 | 3    0.000000
 45 | 4    0.000000
 46 | 5    0.000000
 47 | 6    0.000000
 48 | 7    0.000000
 49 | 8   -0.861849
 50 | 9   -2.104569
 51 | dtype: float64
 52 | BlockIndex
 53 | Block locations: array([0, 8], dtype=int32)
 54 | Block lengths: array([2, 2], dtype=int32)
 55 | 
56 |
57 |

稀疏对象存在是为了内存效率的原因。假设你有一个大的,主要是NA DataFrame:

58 |
In [6]: df = pd.DataFrame(randn(10000, 4))
 59 | 
 60 | In [7]: df.ix[:9998] = np.nan
 61 | 
 62 | In [8]: sdf = df.to_sparse()
 63 | 
 64 | In [9]: sdf
 65 | Out[9]: 
 66 |              0         1         2         3
 67 | 0          NaN       NaN       NaN       NaN
 68 | 1          NaN       NaN       NaN       NaN
 69 | 2          NaN       NaN       NaN       NaN
 70 | 3          NaN       NaN       NaN       NaN
 71 | 4          NaN       NaN       NaN       NaN
 72 | 5          NaN       NaN       NaN       NaN
 73 | 6          NaN       NaN       NaN       NaN
 74 | ...        ...       ...       ...       ...
 75 | 9993       NaN       NaN       NaN       NaN
 76 | 9994       NaN       NaN       NaN       NaN
 77 | 9995       NaN       NaN       NaN       NaN
 78 | 9996       NaN       NaN       NaN       NaN
 79 | 9997       NaN       NaN       NaN       NaN
 80 | 9998       NaN       NaN       NaN       NaN
 81 | 9999  0.280249 -1.648493  1.490865 -0.890819
 82 | 
 83 | [10000 rows x 4 columns]
 84 | 
 85 | In [10]: sdf.density
 86 | Out[10]: 0.0001
 87 | 
88 |
89 |

如你所见,密度(未被“压缩”的值的百分比)非常低。这个稀疏对象在磁盘(pickled)和Python解释器中占用更少的内存。在功能上,它们的行为应该与它们的稠密对应物几乎相同。

90 |

任何稀疏对象都可以通过调用to_dense转换回标准密集形式:

91 |
In [11]: sts.to_dense()
 92 | Out[11]: 
 93 | 0    0.469112
 94 | 1   -0.282863
 95 | 2         NaN
 96 | 3         NaN
 97 | 4         NaN
 98 | 5         NaN
 99 | 6         NaN
100 | 7         NaN
101 | 8   -0.861849
102 | 9   -2.104569
103 | dtype: float64
104 | 
105 |
106 |
107 |

SparseArray

108 |

SparseArray是所有稀疏索引数据结构的基本层。它是一个1维的ndarray样对象,只存储不同于fill_value的值:

109 |
In [12]: arr = np.random.randn(10)
110 | 
111 | In [13]: arr[2:5] = np.nan; arr[7:8] = np.nan
112 | 
113 | In [14]: sparr = pd.SparseArray(arr)
114 | 
115 | In [15]: sparr
116 | Out[15]: 
117 | [-1.95566352972, -1.6588664276, nan, nan, nan, 1.15893288864, 0.145297113733, nan, 0.606027190513, 1.33421134013]
118 | Fill: nan
119 | IntIndex
120 | Indices: array([0, 1, 5, 6, 8, 9], dtype=int32)
121 | 
122 |
123 |

像索引对象(SparseSeries,SparseDataFrame)一样,通过调用to_dense可以将SparseArray转换回常规的ndarray:

124 |
In [16]: sparr.to_dense()
125 | Out[16]: 
126 | array([-1.9557, -1.6589,     nan,     nan,     nan,  1.1589,  0.1453,
127 |            nan,  0.606 ,  1.3342])
128 | 
129 |
130 |
131 |
132 |

SparseList

133 |

SparseList类已弃用,将在以后的版本中删除。有关SparseList的文档,请参见以前版本的文档

134 |
135 |
136 |

SparseIndex objects

137 |

实现了两种SparseIndexblockinteger我们建议使用block,因为它更节省内存。integer格式保留数据不等于填充值的所有位置的数组。block格式只跟踪数据块的位置和大小。

138 |
139 |
140 |

Sparse Dtypes

141 |

稀疏数据应具有与其密集表示相同的dtype。目前,支持float64int64bool dtypes。根据原始dtype,fill_value默认更改:

142 | 147 |
In [17]: s = pd.Series([1, np.nan, np.nan])
148 | 
149 | In [18]: s
150 | Out[18]: 
151 | 0    1.0
152 | 1    NaN
153 | 2    NaN
154 | dtype: float64
155 | 
156 | In [19]: s.to_sparse()
157 | Out[19]: 
158 | 0    1.0
159 | 1    NaN
160 | 2    NaN
161 | dtype: float64
162 | BlockIndex
163 | Block locations: array([0], dtype=int32)
164 | Block lengths: array([1], dtype=int32)
165 | 
166 | In [20]: s = pd.Series([1, 0, 0])
167 | 
168 | In [21]: s
169 | Out[21]: 
170 | 0    1
171 | 1    0
172 | 2    0
173 | dtype: int64
174 | 
175 | In [22]: s.to_sparse()
176 | Out[22]: 
177 | 0    1
178 | 1    0
179 | 2    0
180 | dtype: int64
181 | BlockIndex
182 | Block locations: array([0], dtype=int32)
183 | Block lengths: array([1], dtype=int32)
184 | 
185 | In [23]: s = pd.Series([True, False, True])
186 | 
187 | In [24]: s
188 | Out[24]: 
189 | 0     True
190 | 1    False
191 | 2     True
192 | dtype: bool
193 | 
194 | In [25]: s.to_sparse()
195 | Out[25]: 
196 | 0     True
197 | 1    False
198 | 2     True
199 | dtype: bool
200 | BlockIndex
201 | Block locations: array([0, 2], dtype=int32)
202 | Block lengths: array([1, 1], dtype=int32)
203 | 
204 |
205 |

您可以使用.astype()更改dtype,结果也是稀疏的。请注意,.astype()也会影响fill_value以保持其密集表示。

206 |
In [26]: s = pd.Series([1, 0, 0, 0, 0])
207 | 
208 | In [27]: s
209 | Out[27]: 
210 | 0    1
211 | 1    0
212 | 2    0
213 | 3    0
214 | 4    0
215 | dtype: int64
216 | 
217 | In [28]: ss = s.to_sparse()
218 | 
219 | In [29]: ss
220 | Out[29]: 
221 | 0    1
222 | 1    0
223 | 2    0
224 | 3    0
225 | 4    0
226 | dtype: int64
227 | BlockIndex
228 | Block locations: array([0], dtype=int32)
229 | Block lengths: array([1], dtype=int32)
230 | 
231 | In [30]: ss.astype(np.float64)
232 | Out[30]: 
233 | 0    1.0
234 | 1    0.0
235 | 2    0.0
236 | 3    0.0
237 | 4    0.0
238 | dtype: float64
239 | BlockIndex
240 | Block locations: array([0], dtype=int32)
241 | Block lengths: array([1], dtype=int32)
242 | 
243 |
244 |

如果任何值不能强制到指定的dtype,它会引发。

245 |
In [1]: ss = pd.Series([1, np.nan, np.nan]).to_sparse()
246 | 0    1.0
247 | 1    NaN
248 | 2    NaN
249 | dtype: float64
250 | BlockIndex
251 | Block locations: array([0], dtype=int32)
252 | Block lengths: array([1], dtype=int32)
253 | 
254 | In [2]: ss.astype(np.int64)
255 | ValueError: unable to coerce current fill_value nan to int64 dtype
256 | 
257 |
258 |
259 |
260 |

Sparse Calculation

261 |

您可以将NumPy ufuncs应用于SparseArray,并获得SparseArray作为结果。

262 |
In [31]: arr = pd.SparseArray([1., np.nan, np.nan, -2., np.nan])
263 | 
264 | In [32]: np.abs(arr)
265 | Out[32]: 
266 | [1.0, nan, nan, 2.0, nan]
267 | Fill: nan
268 | IntIndex
269 | Indices: array([0, 3], dtype=int32)
270 | 
271 |
272 |

ufunc也适用于fill_value这是需要得到正确的密集结果。

273 |
In [33]: arr = pd.SparseArray([1., -1, -1, -2., -1], fill_value=-1)
274 | 
275 | In [34]: np.abs(arr)
276 | Out[34]: 
277 | [1.0, 1, 1, 2.0, 1]
278 | Fill: 1
279 | IntIndex
280 | Indices: array([0, 3], dtype=int32)
281 | 
282 | In [35]: np.abs(arr).to_dense()
283 | Out[35]: array([ 1.,  1.,  1.,  2.,  1.])
284 | 
285 |
286 |
287 |
288 |

Interaction with scipy.sparse

289 |

实验api在稀疏熊猫和scipy.sparse结构之间进行转换。

290 |

A SparseSeries.to_coo() method is implemented for transforming a SparseSeries indexed by a MultiIndex to a scipy.sparse.coo_matrix.

291 |

该方法需要具有两个或更多个级别的MultiIndex

292 |
In [36]: s = pd.Series([3.0, np.nan, 1.0, 3.0, np.nan, np.nan])
293 | 
294 | In [37]: s.index = pd.MultiIndex.from_tuples([(1, 2, 'a', 0),
295 |    ....:                                      (1, 2, 'a', 1),
296 |    ....:                                      (1, 1, 'b', 0),
297 |    ....:                                      (1, 1, 'b', 1),
298 |    ....:                                      (2, 1, 'b', 0),
299 |    ....:                                      (2, 1, 'b', 1)],
300 |    ....:                                      names=['A', 'B', 'C', 'D'])
301 |    ....: 
302 | 
303 | In [38]: s
304 | Out[38]: 
305 | A  B  C  D
306 | 1  2  a  0    3.0
307 |          1    NaN
308 |    1  b  0    1.0
309 |          1    3.0
310 | 2  1  b  0    NaN
311 |          1    NaN
312 | dtype: float64
313 | 
314 | # SparseSeries
315 | In [39]: ss = s.to_sparse()
316 | 
317 | In [40]: ss
318 | Out[40]: 
319 | A  B  C  D
320 | 1  2  a  0    3.0
321 |          1    NaN
322 |    1  b  0    1.0
323 |          1    3.0
324 | 2  1  b  0    NaN
325 |          1    NaN
326 | dtype: float64
327 | BlockIndex
328 | Block locations: array([0, 2], dtype=int32)
329 | Block lengths: array([1, 2], dtype=int32)
330 | 
331 |
332 |

在下面的示例中,通过指定第一个和第二个MultiIndex级别定义行的标签,将SparseSeries变换为2-d数组的稀疏表示,和第四级定义列的标签。我们还指定列和行标签应按最终稀疏表示法排序。

333 |
In [41]: A, rows, columns = ss.to_coo(row_levels=['A', 'B'],
334 |    ....:                              column_levels=['C', 'D'],
335 |    ....:                              sort_labels=True)
336 |    ....: 
337 | 
338 | In [42]: A
339 | Out[42]: 
340 | <3x4 sparse matrix of type '<type 'numpy.float64'>'
341 | 	with 3 stored elements in COOrdinate format>
342 | 
343 | In [43]: A.todense()
344 | Out[43]: 
345 | matrix([[ 0.,  0.,  1.,  3.],
346 |         [ 3.,  0.,  0.,  0.],
347 |         [ 0.,  0.,  0.,  0.]])
348 | 
349 | In [44]: rows
350 | Out[44]: [(1, 1), (1, 2), (2, 1)]
351 | 
352 | In [45]: columns
353 | Out[45]: [('a', 0), ('a', 1), ('b', 0), ('b', 1)]
354 | 
355 |
356 |

指定不同的行和列标签(而不是排序)会产生不同的稀疏矩阵:

357 |
In [46]: A, rows, columns = ss.to_coo(row_levels=['A', 'B', 'C'],
358 |    ....:                              column_levels=['D'],
359 |    ....:                              sort_labels=False)
360 |    ....: 
361 | 
362 | In [47]: A
363 | Out[47]: 
364 | <3x2 sparse matrix of type '<type 'numpy.float64'>'
365 | 	with 3 stored elements in COOrdinate format>
366 | 
367 | In [48]: A.todense()
368 | Out[48]: 
369 | matrix([[ 3.,  0.],
370 |         [ 1.,  3.],
371 |         [ 0.,  0.]])
372 | 
373 | In [49]: rows
374 | Out[49]: [(1, 2, 'a'), (1, 1, 'b'), (2, 1, 'b')]
375 | 
376 | In [50]: columns
377 | Out[50]: [0, 1]
378 | 
379 |
380 |

实现方便方法SparseSeries.from_coo()用于从scipy.sparse.coo_matrix创建SparseSeries

381 |
In [51]: from scipy import sparse
382 | 
383 | In [52]: A = sparse.coo_matrix(([3.0, 1.0, 2.0], ([1, 0, 0], [0, 2, 3])),
384 |    ....:                       shape=(3, 4))
385 |    ....: 
386 | 
387 | In [53]: A
388 | Out[53]: 
389 | <3x4 sparse matrix of type '<type 'numpy.float64'>'
390 | 	with 3 stored elements in COOrdinate format>
391 | 
392 | In [54]: A.todense()
393 | Out[54]: 
394 | matrix([[ 0.,  0.,  1.,  2.],
395 |         [ 3.,  0.,  0.,  0.],
396 |         [ 0.,  0.,  0.,  0.]])
397 | 
398 |
399 |

默认行为(dense_index=False)只返回一个只包含非空条目的SparseSeries

400 |
In [55]: ss = pd.SparseSeries.from_coo(A)
401 | 
402 | In [56]: ss
403 | Out[56]: 
404 | 0  2    1.0
405 |    3    2.0
406 | 1  0    3.0
407 | dtype: float64
408 | BlockIndex
409 | Block locations: array([0], dtype=int32)
410 | Block lengths: array([3], dtype=int32)
411 | 
412 |
413 |

指定dense_index=True将产生一个索引,该索引是矩阵的行和列坐标的笛卡尔乘积。注意,如果稀疏矩阵足够大(和稀疏),这将消耗大量的存储器(相对于dense_index=False)。

414 |
In [57]: ss_dense = pd.SparseSeries.from_coo(A, dense_index=True)
415 | 
416 | In [58]: ss_dense
417 | Out[58]: 
418 | 0  0    NaN
419 |    1    NaN
420 |    2    1.0
421 |    3    2.0
422 | 1  0    3.0
423 |    1    NaN
424 |    2    NaN
425 |    3    NaN
426 | 2  0    NaN
427 |    1    NaN
428 |    2    NaN
429 |    3    NaN
430 | dtype: float64
431 | BlockIndex
432 | Block locations: array([2], dtype=int32)
433 | Block lengths: array([3], dtype=int32)
434 | 
435 |
436 |
437 | -------------------------------------------------------------------------------- /tutorials.html: -------------------------------------------------------------------------------- 1 | 2 |

教程

3 |
4 |

原文:http://pandas.pydata.org/pandas-docs/stable/tutorials.html

5 |

译者:飞龙 UsyiyiCN

6 |

校对:(虚位以待)

7 |
8 | 9 |

这是一份很多pandas教程的指南,主要面向pandas的新用户

10 |
11 |

内部指南

12 |

pandas10分钟了解pandas

13 |

更复杂的运用在Cookbook

14 |
15 |
16 |

pandas Cookbook

17 |

这本书的目标(由Julia Evans)是通过给你一些具体的例子来开始使用pandas。这些是真实数据的例子,以及所有的错误和引起异常。

18 |

这里是v0.1版本的链接。有关最新的目录,请参阅pandas-cookbook GitHub存储库要运行本教程中的示例,您需要克隆GitHub存储库并使IPython Notebook运行。请参阅如何使用本CookBook

19 | 30 |
31 |
32 |

Lessons for New pandas Users

33 |

有关更多资源,请访问主要的存储库

34 | 47 |
48 |
49 |

Practical data analysis with Python

50 |

指南是使用Python数据生态系统和一个有趣的开放数据集的数据分析过程的全面介绍。有四个部分涵盖所选主题如下:

51 | 57 |
58 |
59 |

Modern Pandas

60 | 68 |
69 |
70 |

Excel charts with pandas, vincent and xlsxwriter

71 | 74 |
75 |
76 |

Various Tutorials

77 | 86 |
87 | -------------------------------------------------------------------------------- /whatsnew.html: -------------------------------------------------------------------------------- 1 |

新功能

2 |
3 |

原文:http://pandas.pydata.org/pandas-docs/stable/whatsnew.html

4 |

译者:飞龙 UsyiyiCN

5 |

校对:(虚位以待)

6 |
7 | --------------------------------------------------------------------------------