├── 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 |
4 |8 | 9 |原文:http://pandas.pydata.org/pandas-docs/stable/ecosystem.html
5 | 6 |校对:(虚位以待)
7 |
越来越多的软件包在大熊猫上构建,以满足数据准备,分析和可视化的特定需求。这是令人鼓舞的,因为它意味着熊猫不仅帮助用户处理他们的数据任务,而且它为开发者提供了一个更好的起点,构建强大和更集中的数据工具。创建补充熊猫功能的图书馆也允许熊猫开发继续专注于它的原始要求。
10 |11 |
我们希望让用户更容易找到这些项目,如果您知道您认为应该在此列表中的其他实质性项目,请告诉我们。
12 |Statsmodels是着名的python“统计和计量经济学图书馆”,它与熊猫有着长期的特殊关系。Statsmodels提供强大的统计,计量经济学,分析和建模功能,超出了熊猫的范围。Statsmodels利用pandas对象作为计算的基础数据容器。
17 |在scikit-learn ML管道中使用pandas DataFrames。
21 |Bokeh是一个用于大型数据集的Python交互式可视化库,本地使用最新的Web技术。其目标是以Protovis / D3的风格提供优雅,简洁的新颖图形构造,同时为大型数据向瘦客户端提供高性能交互性。
28 |Hadley Wickham的ggplot2是R语言的基础探索性可视化包。基于“图形语法”它提供了一个强大的,声明性和极其一般的方式来生成任何类型的数据的定制图。这真的很不可思议。各种实现到其他语言是可用的,但一个忠实的实现python用户长期以来一直缺失。虽然仍然年轻(截至2014年1月),yhat / ggplot项目已经在这个方向上迅速发展。
32 |虽然熊猫有相当多的“只是绘图”的功能内置,可视化,特别是统计图形是一个广泛的领域,具有悠久的传统和大量的地面覆盖。Seaborn项目构建在pandas和matplotlib之上,以便于绘制更多高级类型的数据,然后提供由pandas提供的数据。
36 |Vincent项目利用Vega(进而利用d3)创建图表。虽然功能,从2016年夏天Vincent项目在两年内没有更新,不太可能收到进一步更新。
40 |像Vincent一样,IPython Vega项目利用Vega创建图,但主要针对IPython Notebook环境。
44 |Plotly的 Python API可提供互动数字和网页分享功能。使用WebGL和D3.js来呈现地图,2D,3D和实况流图。该库支持直接从pandas DataFrame和基于云的协作绘制。matplotlib,ggplot for Python和Seaborn的用户可以将图形转换为基于Web的互动图。绘图可以在IPython笔记本中绘制,使用R或MATLAB编辑,在GUI中修改,或嵌入在应用程序和仪表板中。Plotly可免费无限制分享,且拥有云,离线或内部帐户供私人使用。
48 |IPython是一个交互式命令shell和分布式计算环境。IPython Notebook是一个用于创建IPython笔记本的Web应用程序。IPython notebook是一个JSON文档,包含输入/输出单元格的有序列表,其中可以包含代码,文本,数学,图表和富媒体。IPython Notebook可以通过Web界面中的“下载为”和ipython t1转换为多种开放标准输出格式(HTML,HTML演示文稿幻灯片,LaTeX,PDF,ReStructuredText,Markdown, > nbconvert
。
Pandas DataFrames实现了IPython Notebook用于显示(缩写)HTML表的_repr_html_
方法。(注意:HTML表格可能与非HTML IPython输出格式兼容,也可能不兼容)。
qgrid是“用于排序和过滤IPython Notebook中的DataFrames的交互式网格”,使用SlickGrid构建。
64 |Spyder是一个跨平台的基于Qt的开源Python IDE,具有编辑,测试,调试和内省功能。Spyder现在可以内省和显示Pandas DataFrames,并显示“列方式最小/最大值和全局最小/最大着色”。
68 |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中至少有一个文档段落:
以下数据Feed可用:
76 |77 |88 |78 |
87 |- 雅虎金融
79 |- Google财经
80 |- FRED
81 |- Fama /法语
82 |- 世界银行
83 |- 经合组织
84 |- 欧洲统计局
85 |- EDGAR索引
86 |
Quandl API for Python包装Quandl REST API以返回带有时间序列索引的Pandas DataFrames。
92 |PyDatastream是Thomson Dataworks Enterprise(DWE / Datastream) SOAP API的Python接口,用于返回带有财务数据的带索引的Pandas DataFrames或面板。此程序包需要此API的有效凭据(非免费)。
96 |pandaSDMX是一个可扩展的库,用于检索和获取在SDMX 2.1中传播的统计数据和元数据。本标准目前由欧洲统计局(欧盟统计局)和欧洲中央银行(欧洲中央银行)支持。数据集可以作为pandas系列或多索引的DataFrames返回。
100 |fredapi是由圣路易斯联邦储备银行提供的联邦储备经济数据(FRED)的Python接口。它与包含时间点数据(即历史数据修订)的FRED数据库和ALFRED数据库一起工作。fredapi在python中为FRED HTTP API提供了一个包装器,并且还提供了几种方便的方法来解析和分析来自ALFRED的时间点数据。fredapi使用pandas并返回一个Series或DataFrame中的数据。此模块需要FRED API密钥,您可以在FRED网站上免费获取。
104 |地理空间扩展了熊猫数据对象,以包括支持几何操作的地理信息。如果你的工作需要地图和地理坐标,你喜欢大熊猫,你应该仔细看看地球圈。
111 |xarray通过提供核心熊猫数据结构的N维变量将大熊猫的标记数据功率带到物理科学。它旨在提供一个用于多维数组分析的熊猫和熊猫兼容工具包,而不是熊猫擅长的表格数据。
115 |Dask是一个用于分析的灵活的并行计算库。Dask允许熟悉的DataFrame
接口用于核外,并行和分布式计算。
Blaze提供了一个标准API,用于使用各种内存和磁盘后端进行计算:NumPy,Pandas,SQLAlchemy,MongoDB,PyTables,PySpark。
126 |Odo提供了用于在不同格式之间移动数据的统一API。它使用pandas自己的read_csv
来获取CSV IO,并利用许多现有的包(如PyTables,h5py和pymongo)在非熊猫格式之间移动数据。它的基于图的方法也可以由最终用户扩展自定义格式,可能太具体的odo的核心。
4 |8 | 9 |原文:http://pandas.pydata.org/pandas-docs/stable/faq.html
5 | 6 |校对:(虚位以待)
7 |
对于pandas版本0.15.0,当使用info
方法访问结构数据时,将输出结构数据(包括索引)的内存使用情况。配置选项display.memory_usage
(请参阅Options and Settings)指定在调用df.info()
例如,调用df.info()
时会显示以下结构数据的内存使用情况:
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 |
+
符号表示真正的内存使用率可能更高,因为pandas不会计算dtype=object
的列中使用的内存。
版本0.17.1中的新功能。
46 |传递memory_usage='deep'
参数,将输出更准确的内存使用情况报告,包含结构数据内存的完全使用情况。这是参数是可选的,因为做更深入的内存检查需要付出更多。
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 |
默认情况下,display选项设置为True
,但是可以在调用df.info()
时传递memory_usage
参数来显式覆盖。
通过调用memory_usage
方法可以找到每列的内存使用情况。这将返回一个具有以字节表示的列的名称和内存使用情况的索引。对于上面的数据帧,可以使用memory_usage方法找到每列数据的内存使用情况和结构数据的总内存使用情况:
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 |
默认情况下,结构数据索引的内存使用情况显示在返回的Series中,可以通过传递index=False
参数来去除索引的内存使用情况:
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 |
info
方法显示的内存使用情况利用memory_usage
方法来确定结构数据的内存使用情况,同时还以人类可读单位格式化输出(base-2表示;即1KB = 1024字节)。
有时,您可能必须处理在机器上创建的数据具有与运行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 |
有关详细信息,请参阅有关字节顺序的NumPy文档。
112 |在pandas中没有这种可视化的支持。但是,外部模块pandas-qt提供这样的功能。
116 |4 |8 | 9 |原文:http://pandas.pydata.org/pandas-docs/stable/index.html
5 | 6 |校对:(虚位以待)
7 |
日期: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 | 16 |pandas是一个提供快速,灵活和表达性数据结构的Python包,旨在使“关系”或“标记”数据变得简单直观。它旨在成为在Python中进行实用的真实世界数据分析的基本高级构建块。此外,它的更广泛的目标是成为最强大和最灵活的任何语言的开源数据分析/操作工具。它已经很好地朝着这个目标前进了。
17 |pandas非常适合许多不同类型的数据:
18 |19 |26 |20 |
25 |- 具有非均匀类型列的表格数据,如在SQL表或Excel电子表格中
21 |- 有序和无序(不一定是固定频率)时间序列数据。
22 |- 带有行和列标签的任意矩阵数据(均匀类型或异质)
23 |- 任何其他形式的观测/统计数据集。数据实际上不需要被标记就可以被放置到Pandas的数据结构中
24 |
pandas的两个主要数据结构Series
(一维)和DataFrame
(二维)处理了金融,统计,社会中的绝大多数典型用例科学,以及许多工程领域。对于R用户,DataFrame
提供R的data.frame
所有功能及其他功能。pandas建立在NumPy之上,旨在包含更多其他第三方库并与之集成为优秀的科学计算环境。
这里只是几个pandas做得很好的事情:
28 |29 |43 |30 |
42 |- 轻松处理浮点数据中的缺失数据(表示为NaN)以及非浮点数据
31 |- 大小可变性:列可以从DataFrame和更高维度的对象中插入和删除
32 |- 自动和显式数据对齐:对象可以显式地对齐到一组标签,或者用户可以简单地忽略标签,让Series,DataFrame 等在计算中为您自动对齐数据
33 |- 功能强大,灵活的分组功能对数据集执行拆分应用组合操作,以聚合和转换数据
34 |- 使易于将其他Python和NumPy数据结构中的粗糙,不同索引的数据转换为DataFrame对象
35 |- 基于智能标签的切片,花式索引和子集化大数据集
36 |- 直观的合并和连接数据集
37 |- 灵活的重塑和数据集的旋转
38 |- 轴的分层标签(每个标记可能有多个标签)
39 |- 用于从平面文件(CSV和定界),Excel文件,数据库加载数据并保存/加载超快速HDF5格式的数据的强大IO工具
40 |- 时间序列 - 特定功能:日期范围生成和频率转换,移动窗口统计,移动窗口线性回归,日期移动和滞后等。
41 |
许多此处原则是为了解决在使用其他语言/科学研究环境时常常所遇到的不足。对于数据科学家,处理数据通常分为多个阶段:清理和清理数据,分析/建模,然后将分析的结果组织成适合于绘图或表格显示的形式。pandas是处理所有这些任务的理想工具。
44 |其他一些注释
45 |46 |52 |47 |
51 |- pandas是快速的。许多低级算法位已在Cython代码中广泛调整。然而,通用化的代价是牺牲性能,这是一种普遍现象。因此,如果您专注于应用程序的一个功能,您可以创建一个更快的专业工具。
48 |- pandas是statsmodels的依赖项,使其成为Python中统计计算生态系统的重要组成部分。
49 |- pandas已广泛用于金融应用的产品。
50 |
注意
54 |本文档假定你熟悉NumPy。如果你还没有熟练使用NumPy或者根本没用过numpy,请先花一些时间学习NumPy。
55 |有关库中的内容的更多详细信息,请参阅软件包概述。
57 |4 |8 | 9 |原文:http://pandas.pydata.org/pandas-docs/stable/install.html
5 | 6 |校对:(虚位以待)
7 |
大多数用户安装 pandas 的最简单的方法是将其安装为 Anaconda 发行版的一部分,这是一个用于数据分析和科学计算的跨平台发行版。这是大多数 pandas 用户选择的安装方式
10 |此外这里还提供了从源码,PyPI,各种Linux发行版或开发版本安装的说明。
11 |官方Python 2.7,3.4,3.5和3.6
14 |最简单开始尝试pandas方式,不需要安装pandas,方式如下
20 |Wakari是一项免费服务,可在云中提供托管的IPython Notebook服务。
21 |只需创建一个帐户,即可在几分钟内通过IPython Notebook在浏览器中访问pandas。
22 |对于没有经验的用户安装Pandas、NumPy和SciPy数据科学分析体系的其余部分可能有点困难。
26 |最简单的方法不仅安装pandas,而且还安装Python和构成SciPy辅助(IPython,NumPy,Matplotlib,...)与用于数据分析和科学计算的跨平台(Linux,Mac OS X,Windows)Python分发版Anaconda。
27 |运行简单的安装程序后,用户将可以访问pandas和SciPy体系的其余部分,而无需安装任何其他内容,无需等待任何软件编译。
28 | 29 |作为Anaconda分发一部分的软件包的完整列表可在此处找到。
30 |安装Anaconda的另一个好处是,你不需要管理员权限安装它,它会安装在用户的主目录,这也使得在日后删除Anaconda(只是删除该文件夹)变得简单。
31 |上一节概述了如何将 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 |
这将创建一个只安装了Python的最小环境。要将你自己放在这个环境中运行:
44 |source activate name_of_my_env
45 |
在Windows上,命令是:
48 |activate name_of_my_env
49 |
所需的最后一步是安装pandas。可以使用以下命令完成:
52 |conda install pandas
53 |
要安装特定的pandas版本:
56 |conda install pandas=0.13.1
57 |
要安装其他软件包,例如IPython:
60 |conda install ipython
61 |
要安装完整的Anaconda发行版:
64 |conda install anaconda
65 |
如果你需要任何可用的pip,但不能conda,只需安装pip,并使用pip安装这些软件包:
68 |conda install pip
69 | pip install django
70 |
pandas还可以通过pip从PyPI安装。
76 |pip install pandas
77 |
这可能需要安装一些依赖项,包括NumPy,将需要一个编译器来编译所需的代码位,并且可能需要几分钟时间才能完成。
80 |此表中的命令将从您的分发中安装用于Python 2的pandas。要为Python 3安装pandas,您可能需要使用包python3-pandas
。
分配 | 93 |状态 | 94 |下载/ Repository链接 | 95 |安装方法 | 96 |
---|---|---|---|
Debian | 100 |稳定 | 101 |官方Debian存储库 | 102 |sudo apt-get 安装 python-pandas |
103 |
Debian和Ubuntu | 105 |unstable(最新软件包) | 106 |NeuroDebian | 107 |sudo apt-get 安装 python-pandas |
108 |
Ubuntu | 110 |稳定 | 111 |官方Ubuntu存储库 | 112 |sudo apt-get 安装 python-pandas |
113 |
Ubuntu | 115 |不稳定(每日构建) | 116 |PythonXY PPA; activate by:sudo add-apt-repository ppa:pythonxy / pythonxy-devel &amp;&amp; > sudo apt-get 更新 |
117 | sudo apt-get 安装 python-pandas |
118 |
OpenSuse | 120 |稳定 | 121 |OpenSuse存储库 | 122 |zypper 在 python-pandas |
123 |
Fedora | 125 |稳定 | 126 |官方Fedora存储库 | 127 |dnf 安装 python-pandas |
128 |
Centos / RHEL | 130 |稳定 | 131 |EPEL存储库 | 132 |yum 安装 python-pandas |
133 |
有关从git源代码树构建的完整说明,请参阅contributing documentation。此外,如果您要创建pandas开发环境,请参阅creating a development environment。
140 |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 |
numexpr
使用多个内核以及智能分块和缓存来实现大型加速。如果已安装,则必须为2.1或更高版本(不包括2.4.4版本)。强烈建议使用版本2.4.6或更高版本。nan
评估。bottleneck
使用专用的cython例程来实现大的加速。注意
181 |强烈建议您安装这些库,因为它们提供大的加速,尤其是使用大型数据集时。
182 |Cython:只需要构建开发版本。版本0.19.1或更高版本。
188 |SciPy:其他统计函数
190 |xarray:pandas像处理> 2 dims,需要将面板转换为xarray对象。建议使用0.7.0或更高版本。
192 |PyTables:基于HDF5的存储所必需。强烈建议需要3.0.0或更高版本,3.2.1或更高版本。
194 |SQLAlchemy:用于SQL数据库支持。建议使用0.8.1或更高版本。除了SQLAlchemy,还需要一个数据库特定的驱动程序。您可以在SQLAlchemy docs中找到每种SQL方言的支持的驱动程序的概述。一些常见的驱动程序是:
196 |197 |203 |
matplotlib:用于绘图
205 |对于Excel I / O:
207 |Jinja2:用于条件HTML格式化的模板引擎。
214 |boto:对于Amazon S3访问必需的。
216 |blosc:用于使用blosc
的msgpack压缩
PyQt4,PySide,pygtk,xsel或xclip之一:必要使用read_clipboard()
。Linux发行版上的大多数软件包管理器都会立即提供xclip
和/或xsel
。
Google的`python-gflags <<https://github.com/google/python-gflags/>`__,oauth2client,httplib2 和google-api-python-client:需要gbq
Backports.lzma:仅适用于Python 2,用于在CSV中写入和/或读取xz压缩的DataFrame; Python 3支持内置到标准库中。
224 |需要使用以下库的组合之一来使用顶层read_html()
函数:
警告
234 |read_html()
将不仅处理 BeautifulSoup4。注意
243 |如果你使用apt-get
的系统,你可以这样做
sudo apt-get build-dep python-lxml
246 |
以获取安装lxml所需的依赖关系。这可以防止下面进程中出现错误。
249 |注意
256 |没有可选的依赖项,许多有用的功能将不工作。因此,强烈建议您安装这些。像Anaconda或Enthought Canopy的打包分发可能值得考虑。
257 |4 |8 | 9 |原文:http://pandas.pydata.org/pandas-docs/stable/internals.html
5 | 6 |校对:(虚位以待)
7 |
本节将介绍一些大熊猫内部。
10 |在大熊猫中有一些实现的对象可以作为轴标签的有效容器:
13 |Index
:通用的“有序集合”对象,对象类型的ndarray,不考虑其内容。标签必须是可哈希的(并且可能是不可变的)和唯一的。在Cython中填充标签的位置以执行O(1)
查找。Int64Index
:针对64位整数数据(例如时间戳)高度优化的Index
版本Float64Index
:针对64位浮点数据进行高度优化的Index
版本MultiIndex
:标准层次索引对象DatetimeIndex
:带有Timestamp
框元素的索引对象(impl是int64值)TimedeltaIndex
:具有Timedelta
框元素的索引对象(impl是in64值)PeriodIndex
:包含Period元素的索引对象有一些功能使得创建常规索引变得容易:
23 |date_range
:从时间规则或DateOffset生成的固定频率日期范围。Python datetime对象的ndarrayperiod_range
:从时间规则或DateOffset生成的固定频率日期范围。Period
对象的数组,表示时间段首先具有Index
类的动机是启用不同的索引实现。这意味着,用户可以实现一个自定义Index
子类,它可能更适合于特定应用程序,而不是在pandas中提供的。
从内部实现的角度来看,Index
必须定义的相关方法是以下一个或多个(取决于新对象内部与Index
功能):
get_loc
:为标签返回“indexer”(整数,或在某些情况下为slice对象)slice_locs
:返回“范围”到两个标签之间的切片get_indexer
:计算用于重建索引/数据对齐目的的索引向量。有关更多信息,请参阅source / docstringsget_indexer_non_unique
:当索引非唯一时,计算索引向量以进行重建索引/数据对齐。有关更多信息,请参阅source / docstringsreindex
:输入索引的任何预转换然后调用get_indexer
union
,intersection
:计算两个Index对象的并集或交集insert
:在索引中插入一个新标签,产生一个新对象delete
:删除标签,生成一个新对象drop
:删除一组标签take
:类似于ndarray.take在内部,MultiIndex
包含以下几项内容:级别,整数标签和级别名称:
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 |
您可能猜测标签确定在索引的每个层上用该位置标识哪个唯一元素。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_tuples
和from_arrays
确保这是真的,但如果你自己计算级别和标签,请小心。
本节介绍如何子类化pandas
数据结构以满足更具体的需求。有2分需要注意:
注意
82 |你可以在geopandas项目中找到一个很好的例子。
83 |每个数据结构都具有指定数据构造函数的构造函数属性。通过覆盖这些属性,您可以通过pandas
数据操作来保留定义类。
有3个构造函数要定义:
88 |_constructor
:当操作结果与原始操作结果具有相同的缩放时使用。_constructor_sliced
:当操作结果具有一个较低维度作为原始值时使用,例如DataFrame
单列切片。_constructor_expanddim
:当操作结果具有一个较高维度作为原始值时使用,例如Series.to_frame()
和DataFrame.to_panel()
。下表显示了默认情况下pandas
数据结构如何定义构造函数属性。
属性属性 | 103 |Series |
104 | DataFrame |
105 | Panel |
106 |
---|---|---|---|
_constructor |
110 | Series |
111 | DataFrame |
112 | Panel |
113 |
_constructor_sliced |
115 | NotImplementedError |
116 | Series |
117 | DataFrame |
118 |
_constructor_expanddim |
120 | DataFrame |
121 | Panel |
122 | NotImplementedError |
123 |
下面的示例显示如何定义SubclassedSeries
和SubclassedDataFrame
覆盖构造函数属性。
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 |
>>> 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 |
要让原始数据结构具有其他属性,您应该让pandas
知道添加了什么属性。pandas
将未知属性映射到覆盖__getattribute__
的数据名称。定义原始属性可以通过以下两种方式之一完成:
_internal_names
和_internal_names_set
。_metadata
。下面是一个定义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 |
>>> 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 |
4 |8 | 9 |原文:http://pandas.pydata.org/pandas-docs/stable/overview.html
5 | 6 |校对:(虚位以待)
7 |
pandas
包含以下内容
11 |22 |12 |
21 |- 面板数据标记功能,其中主要的是Series和DataFrame
13 |- 索引功能,其中分为简单轴索引和多层/多级轴索引
14 |- 用于聚合和转换数据集的引擎集成组
15 |- 生成日期范围(日期范围)和自定义日期偏移,实现自定义频率
16 |- 输入/输出工具:从平面文件(CSV,分隔,Excel 2003)加载表格数据,以及从快速高效的PyTables / HDF5格式保存和加载pandas对象。
17 |- 用于存储大多数丢失或大部分不变的数据(某些固定值)的标准数据结构的高效内存“稀疏”版本
18 |- 移动窗口统计(滚动平均,滚动标准偏差等)
19 |- 静态和移动窗口线性回归和面板回归
20 |
维度 | 32 |名称 | 33 |描述 | 34 |
---|---|---|
1 | 38 |Series | 39 |1维标记同类型数组 | 40 |
2 | 42 |DataFrame | 43 |普通2维标记大小可变的表格结构,且列能有不同类型 | 44 |
3 | 46 |Panel | 47 |普通3维标记,大小可变 | 48 |
学习 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 |
所有的pandas数据结构都是值可变的(它们包含的值可以改变),但不总是size-mutable。Series的长度不可更改,但是,可以将列插入到DataFrame中。然而,绝大多数方法产生新对象并且保持输入数据不变。一般来说,我们喜欢有利于不变性。
66 |Pandas问题和想法的第一站是Github问题跟踪器。如果你有一个一般的问题,pandas社区专家可以通过Stack Overflow回答。
70 |更长的讨论发生在开发人员邮件列表上,而Lambda Foundry的商业支持查询应发送到:支持@ lambdafoundry 。
71 |pandas于2008年4月由AQR资本管理。它是在2009年年底开源的。2011年底,AQR继续为发展提供资源,并继续提供今天的错误报告。
75 |自2012年1月起,Lambda Foundry一直提供开发资源,以及商业支持,培训和pandas咨询。
76 |pandas只是由一组世界各地的人像你一样,贡献了新的代码,错误报告,修复,评论和想法。完整的列表可以在Github上找到。
77 |pandas是PyData项目的一部分。PyData开发团队是专注于改进Python数据库的开发人员的集合。协调开发的核心团队可以在Github上找到。如果您有兴趣参与,请访问项目网站。
81 |=======
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 |
4 |8 | 9 |原文:http://pandas.pydata.org/pandas-docs/stable/r_interface.html
5 | 6 |校对:(虚位以待)
7 |
警告
11 |在v0.16.0中,pandas.rpy
接口已弃用,将在未来版本中删除。类似的功能可以通过rpy2项目访问。有关将代码从pandas.rpy
移至rpy2
函数的指南,请参阅updating部分。
在v0.16.0中,pandas.rpy
模块已弃用,用户指向rpy2
本身)。
不要将导入 pandas.rpy.common 作为 com
导入,应该做到激活rpy2中的pandas转换支持:
from rpy2.robjects import pandas2ri
18 | pandas2ri.activate()
19 |
在rpy2和pandas之间来回转换数据帧应该在很大程度上自动化(不需要显式转换,它将在大多数rpy2函数中即时完成)。
22 |要显式转换,函数为pandas2ri.py2ri()
和pandas2ri.ri2py()
。所以这些函数可以用来替换pandas中的现有函数:
com.convert_to_r_dataframe(df)
应替换为pandas2ri.py2ri(df)
com.convert_robj(rdf)
应替换为pandas2ri.ri2py(rdf)
注意:这些函数用于最新版本(rpy2 2.5.x),之前称为pandas2ri.pandas2ri()
和pandas2ri.ri2pandas()
。
pandas.rpy中的一些其他功能也可以轻松替换。例如,使用load_data
函数加载R数据,当前方法:
df_iris = com.load_data('iris')
30 |
可替换为:
33 |from rpy2.robjects import r
34 | r.data('iris')
35 | df_iris = pandas2ri.ri2py(r[name])
36 |
convert_to_r_matrix
函数可以替换为正常的pandas2ri.py2ri
以转换数据帧,随后调用R as.matrix
函数。
警告
41 |并不是rpy2中的所有转换函数都与pandas中的当前方法完全相同。如果您遇到与大熊猫相比的问题或限制,请在问题跟踪器上报告此问题。
42 |另请参见rpy2项目的文档。
44 |如果您的计算机安装了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 |
注意
59 |要通过此接口使用R程序包,您需要自己在R中安装它们。目前它无法为您安装它们。
60 |安装完R和rpy2后,您应该可以轻松导入pandas.rpy.common
。
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 |
版本0.8中的新功能。
85 |从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 |
DataFrame的索引存储为data.frame实例的rownames
属性。
您还可以使用convert_to_r_matrix获取Matrix
实例,但是请记住,它只适用于均匀类型的DataFrames(因为R矩阵不包含数据类型的信息):
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 |
4 |8 | 9 |原文:http://pandas.pydata.org/pandas-docs/stable/remote_data.html
5 | 6 |校对:(虚位以待)
7 |
删除子包pandas.io.data
以支持可单独安装的pandas-datareader包。这将允许数据模块独立更新到您的pandas安装。pandas-datareader v0.1.1
的API与pandas v0 .16.1
。(GH8961)
13 |22 |您应该替换以下的导入:
14 |17 |16 |from pandas.io import data, wb 15 |使用:
18 |21 |20 |from pandas_datareader import data, wb 19 |
ga
模块为Google Analytics API提供了一个包装,以简化检索流量数据。结果集将解析为具有从源表派生的形状和数据类型的pandas DataFrame。
您需要做的第一件事是设置对Google Analytics(分析)API的访问。请按照以下步骤操作:
29 |client_secrets.json
pandas/io
模块目录第一次使用read_ga()
函数时,将打开一个浏览器窗口,要求您对Google API进行身份验证。请继续。
以下内容将从特定媒体资源获取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 |
唯一的强制参数是metrics,
dimensions
和start_date
。我们强烈建议您始终指定account_id
,profile_id
和property_id
,以避免在Google Analytics(分析)中访问错误的数据桶。
index_col
参数指示必须将哪个维度用作索引。
filters
参数指示要应用于查询的过滤。在上面的示例中,网页网址必须包含aboutus
,访问者国家必须是法国。
详细信息如下:
74 | 79 |4 |8 | 9 |原文:http://pandas.pydata.org/pandas-docs/stable/sparse.html
5 | 6 |校对:(虚位以待)
7 |
注意
11 |在0.19.0中已删除SparsePanel
类
我们实现了“稀疏”版本的Series和DataFrame。这些在典型的“大多为0”中不稀疏。相反,您可以将这些对象视为“压缩”,其中省略任何匹配特定值(NaN
/缺失值,尽管可以选择任何值)的数据。特殊的SparseIndex
对象跟踪数据已被“稀疏化”的位置。在一个例子中,这将更有意义。所有标准的熊猫数据结构都有一个to_sparse
方法:
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 |
to_sparse
方法采用kind
参数(对于稀疏索引,请参见下文)和fill_value
。所以如果我们有一个大多数为零的系列,我们可以将它转换为稀疏与fill_value=0
:
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 |
稀疏对象存在是为了内存效率的原因。假设你有一个大的,主要是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 |
如你所见,密度(未被“压缩”的值的百分比)非常低。这个稀疏对象在磁盘(pickled)和Python解释器中占用更少的内存。在功能上,它们的行为应该与它们的稠密对应物几乎相同。
90 |任何稀疏对象都可以通过调用to_dense
转换回标准密集形式:
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 |
SparseArray
是所有稀疏索引数据结构的基本层。它是一个1维的ndarray样对象,只存储不同于fill_value
的值:
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 |
像索引对象(SparseSeries,SparseDataFrame)一样,通过调用to_dense
可以将SparseArray
转换回常规的ndarray:
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 |
SparseList
类已弃用,将在以后的版本中删除。有关SparseList
的文档,请参见以前版本的文档。
实现了两种SparseIndex
,block
和integer
。我们建议使用block
,因为它更节省内存。integer
格式保留数据不等于填充值的所有位置的数组。block
格式只跟踪数据块的位置和大小。
稀疏数据应具有与其密集表示相同的dtype。目前,支持float64
,int64
和bool
dtypes。根据原始dtype,fill_value
默认更改:
float64
:np.nan
int64
:0
bool
:False
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 |
您可以使用.astype()
更改dtype,结果也是稀疏的。请注意,.astype()
也会影响fill_value
以保持其密集表示。
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 |
如果任何值不能强制到指定的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 |
您可以将NumPy ufuncs应用于SparseArray
,并获得SparseArray
作为结果。
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 |
ufunc也适用于fill_value
。这是需要得到正确的密集结果。
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 |
实验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
.
该方法需要具有两个或更多个级别的MultiIndex
。
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 |
在下面的示例中,通过指定第一个和第二个MultiIndex
级别定义行的标签,将SparseSeries
变换为2-d数组的稀疏表示,和第四级定义列的标签。我们还指定列和行标签应按最终稀疏表示法排序。
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 |
指定不同的行和列标签(而不是排序)会产生不同的稀疏矩阵:
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 |
实现方便方法SparseSeries.from_coo()
用于从scipy.sparse.coo_matrix
创建SparseSeries
。
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 |
默认行为(dense_index=False
)只返回一个只包含非空条目的SparseSeries
。
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 |
指定dense_index=True
将产生一个索引,该索引是矩阵的行和列坐标的笛卡尔乘积。注意,如果稀疏矩阵足够大(和稀疏),这将消耗大量的存储器(相对于dense_index=False
)。
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 |
4 |8 | 9 |原文:http://pandas.pydata.org/pandas-docs/stable/tutorials.html
5 | 6 |校对:(虚位以待)
7 |
这是一份很多pandas教程的指南,主要面向pandas的新用户
10 | 15 |这本书的目标(由Julia Evans)是通过给你一些具体的例子来开始使用pandas。这些是真实数据的例子,以及所有的错误和引起异常。
18 |这里是v0.1版本的链接。有关最新的目录,请参阅pandas-cookbook GitHub存储库。要运行本教程中的示例,您需要克隆GitHub存储库并使IPython Notebook运行。请参阅如何使用本CookBook。
19 |有关更多资源,请访问主要的存储库。
34 |此指南是使用Python数据生态系统和一个有趣的开放数据集的数据分析过程的全面介绍。有四个部分涵盖所选主题如下:
51 | 57 |3 |7 | --------------------------------------------------------------------------------原文:http://pandas.pydata.org/pandas-docs/stable/whatsnew.html
4 | 5 |校对:(虚位以待)
6 |