食谱#

这是关于有用的 pandas 食谱的*简短精炼*示例和链接的存储库。我们鼓励用户为此文档添加内容。

向此部分添加有趣的链接和/或内联示例是一个很棒的*首次拉取请求*。

在可能的情况下,我们插入了简化、精炼、对新用户友好的内联示例,以增强 Stack-Overflow 和 GitHub 链接。许多链接包含比内联示例更丰富的信息。

pandas (pd) 和 NumPy (np) 是仅有的两个缩写导入的模块。其余的为方便新用户,都明确导入。

惯用法#

这里有一些巧妙的 pandas 惯用法

if-then/if-then-else on one column, and assignment to another one or more columns:

if-then…#

对一列的 if-then

对 2 列进行 if-then 赋值:

添加另一行具有不同逻辑,以处理 -else

或者在设置好掩码后使用 pandas 的 where

if-then-else using NumPy’s where()

拆分#

Split a frame with a boolean criterion

构建条件#

Select with multi-column criteria

…如果不进行赋值,则返回一个 Series

…或者(如果不进行赋值,则返回一个 Series)

…或者(赋值会修改 DataFrame)

Select rows with data closest to certain value using argsort

Dynamically reduce a list of criteria using a binary operators

可以硬编码:

…或者可以使用动态构建的条件列表来完成

选择#

DataFrame#

indexing 文档。

Using both row labels and value conditionals

使用 loc 进行面向标签的切片,使用 iloc 进行面向位置的切片 GH 2904

有两种明确的切片方法,还有第三种通用情况

  1. 面向位置(Python 切片风格:不包含结束位置)

  2. 面向标签(非 Python 切片风格:包含结束位置)

  3. 通用(任何一种切片风格:取决于切片包含标签还是位置)

当索引包含整数且起始值非零或增量非单位时,会出现歧义。

Using inverse operator (~) to take the complement of a mask

新列#

Efficiently and dynamically creating new columns using DataFrame.map (previously named applymap)

Keep other columns when using min() with groupby

方法 1:使用 idxmin() 获取最小值索引

方法 2:排序然后取每组的第一个

可以看到结果相同,除了索引不同。

多重索引#

multindexing 文档。

Creating a MultiIndex from a labeled frame

算术运算#

Performing arithmetic with a MultiIndex that needs broadcasting

切片#

Slicing a MultiIndex with xs

取第一个轴的第一个级别的横截面:

…然后是第一个轴的第二个级别。

Slicing a MultiIndex with xs, method #2

Setting portions of a MultiIndex with xs

排序#

Sort by specific column or an ordered list of columns, with a MultiIndex

部分选择,排序的必要性 GH 2995

水平#

Prepending a level to a multiindex

Flatten Hierarchical columns

缺失数据#

missing data 文档。

前向填充反转的时间序列

cumsum reset at NaN values

替换#

Using replace with backrefs

分组#

grouping 文档。

Basic grouping with apply

与 agg 不同,apply 的可调用对象接收一个子 DataFrame,这使您可以访问所有列

Using get_group

Apply to different items in a group

Expanding apply

Replacing some values with mean of the rest of a group

Sort groups by aggregated data

Create multiple aggregated columns

Create a value counts column and reassign back to the DataFrame

Shift groups of the values in a column based on the index

Select row with maximum value from each group

Grouping like Python’s itertools.groupby

展开数据#

Alignment and to-date

Rolling Computation window based on values instead of counts

Rolling Mean by Time Interval

拆分#

Splitting a frame

创建数据框列表,使用基于行中包含的逻辑的分隔符进行拆分。

透视#

Pivot 文档。

Partial sums and subtotals

Frequency table like plyr in R

Plot pandas DataFrame with year over year data

创建年和月交叉表:

应用#

Rolling apply to organize - Turning embedded lists into a MultiIndex frame

Rolling apply with a DataFrame returning a Series

滚动 apply 到多个列,其中函数在一个标量从 Series 返回之前计算一个 Series

Rolling apply with a DataFrame returning a Scalar

滚动 apply 到多个列,其中函数返回一个标量(成交量加权平均价)

时间序列#

Between times

Using indexer between time

Constructing a datetime range that excludes weekends and includes only certain times

Vectorized Lookup

Aggregation and plotting time series

将列为小时、行为日期的矩阵转换为时间序列形式的连续行序列. How to rearrange a Python pandas DataFrame?

Dealing with duplicates when reindexing a timeseries to a specified frequency

计算 DatetimeIndex 中每个条目的月份第一天

重采样#

Resample 文档.

Using Grouper instead of TimeGrouper for time grouping of values

Time grouping with some missing values

Grouper 的有效频率参数 Timeseries

Grouping using a MultiIndex

使用 TimeGrouper 和另一个分组创建子组,然后应用自定义函数 GH 3791

Resampling with custom periods

Resample intraday frame without adding new days

Resample minute data

Resample with groupby

合并#

Join 文档.

Concatenate two dataframes with overlapping index (emulate R rbind)

根据 df 的构造,可能需要 ignore_index

DataFrame 的自连接 GH 2996

How to set the index and join

KDB like asof join

Join with a criteria based on the values

Using searchsorted to merge based on values inside a range

绘图#

Plotting 文档.

Make Matplotlib look like R

Setting x-axis major and minor labels

Plotting multiple charts in an IPython Jupyter notebook

Creating a multi-line plot

Plotting a heatmap

Annotate a time-series plot

Annotate a time-series plot #2

Generate Embedded plots in excel files using Pandas, Vincent and xlsxwriter

Boxplot for each quartile of a stratifying variable

数据输入/输出#

Performance comparison of SQL vs HDF5

CSV#

CSV 文档

read_csv in action

appending to a csv

Reading a csv chunk-by-chunk

Reading only certain rows of a csv chunk-by-chunk

Reading the first few lines of a frame

读取被压缩但非 gzip/bz2 ( read_csv 原生支持的压缩格式) 的文件。 这个例子展示了一个 WinZipped 文件,但它展示了通用的方法:在一个上下文管理器中打开文件,然后使用该句柄进行读取。 See here

Inferring dtypes from a file

处理错误行 GH 2886

Write a multi-row index CSV without writing duplicates

将多个文件读取到一个 DataFrame#

将多个文件合并到一个 DataFrame 的最佳方法是逐个读取单个 DataFrame,将它们全部放入一个列表中,然后使用 pd.concat() 来合并列表中的 DataFrame:

您可以使用类似的方法来读取所有匹配某个模式的文件。 下面是一个使用 glob 的例子:

最后,这种策略也适用于 io docs 中描述的其他 pd.read_*(...) 函数。

解析多列中的日期组件#

使用格式可以更快地解析多列中的日期组件

跳过文件头和数据之间的行#

选项 1:显式传递要跳过的行#
选项 2:读取列名,然后读取数据#

SQL#

SQL 文档

Reading from databases with SQL

Excel#

Excel 文档

Reading from a filelike handle

Modifying formatting in XlsxWriter output

仅加载可见的工作表 GH 19842#issuecomment-892150745

HTML#

Reading HTML tables from a server that cannot handle the default request header

HDFStore#

HDFStores 文档

Simple queries with a Timestamp Index

使用链接的多表层级结构管理异构数据 GH 3032

Merging on-disk tables with millions of rows

Avoiding inconsistencies when writing to a store from multiple processes/threads

通过分块去重大型 Store,本质上是一种递归规约操作。 展示了一个通过分块从 csv 文件获取数据并创建 Store 的函数,同时也处理日期解析。 See here

Creating a store chunk-by-chunk from a csv file

Appending to a store, while creating a unique index

Large Data work flows

Reading in a sequence of files, then providing a global unique index to a store while appending

Groupby on a HDFStore with low group density

Groupby on a HDFStore with high group density

Hierarchical queries on a HDFStore

Counting with a HDFStore

Troubleshoot HDFStore exceptions

Setting min_itemsize with strings

Using ptrepack to create a completely-sorted-index on a store

将属性存储到组节点

您可以通过将 driver 参数传递给 PyTables 来创建或加载一个内存中的 HDFStore。更改仅在 HDFStore 关闭时写入磁盘。

二进制文件#

如果需要读取一个包含 C 结构体数组的二进制文件,pandas 可以很方便地接受 NumPy 记录数组。例如,给定在 main.c 文件中的 C 程序,并在 64 位机器上使用 gcc main.c -std=gnu99 编译,

#include <stdio.h>
#include <stdint.h>

typedef struct _Data
{
    int32_t count;
    double avg;
    float scale;
} Data;

int main(int argc, const char *argv[])
{
    size_t n = 10;
    Data d[n];

    for (int i = 0; i < n; ++i)
    {
        d[i].count = i;
        d[i].avg = i + 1.0;
        d[i].scale = (float) i + 2.0f;
    }

    FILE *file = fopen("binary.dat", "wb");
    fwrite(&d, sizeof(Data), n, file);
    fclose(file);

    return 0;
}

以下 Python 代码将二进制文件 'binary.dat' 读取到一个 pandas DataFrame 中,其中结构体的每个元素对应帧中的一个列:

names = "count", "avg", "scale"

# note that the offsets are larger than the size of the type because of
# struct padding
offsets = 0, 8, 16
formats = "i4", "f8", "f4"
dt = np.dtype({"names": names, "offsets": offsets, "formats": formats}, align=True)
df = pd.DataFrame(np.fromfile("binary.dat", dt))

备注

结构体元素的偏移量可能因创建文件的机器的架构而异。不建议使用像这样的原始二进制文件格式进行通用数据存储,因为它不具备跨平台性。我们推荐 HDF5 或 parquet,它们都受 pandas 的 IO 工具支持。

计算#

Numerical integration (sample-based) of a time series

相关性#

通常,通过传递布尔掩码给 where 来获取从 DataFrame.corr() 计算出的相关矩阵的下三角(或上三角)形式会很有用,如下所示:

The method argument within DataFrame.corr can accept a callable in addition to the named correlation types. Here we compute the distance correlation matrix for a DataFrame object.

Timedeltas#

Timedeltas 文档。

Using timedeltas

Adding and subtracting deltas and dates

Another example

与 datetime 类似,可以使用 np.nan 将值设置为 NaT。

创建示例数据#

要从给定值的组合中创建 DataFrame,类似于 R 的 expand.grid() 函数,我们可以创建一个字典,其中键是列名,值是数据值列表:

常数序列#

要判断一个序列是否具有恒定值,我们可以检查 series.nunique() <= 1。但是,一种更高效的方法(而不是先计算所有唯一值)是:

这种方法假设序列不包含缺失值。对于先丢弃 NA 值的情况,我们可以先删除这些值:

如果将缺失值视为与其他任何值不同,那么可以使用:

(请注意,此示例不区分 np.nanpd.NANone