This is a short introduction to pandas, geared mainly for new users. You can see more complex recipes in the Cookbook
Customarily, we import as follows:
See the Data Structure Intro section
Creating a Series
by passing a list of values, letting pandas create a default integer index:
Creating a DataFrame
by passing a numpy array, with a datetime index and labeled columns:
Creating a DataFrame
by passing a dict of objects that can be converted to series-like.
Having specific dtypes
If you’re using IPython, tab completion for column names (as well as public attributes) is automatically enabled. Here’s a subset of the attributes that will be completed:
As you can see, the columns A
, B
, C
, and D
are automatically tab completed. E
is there as well; the rest of the attributes have been truncated for brevity.
See the Basics section
See the top & bottom rows of the frame
Display the index, columns, and the underlying numpy data
Describe shows a quick statistic summary of your data
Transposing your data
Sorting by an axis
Sorting by values
Note
While standard Python / Numpy expressions for selecting and setting are intuitive and come in handy for interactive work, for production code, we recommend the optimized pandas data access methods, .at
, .iat
, .loc
,.iloc
and .ix
.
See the indexing documentation Indexing and Selecting Data and MultiIndex / Advanced Indexing
Selecting a single column, which yields a Series
, equivalent to df.A
Selecting via []
, which slices the rows.
See more in Selection by Label
For getting a cross section using a label
Selecting on a multi-axis by label
Showing label slicing, both endpoints are included
Reduction in the dimensions of the returned object
For getting a scalar value
For getting fast access to a scalar (equiv to the prior method)
See more in Selection by Position
Select via the position of the passed integers
By integer slices, acting similar to numpy/python
By lists of integer position locations, similar to the numpy/python style
For slicing rows explicitly
For slicing columns explicitly
For getting a value explicitly
For getting fast access to a scalar (equiv to the prior method)
Using a single column’s values to select data.
Selecting values from a DataFrame where a boolean condition is met.
Using the isin()
method for filtering:
Setting a new column automatically aligns the data by the indexes
Setting values by label
Setting values by position
Setting by assigning with a numpy array
The result of the prior setting operations
A where
operation with setting.
pandas primarily uses the value np.nan
to represent missing data. It is by default not included in computations. See the Missing Data section
Reindexing allows you to change/add/delete the index on a specified axis. This returns a copy of the data.
To drop any rows that have missing data.
Filling missing data
To get the boolean mask where values are nan
See the Basic section on Binary Ops
Operations in general exclude missing data.
Performing a descriptive statistic
Same operation on the other axis
Operating with objects that have different dimensionality and need alignment. In addition, pandas automatically broadcasts along the specified dimension.
Applying functions to the data
See more at Histogramming and Discretization
Series is equipped with a set of string processing methods in the str attribute that make it easy to operate on each element of the array, as in the code snippet below. Note that pattern-matching in str generally uses regular expressions by default (and in some cases always uses them). See more at Vectorized String Methods.
pandas provides various facilities for easily combining together Series, DataFrame, and Panel objects with various kinds of set logic for the indexes and relational algebra functionality in the case of join / merge-type operations.
See the Merging section
Concatenating pandas objects together with concat()
:
SQL style merges. See the Database style joining
Another example that can be given is:
Append rows to a dataframe. See the Appending
By “group by” we are referring to a process involving one or more of the following steps
- Splitting the data into groups based on some criteria
- Applying a function to each group independently
- Combining the results into a data structure
See the Grouping section
Grouping and then applying a function sum
to the resulting groups.
Grouping by multiple columns forms a hierarchical index, which we then apply the function.
See the sections on Hierarchical Indexing and Reshaping.
The stack()
method “compresses” a level in the DataFrame’s columns.
With a “stacked” DataFrame or Series (having a MultiIndex
as the index
), the inverse operation of stack()
is unstack()
, which by default unstacks the last level:
See the section on Pivot Tables.
We can produce pivot tables from this data very easily:
pandas has simple, powerful, and efficient functionality for performing resampling operations during frequency conversion (e.g., converting secondly data into 5-minutely data). This is extremely common in, but not limited to, financial applications. See the Time Series section
Time zone representation
Convert to another time zone
Converting between time span representations
Converting between period and timestamp enables some convenient arithmetic functions to be used. In the following example, we convert a quarterly frequency with year ending in November to 9am of the end of the month following the quarter end:
Since version 0.15, pandas can include categorical data in a DataFrame
. For full docs, see the categorical introductionand the API documentation.
Convert the raw grades to a categorical data type.
Rename the categories to more meaningful names (assigning to Series.cat.categories
is inplace!)
Reorder the categories and simultaneously add the missing categories (methods under Series .cat
return a new Series
per default).
Sorting is per order in the categories, not lexical order.
Grouping by a categorical column shows also empty categories.
Plotting docs.
On DataFrame, plot()
is a convenience to plot all of the columns with labels:
Writing to a csv file
Reading from a csv file
Reading and writing to HDFStores
Writing to a HDF5 Store
Reading from a HDF5 Store
Reading and writing to MS Excel
Writing to an excel file
Reading from an excel file
If you are trying an operation and you see an exception like:
See Comparisons for an explanation and what to do.
本文是对pandas官方网站上《10 Minutes to pandas》的一个简单的翻译,原文在这里。这篇文章是对pandas的一个简单的介绍,详细的介绍请参考:Cookbook 。习惯上,我们会按下面格式引入所需要的包:
可以通过 Data Structure Intro Setion 来查看有关该节内容的详细信息。
1、可以通过传递一个list对象来创建一个Series,pandas会默认创建整型索引:
2、通过传递一个numpy array,时间索引以及列标签来创建一个DataFrame:
3、通过传递一个能够被转换成类似序列结构的字典对象来创建一个DataFrame:
4、查看不同列的数据类型:
5、如果你使用的是IPython,使用Tab自动补全功能会自动识别所有的属性以及自定义的列,下图中是所有能够被自动识别的属性的一个子集:
详情请参阅:Basics Section
1、 查看frame中头部和尾部的行:
2、 显示索引、列和底层的numpy数据:
3、 describe()函数对于数据的快速统计汇总:
4、 对数据的转置:
5、 按轴进行排序
6、 按值进行排序
虽然标准的Python/Numpy的选择和设置表达式都能够直接派上用场,但是作为工程使用的代码,我们推荐使用经过优化的pandas数据访问方式: .at, .iat, .loc, .iloc 和 .ix详情请参阅Indexing and Selecing Data 和 MultiIndex / Advanced Indexing。
l 获取
1、 选择一个单独的列,这将会返回一个Series,等同于df.A:
2、 通过[]进行选择,这将会对行进行切片
l 通过标签选择
1、 使用标签来获取一个交叉的区域
2、 通过标签来在多个轴上进行选择
3、 标签切片
4、 对于返回的对象进行维度缩减
5、 获取一个标量
6、 快速访问一个标量(与上一个方法等价)
l 通过位置选择
1、 通过传递数值进行位置选择(选择的是行)
2、 通过数值进行切片,与numpy/python中的情况类似
3、 通过指定一个位置的列表,与numpy/python中的情况类似
4、 对行进行切片
5、 对列进行切片
6、 获取特定的值
l 布尔索引
1、 使用一个单独列的值来选择数据:
2、 使用where操作来选择数据:
3、 使用isin()方法来过滤:
l 设置
1、 设置一个新的列:
2、 通过标签设置新的值:
3、 通过位置设置新的值:
4、 通过一个numpy数组设置一组新值:
上述操作结果如下:
5、 通过where操作来设置新的值:
在pandas中,使用np.nan来代替缺失值,这些值将默认不会包含在计算中,详情请参阅:Missing Data Section。
1、 reindex()方法可以对指定轴上的索引进行改变/增加/删除操作,这将返回原始数据的一个拷贝:、
2、 去掉包含缺失值的行:
3、 对缺失值进行填充:
4、 对数据进行布尔填充:
详情请参与 Basic Section On Binary Ops
l 统计(相关操作通常情况下不包括缺失值)
1、 执行描述性统计:
2、 在其他轴上进行相同的操作:
3、 对于拥有不同维度,需要对齐的对象进行操作。Pandas会自动的沿着指定的维度进行广播:
l Apply
1、 对数据应用函数:
l 直方图
具体请参照:Histogramming and Discretization
l 字符串方法
Series对象在其str属性中配备了一组字符串处理方法,可以很容易的应用到数组中的每个元素,如下段代码所示。更多详情请参考:Vectorized String Methods.
Pandas提供了大量的方法能够轻松的对Series,DataFrame和Panel对象进行各种符合各种逻辑关系的合并操作。具体请参阅:Merging section
l Concat
l Join 类似于SQL类型的合并,具体请参阅:Database style joining
l Append 将一行连接到一个DataFrame上,具体请参阅Appending:
对于”group by”操作,我们通常是指以下一个或多个操作步骤:
l (Splitting)按照一些规则将数据分为不同的组;
l (Applying)对于每组数据分别执行一个函数;
l (Combining)将结果组合到一个数据结构中;
详情请参阅:Grouping section
1、 分组并对每个分组执行sum函数:
2、 通过多个列进行分组形成一个层次索引,然后执行函数:
详情请参阅 Hierarchical Indexing 和 Reshaping。
l Stack
l 数据透视表,详情请参阅:Pivot Tables.
可以从这个数据中轻松的生成数据透视表:
Pandas在对频率转换进行重新采样时拥有简单、强大且高效的功能(如将按秒采样的数据转换为按5分钟为单位进行采样的数据)。这种操作在金融领域非常常见。具体参考:Time Series section。
1、 时区表示:
2、 时区转换:
3、 时间跨度转换:
4、 时期和时间戳之间的转换使得可以使用一些方便的算术函数。
从0.15版本开始,pandas可以在DataFrame中支持Categorical类型的数据,详细 介绍参看:categorical introduction和API documentation。
1、 将原始的grade转换为Categorical数据类型:
2、 将Categorical类型数据重命名为更有意义的名称:
3、 对类别进行重新排序,增加缺失的类别:
4、 排序是按照Categorical的顺序进行的而不是按照字典顺序进行:
5、 对Categorical列进行排序时存在空的类别:
具体文档参看:Plotting docs
对于DataFrame来说,plot是一种将所有列及其标签进行绘制的简便方法:
l CSV,参考:Writing to a csv file
1、 写入csv文件:
2、 从csv文件中读取:
l HDF5,参考:HDFStores
1、 写入HDF5存储:
2、 从HDF5存储中读取:
l Excel,参考:MS Excel
1、 写入excel文件:
2、 从excel文件中读取: