当前位置:   article > 正文

Pandas 2.2 中文文档(一百零三)_pandapipes 中文手册

pandapipes 中文手册

原文:pandas.pydata.org/docs/

版本 0.16.2(2015 年 6 月 12 日)

原文:pandas.pydata.org/docs/whatsnew/v0.16.2.html

这是从 0.16.1 中的次要 bug 修复版本,并包括大量的 bug 修复,以及一些新功能(pipe()方法)、增强和性能改进。

我们建议所有用户升级到此版本。

重点包括:

  • 新的pipe方法,请参阅此处

  • 使用numbapandas的文档,请参阅此处。

新功能在 v0.16.2 中的变化

  • 新功能

    • 管道

    • 其他增强

  • API 更改

  • 性能改进

  • 错误修复

  • 贡献者

新功能

管道

我们引入了一个新方法DataFrame.pipe()。顾名思义,pipe应该用于将数据通过一系列函数调用传递。目标是避免混淆的嵌套函数调用,比如

# df is a DataFrame
# f, g, and h are functions that take and return DataFrames
f(g(h(df), arg1=1), arg2=2, arg3=3)  # noqa F821 
  • 1
  • 2
  • 3

逻辑从内到外流动,函数名称与它们的关键字参数分开。这可以重写为

(
    df.pipe(h)  # noqa F821
    .pipe(g, arg1=1)  # noqa F821
    .pipe(f, arg2=2, arg3=3)  # noqa F821
) 
  • 1
  • 2
  • 3
  • 4
  • 5

现在代码和逻辑都从上到下流动。关键字参数紧跟在它们的函数旁边。整体而言,代码更加可读。

在上面的示例中,函数fgh每个都期望 DataFrame 作为第一个位置参数。当您希望应用的函数将数据放在除第一个参数之外的任何位置时,传递一个(function, keyword)元组,指示 DataFrame 应该流动到何处。例如:

In [1]: import statsmodels.formula.api as sm

In [2]: bb = pd.read_csv("data/baseball.csv", index_col="id")

# sm.ols takes (formula, data)
In [3]: (
...:     bb.query("h > 0")
...:     .assign(ln_h=lambda df: np.log(df.h))
...:     .pipe((sm.ols, "data"), "hr ~ ln_h + year + g + C(lg)")
...:     .fit()
...:     .summary()
...: )
...:
Out[3]:
<class 'statsmodels.iolib.summary.Summary'>
"""
 OLS Regression Results
==============================================================================
Dep. Variable:                     hr   R-squared:                       0.685
Model:                            OLS   Adj. R-squared:                  0.665
Method:                 Least Squares   F-statistic:                     34.28
Date:                Tue, 22 Nov 2022   Prob (F-statistic):           3.48e-15
Time:                        05:35:23   Log-Likelihood:                -205.92
No. Observations:                  68   AIC:                             421.8
Df Residuals:                      63   BIC:                             432.9
Df Model:                           4
Covariance Type:            nonrobust
===============================================================================
 coef    std err          t      P>|t|      [0.025      0.975]
-------------------------------------------------------------------------------
Intercept   -8484.7720   4664.146     -1.819      0.074   -1.78e+04     835.780
C(lg)[T.NL]    -2.2736      1.325     -1.716      0.091      -4.922       0.375
ln_h           -1.3542      0.875     -1.547      0.127      -3.103       0.395
year            4.2277      2.324      1.819      0.074      -0.417       8.872
g               0.1841      0.029      6.258      0.000       0.125       0.243
==============================================================================
Omnibus:                       10.875   Durbin-Watson:                   1.999
Prob(Omnibus):                  0.004   Jarque-Bera (JB):               17.298
Skew:                           0.537   Prob(JB):                     0.000175
Kurtosis:                       5.225   Cond. No.                     1.49e+07
==============================================================================

Notes:
[1] Standard Errors assume that the covariance matrix of the errors is correctly specified.
[2] The condition number is large, 1.49e+07. This might indicate that there are
strong multicollinearity or other numerical problems.
""" 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 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

管道方法受到 Unix 管道的启发,它通过进程流传输文本。更近期的dplyrmagrittr引入了流行的(%>%)管道运算符用于R

查看更多文档。(GH 10129) ### 其他增强

  • 在 Index/Series StringMethods 中添加了rsplitGH 10303

  • 删除了 IPython 笔记本中DataFrame HTML 表示的硬编码大小限制,并将其留给 IPython 自身(仅适用于 IPython v3.0 或更高版本)。这消除了在具有大框架的笔记本中出现的重复滚动条(GH 10231)。

    请注意,笔记本有一个toggle output scrolling功能,用于限制显示非常大的框架(点击输出左侧)。您还可以使用 pandas 选项配置 DataFrame 的显示方式,请参见此处。

  • DataFrame.quantileaxis参数现在也接受indexcolumn。(GH 9543) ## API 更改

  • 如果在构造函数中同时使用offsetobservanceHoliday现在会引发NotImplementedError,而不是返回不正确的结果(GH 10217) ## 性能改进

  • 使用dtype=datetime64[ns]改进Series.resample的性能(GH 7754

  • expand=True时,提高str.split的性能(GH 10081) ## Bug 修复

  • 当给定一个一行Series时,Series.hist中会引发错误的 bug(GH 10214

  • HDFStore.select修改传递的列列表的 bug(GH 7212

  • 在 Python 3 中,Categorical repr 中display.widthNone的 bug(GH 10087

  • 在特定方向和CategoricalIndexto_json中会导致段错误的 bug(GH 10317

  • 一些 nan 函数的返回数据类型不一致的 bug(GH 10251

  • 在检查传递了有效轴的DataFrame.quantile中的 bug(GH 9543

  • groupby.apply聚合中Categorical不保留类别的错误(GH 10138

  • datetime是分数时,to_csv中忽略date_format的 bug(GH 10209

  • 混合数据类型时DataFrame.to_json中的 bug(GH 10289

  • 在合并时更新缓存的 bug(GH 10264

  • mean()中整数数据类型可能溢出的错误(GH 10172

  • 当指定 dtype 时,Panel.from_dict中未设置 dtype 的 bug(GH 10058

  • 当传递数组时,Index.union中引发AttributeError的 bug(GH 10149

  • Timestampmicrosecondquarterdayofyearweekdaysinmonth属性返回np.int类型,而不是内置的int类型的 bug(GH 10050

  • 当访问daysinmonthdayofweek属性时,NaT引发AttributeError的 bug(GH 10096

  • 使用max_seq_items=None设置时,Index repr 中的 bug(GH 10182

  • 在各种平台上使用 dateutil 获取时区数据时出现错误(GH 9059GH 8639GH 9663GH 10121

  • 在显示具有混合频率的日期时间时出现错误;将 ‘ms’ 日期时间显示到正确的精度(GH 10170

  • setitem 中的错误会将类型提升应用于整个块(GH 10280

  • Series 算术方法中的错误可能会错误地保留名称(GH 10068

  • 在多个键分组时,GroupBy.get_group 中的错误,其中一个键是分类的(GH 10132

  • 在 timedelta 算术运算后,DatetimeIndexTimedeltaIndex 的名称会丢失(GH 9926

  • 从具有 datetime64 的嵌套 dict 构建 DataFrame 时出现错误(GH 10160

  • 从具有 datetime64 键的 dict 构建 Series 时出现错误(GH 9456

  • Series.plot(label="LABEL") 中的错误未正确设置标签(GH 10119

  • plot 中的错误未默认为 matplotlib axes.grid 设置(GH 9792

  • engine='python'read_csv 解析器中,包含指数但没有小数点的字符串被解析为 int 而不是 float 的错误(GH 9565

  • 当指定 fill_value 时,Series.align 中的错误会重置 nameGH 10067

  • read_csv 中导致空 DataFrame 上未设置索引名称的错误(GH 10184

  • SparseSeries.abs 中的错误会重置 nameGH 10241

  • TimedeltaIndex 切片中的错误可能会重置频率(GH 10292

  • 在组键包含 NaT 时,GroupBy.get_group 引发 ValueError 的错误(GH 6992

  • SparseSeries 构造函数忽略输入数据名称的错误(GH 10258

  • Categorical.remove_categories 中的错误,当底层 dtype 为浮点时,删除 NaN 类别会导致 ValueErrorGH 10156

  • 在推断时间规则(WOM-5XXX)不受 to_offset 支持时,推断频率的错误(GH 9425

  • DataFrame.to_hdf()中表格格式错误会为无效(非字符串)列名引发一个看似无关的错误。现在明确禁止这样做。(GH 9057)

  • 处理空DataFrame掩码的错误(GH 10126)。

  • 修复了 MySQL 接口无法处理数字表/列名称的错误(GH 10255

  • read_csv中使用date_parser返回非[ns]时间分辨率的datetime64数组的错误(GH 10245

  • Panel.apply中当结果的ndim=0时的错误(GH 10332

  • 修复了read_hdf中无法传递auto_close的错误(GH 9327)。

  • 修复了read_hdf中无法使用打开存储的错误(GH 10330)。

  • 添加空DataFrame的错误,现在结果是一个与空DataFrame相等的DataFrameGH 10181)。

  • 修复了to_hdfHDFStore中未检查complib选择是否有效的错误(GH 4582GH 8874)。 ## 贡献者

总共有 34 人为这个版本贡献了补丁。名字后面带有“+”符号的人第一次贡献了补丁。

  • Andrew Rosenfeld

  • Artemy Kolchinsky

  • Bernard Willers +

  • Christer van der Meeren

  • Christian Hudon +

  • Constantine Glen Evans +

  • Daniel Julius Lasiman +

  • Evan Wright

  • Francesco Brundu +

  • Gaëtan de Menten +

  • Jake VanderPlas

  • James Hiebert +

  • Jeff Reback

  • Joris Van den Bossche

  • Justin Lecher +

  • Ka Wo Chen +

  • Kevin Sheppard

  • Mortada Mehyar

  • Morton Fox +

  • Robin Wilson +

  • Sinhrks

  • Stephan Hoyer

  • Thomas Grainger

  • Tom Ajamian

  • Tom Augspurger

  • Yoshiki Vázquez Baeza

  • Younggun Kim

  • austinc +

  • behzad nouri

  • jreback

  • lexual

  • rekcahpassyla +

  • scls19fr

  • sinhrks ## 新功能

管道

我们引入了一个新方法DataFrame.pipe()。正如名称所示,pipe应该用于将数据通过一系列函数调用传递。目标是避免混乱的嵌套函数调用,比如

# df is a DataFrame
# f, g, and h are functions that take and return DataFrames
f(g(h(df), arg1=1), arg2=2, arg3=3)  # noqa F821 
  • 1
  • 2
  • 3

逻辑从内到外流动,函数名称与它们的关键字参数分开。这可以重写为

(
    df.pipe(h)  # noqa F821
    .pipe(g, arg1=1)  # noqa F821
    .pipe(f, arg2=2, arg3=3)  # noqa F821
) 
  • 1
  • 2
  • 3
  • 4
  • 5

现在代码和逻辑都从上到下流动。关键字参数紧挨着它们的函数。整体代码更易读。

在上面的示例中,函数fgh每个都期望 DataFrame 作为第一个位置参数。当您希望应用的函数将数据传递到除第一个参数以外的任何位置时,请传递一个元组(function, keyword),指示 DataFrame 应该流经哪里。例如:

In [1]: import statsmodels.formula.api as sm

In [2]: bb = pd.read_csv("data/baseball.csv", index_col="id")

# sm.ols takes (formula, data)
In [3]: (
...:     bb.query("h > 0")
...:     .assign(ln_h=lambda df: np.log(df.h))
...:     .pipe((sm.ols, "data"), "hr ~ ln_h + year + g + C(lg)")
...:     .fit()
...:     .summary()
...: )
...:
Out[3]:
<class 'statsmodels.iolib.summary.Summary'>
"""
 OLS Regression Results
==============================================================================
Dep. Variable:                     hr   R-squared:                       0.685
Model:                            OLS   Adj. R-squared:                  0.665
Method:                 Least Squares   F-statistic:                     34.28
Date:                Tue, 22 Nov 2022   Prob (F-statistic):           3.48e-15
Time:                        05:35:23   Log-Likelihood:                -205.92
No. Observations:                  68   AIC:                             421.8
Df Residuals:                      63   BIC:                             432.9
Df Model:                           4
Covariance Type:            nonrobust
===============================================================================
 coef    std err          t      P>|t|      [0.025      0.975]
-------------------------------------------------------------------------------
Intercept   -8484.7720   4664.146     -1.819      0.074   -1.78e+04     835.780
C(lg)[T.NL]    -2.2736      1.325     -1.716      0.091      -4.922       0.375
ln_h           -1.3542      0.875     -1.547      0.127      -3.103       0.395
year            4.2277      2.324      1.819      0.074      -0.417       8.872
g               0.1841      0.029      6.258      0.000       0.125       0.243
==============================================================================
Omnibus:                       10.875   Durbin-Watson:                   1.999
Prob(Omnibus):                  0.004   Jarque-Bera (JB):               17.298
Skew:                           0.537   Prob(JB):                     0.000175
Kurtosis:                       5.225   Cond. No.                     1.49e+07
==============================================================================

Notes:
[1] Standard Errors assume that the covariance matrix of the errors is correctly specified.
[2] The condition number is large, 1.49e+07. This might indicate that there are
strong multicollinearity or other numerical problems.
""" 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 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

pipe 方法受到 Unix 管道的启发,通过进程流式传输文本。最近,dplyrmagrittr 引入了流行的 (%>%) 管道操作符用于 R

查看文档以获取更多信息。 (GH 10129) ### 其他增强

  • rsplit 添加到索引/系列的字符串方法中(GH 10303

  • 删除了 IPython 笔记本中 DataFrame HTML 表示的硬编码大小限制,并将其留给 IPython 自己处理(仅适用于 IPython v3.0 或更高版本)。这消除了在大框架笔记本中出现的重复滚动条(GH 10231)。

    请注意,笔记本有一个切换输出滚动功能,以限制非常大的框架的显示(通过点击输出左侧)。您还可以使用 pandas 选项配置 DataFrame 的显示方式,请参见这里。

  • DataFrame.quantileaxis 参数现在还接受 indexcolumn。 (GH 9543) ### 管道

我们引入了一个新方法 DataFrame.pipe()。如名称所示,pipe 应该用于通过一系列函数调用传递数据。目标是避免混淆的嵌套函数调用,如下所示:

# df is a DataFrame
# f, g, and h are functions that take and return DataFrames
f(g(h(df), arg1=1), arg2=2, arg3=3)  # noqa F821 
  • 1
  • 2
  • 3

逻辑从内向外流动,函数名称与其关键字参数分开。这可以重写为

(
    df.pipe(h)  # noqa F821
    .pipe(g, arg1=1)  # noqa F821
    .pipe(f, arg2=2, arg3=3)  # noqa F821
) 
  • 1
  • 2
  • 3
  • 4
  • 5

现在代码和逻辑都是自上而下的。关键字参数紧跟在它们的函数旁边。整体上,代码更加可读。

在上面的示例中,函数fgh每个都将 DataFrame 作为第一个位置参数。当您希望应用的函数将数据放在除第一个参数之外的任何位置时,请传递一个元组(function, keyword),指示 DataFrame 应该流经哪里。例如:

In [1]: import statsmodels.formula.api as sm

In [2]: bb = pd.read_csv("data/baseball.csv", index_col="id")

# sm.ols takes (formula, data)
In [3]: (
...:     bb.query("h > 0")
...:     .assign(ln_h=lambda df: np.log(df.h))
...:     .pipe((sm.ols, "data"), "hr ~ ln_h + year + g + C(lg)")
...:     .fit()
...:     .summary()
...: )
...:
Out[3]:
<class 'statsmodels.iolib.summary.Summary'>
"""
 OLS Regression Results
==============================================================================
Dep. Variable:                     hr   R-squared:                       0.685
Model:                            OLS   Adj. R-squared:                  0.665
Method:                 Least Squares   F-statistic:                     34.28
Date:                Tue, 22 Nov 2022   Prob (F-statistic):           3.48e-15
Time:                        05:35:23   Log-Likelihood:                -205.92
No. Observations:                  68   AIC:                             421.8
Df Residuals:                      63   BIC:                             432.9
Df Model:                           4
Covariance Type:            nonrobust
===============================================================================
 coef    std err          t      P>|t|      [0.025      0.975]
-------------------------------------------------------------------------------
Intercept   -8484.7720   4664.146     -1.819      0.074   -1.78e+04     835.780
C(lg)[T.NL]    -2.2736      1.325     -1.716      0.091      -4.922       0.375
ln_h           -1.3542      0.875     -1.547      0.127      -3.103       0.395
year            4.2277      2.324      1.819      0.074      -0.417       8.872
g               0.1841      0.029      6.258      0.000       0.125       0.243
==============================================================================
Omnibus:                       10.875   Durbin-Watson:                   1.999
Prob(Omnibus):                  0.004   Jarque-Bera (JB):               17.298
Skew:                           0.537   Prob(JB):                     0.000175
Kurtosis:                       5.225   Cond. No.                     1.49e+07
==============================================================================

Notes:
[1] Standard Errors assume that the covariance matrix of the errors is correctly specified.
[2] The condition number is large, 1.49e+07. This might indicate that there are
strong multicollinearity or other numerical problems.
""" 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 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

pipe 方法受到 Unix 管道的启发,通过进程流式传输文本。最近,dplyrmagrittr 引入了流行的 (%>%) 管道操作符用于 R

查看文档以获取更多信息。 (GH 10129)

其他增强

  • rsplit 添加到索引/系列的字符串方法中(GH 10303

  • 删除了 IPython 笔记本中 DataFrame HTML 表示的硬编码大小限制,将此留给 IPython 自己处理(仅适用于 IPython v3.0 或更高版本)。这消除了在大框架中出现的笔记本中的重复滚动条(GH 10231)。

    请注意,笔记本具有 切换输出滚动 功能,以限制显示非常大的框架(点击输出左侧)。您还可以使用 pandas 选项配置 DataFrame 的显示方式,请参见 此处。

  • DataFrame.quantileaxis 参数现在还接受 indexcolumn。(GH 9543

API 变更

  • 如果在构造函数中同时使用 offsetobservance,则 Holiday 现在会引发 NotImplementedError,而不是返回不正确的结果(GH 10217)。

性能改进

  • 使用 dtype=datetime64[ns] 改进了 Series.resample 的性能(GH 7754

  • expand=True 时,提高了 str.split 的性能。(GH 10081

错误修复

  • Series.hist 在给定一行 Series 时引发错误(GH 10214

  • HDFStore.select 修改传递的列列表的错误(GH 7212

  • 在 Python 3 中,display.widthNone 时,Categorical 的 repr 存在错误(GH 10087

  • 在特定方向和 CategoricalIndex 的情况下,to_json 中存在错误会导致段错误。(GH 10317

  • 一些 nan 函数的返回 dtype 不一致。(GH 10251

  • 在检查是否传递了有效的轴时,DataFrame.quantile 中存在错误。(GH 9543

  • groupby.apply 聚合中 Categorical 的错误未保留类别(GH 10138

  • 如果 datetime 是小数,则 to_csv 中会忽略 date_format 的错误。(GH 10209

  • 在混合数据类型时,DataFrame.to_json 中存在错误。(GH 10289

  • 在合并时缓存更新中存在错误。(GH 10264

  • mean() 中整数 dtype 可能会溢出的错误(GH 10172

  • Panel.from_dict 中的错误未在指定时设置 dtype。(GH 10058

  • Index.union 中的错误在传递数组时引发 AttributeError。(GH 10149

  • Timestampmicrosecondquarterdayofyearweekdaysinmonth 属性返回 np.int 类型而不是内置 int 的错误(GH 10050

  • 在访问 daysinmonthdayofweek 属性时,NaT 引发 AttributeError 的错误(GH 10096

  • 在使用 max_seq_items=None 设置时,Index repr 出现的错误(GH 10182

  • 在各种平台上使用 dateutil 获取时区数据时出现的错误(GH 9059GH 8639GH 9663GH 10121

  • 在显示具有混合频率的日期时间时,将 ‘ms’ 日期时间显示为正确的精度的错误(GH 10170

  • setitem 中应用类型提升到整个块的错误(GH 10280

  • Series 算术方法中可能错误地保留名称的错误(GH 10068

  • 在使用多个键进行分组时,其中一个键是分类时,GroupBy.get_group 中出现的错误(GH 10132

  • 在 timedelta 运算后丢失 DatetimeIndexTimedeltaIndex 的名称的错误(GH 9926

  • 在使用 datetime64 的嵌套 dict 构建 DataFrame 时出现的错误(GH 10160

  • 在使用 datetime64 键从 dict 构建 Series 时的错误(GH 9456

  • Series.plot(label="LABEL") 中未正确设置标签的错误(GH 10119

  • plot 中未默认到 matplotlib axes.grid 设置的错误(GH 9792

  • engine='python'read_csv 解析器中,导致包含指数但没有小数点的字符串被解析为 int 而不是 float 的错误(GH 9565

  • Series.align 中指定 fill_value 时重置 name 的错误(GH 10067

  • 在空 DataFrame 上,read_csv 中导致索引名称未设置的错误(GH 10184

  • SparseSeries.abs 中重置 name 的错误(GH 10241

  • TimedeltaIndex 切片可能重置频率的错误(GH 10292

  • 在组键包含 NaT 时,GroupBy.get_group 引发 ValueError 的错误(GH 6992

  • SparseSeries 构造函数中忽略输入数据名称的错误(GH 10258

  • Bug in Categorical.remove_categories,当底层 dtype 为浮点型时删除 NaN 类别会导致 ValueError 的问题 (GH 10156)。

  • Bug 修复 infer_freq 推断时间规则 (WOM-5XXX),to_offset 不支持的问题 (GH 9425)。

  • Bug in DataFrame.to_hdf(),当表格格式出现无效(非字符串)列名时会引发一个看似无关的错误。现在明确禁止这种情况。 (GH 9057)。

  • Bug 修复空的 DataFrame 掩码问题 (GH 10126)。

  • Bug 在 MySQL 接口中无法处理数字表/列名的问题 (GH 10255)。

  • Bug in read_csv,当 date_parser 返回除 [ns] 之外的其他时间分辨率的 datetime64 数组时 (GH 10245)。

  • Bug 修复 Panel.apply,当结果的 ndim=0 时 (GH 10332)。

  • Bug in read_hdf 无法传递 auto_close 的问题 (GH 9327)。

  • Bug in read_hdf 在使用 open 存储时无法使用的问题 (GH 10330)。

  • Bug 在添加空的 DataFrame 时,现在结果将是一个与空的 DataFrame .equalsDataFrame (GH 10181)。

  • Bug 修复 to_hdfHDFStore,未检查 complib 选择是否有效的问题 (GH 4582, GH 8874)。

贡献者

总共有 34 人为此版本贡献了补丁。名字后面带有“+”符号的人第一次贡献了补丁。

  • Andrew Rosenfeld

  • Artemy Kolchinsky

  • Bernard Willers +

  • Christer van der Meeren

  • Christian Hudon +

  • Constantine Glen Evans +

  • Daniel Julius Lasiman +

  • Evan Wright

  • Francesco Brundu +

  • Gaëtan de Menten +

  • Jake VanderPlas

  • James Hiebert +

  • Jeff Reback

  • Joris Van den Bossche

  • Justin Lecher +

  • Ka Wo Chen +

  • Kevin Sheppard

  • Mortada Mehyar

  • Morton Fox +

  • Robin Wilson +

  • Sinhrks

  • Stephan Hoyer

  • Thomas Grainger

  • Tom Ajamian

  • Tom Augspurger

  • Yoshiki Vázquez Baeza

  • Younggun Kim

  • austinc +

  • behzad nouri

  • jreback

  • lexual

  • rekcahpassyla +

  • scls19fr

  • sinhrks

版本 0.16.1(2015 年 5 月 11 日)

原文:pandas.pydata.org/docs/whatsnew/v0.16.1.html

这是从 0.16.0 的一个小 bug 修复版本,并包括大量的 bug 修复以及一些新功能、增强功能和性能改进。我们建议所有用户升级到这个版本。

亮点包括:

  • 支持CategoricalIndex,基于类别的索引,请参见这里

  • 如何贡献给 pandas 的新部分,请参见这里

  • 修订的“合并、连接和串联”文档,包括图示示例,以便更容易理解每个操作,请参见这里

  • 用于从 Series、DataFrames 和 Panels 中绘制随机样本的新方法sample。请参见这里

  • 默认的Index打印格式已更改为更统一的格式,请参见这里

  • 现在支持BusinessHour日期偏移,请参见这里

  • 进一步增强.str访问器,使字符串操作更加简便,请参见这里

v0.16.1 中的新内容

  • 增强功能

    • CategoricalIndex

    • 样本

    • 字符串方法增强

    • 其他增强功能

  • API 更改

    • 弃用
  • 索引表示

  • 性能改进

  • Bug 修复

  • 贡献者

警告

在 pandas 0.17.0 中,子包pandas.io.data将被移除,取而代之的是一个可以单独安装的包(GH 8961)。

增强功能

CategoricalIndex

我们引入了CategoricalIndex,这是一种新类型的索引对象,用于支持具有重复索引的索引。这是一个围绕Categorical(在 v0.15.0 中引入)的容器,允许对具有大量重复元素的索引进行高效索引和存储。在 0.16.1 之前,将 DataFrame/Series 的索引设置为category dtype 将会将其转换为常规基于对象的Index

In [1]: df = pd.DataFrame({'A': np.arange(6),
 ...:                   'B': pd.Series(list('aabbca'))
 ...:                          .astype('category', categories=list('cab'))
 ...:                   })
 ...:

In [2]: df
Out[2]:
 A  B
0  0  a
1  1  a
2  2  b
3  3  b
4  4  c
5  5  a

In [3]: df.dtypes
Out[3]:
A       int64
B    category
dtype: object

In [4]: df.B.cat.categories
Out[4]: Index(['c', 'a', 'b'], dtype='object') 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24

设置索引,将创建一个CategoricalIndex

In [5]: df2 = df.set_index('B')

In [6]: df2.index
Out[6]: CategoricalIndex(['a', 'a', 'b', 'b', 'c', 'a'], categories=['c', 'a', 'b'], ordered=False, name='B', dtype='category') 
  • 1
  • 2
  • 3
  • 4

使用__getitem__/.iloc/.loc/.ix进行索引类似于具有重复索引的索引。索引器必须在类别中,否则操作将引发错误。

In [7]: df2.loc['a']
Out[7]:
 A
B
a  0
a  1
a  5 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7

并保留CategoricalIndex

In [8]: df2.loc['a'].index
Out[8]: CategoricalIndex(['a', 'a', 'a'], categories=['c', 'a', 'b'], ordered=False, name='B', dtype='category') 
  • 1
  • 2

排序将按类别的顺序排序

In [9]: df2.sort_index()
Out[9]:
 A
B
c  4
a  0
a  1
a  5
b  2
b  3 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10

对索引的 groupby 操作也将保留索引的性质

In [10]: df2.groupby(level=0).sum()
Out[10]:
 A
B
c  4
a  6
b  5

In [11]: df2.groupby(level=0).sum().index
Out[11]: CategoricalIndex(['c', 'a', 'b'], categories=['c', 'a', 'b'], ordered=False, name='B', dtype='category') 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10

重新索引操作,将根据传递的索引器的类型返回结果索引,这意味着传递列表将返回一个普通的索引;使用Categorical进行索引将返回一个CategoricalIndex,根据传递的Categorical dtype 的类别进行索引。 这使得可以任意地对这些进行索引,即使值不在类别中,类似于如何重新索引任何 pandas 索引。

In [12]: df2.reindex(['a', 'e'])
Out[12]:
 A
B
a  0.0
a  1.0
a  5.0
e  NaN

In [13]: df2.reindex(['a', 'e']).index
Out[13]: pd.Index(['a', 'a', 'a', 'e'], dtype='object', name='B')

In [14]: df2.reindex(pd.Categorical(['a', 'e'], categories=list('abcde')))
Out[14]:
 A
B
a  0.0
a  1.0
a  5.0
e  NaN

In [15]: df2.reindex(pd.Categorical(['a', 'e'], categories=list('abcde'))).index
Out[15]: pd.CategoricalIndex(['a', 'a', 'a', 'e'],
 categories=['a', 'b', 'c', 'd', 'e'],
 ordered=False, name='B',
 dtype='category') 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26

更多信息请参见文档(GH 7629, GH 10038, GH 10039) ### 示例

Series、DataFrames 和 Panels 现在有一个新方法:sample()。该方法接受要返回的特定行数或列数,或者总行数或列数的一部分。它还具有使用或不使用替换进行抽样的选项,用于传递非均匀抽样的权重列的选项,以及设置种子值以便复制的选项。 (GH 2419)

In [1]: example_series = pd.Series([0, 1, 2, 3, 4, 5])

# When no arguments are passed, returns 1
In [2]: example_series.sample()
Out[2]: 
3    3
Length: 1, dtype: int64

# One may specify either a number of rows:
In [3]: example_series.sample(n=3)
Out[3]: 
2    2
1    1
0    0
Length: 3, dtype: int64

# Or a fraction of the rows:
In [4]: example_series.sample(frac=0.5)
Out[4]: 
1    1
5    5
3    3
Length: 3, dtype: int64

# weights are accepted.
In [5]: example_weights = [0, 0, 0.2, 0.2, 0.2, 0.4]

In [6]: example_series.sample(n=3, weights=example_weights)
Out[6]: 
2    2
4    4
3    3
Length: 3, dtype: int64

# weights will also be normalized if they do not sum to one,
# and missing values will be treated as zeros.
In [7]: example_weights2 = [0.5, 0, 0, 0, None, np.nan]

In [8]: example_series.sample(n=1, weights=example_weights2)
Out[8]: 
0    0
Length: 1, dtype: int64 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42

当应用于 DataFrame 时,可以传递列名来指定从行中抽样时的抽样权重。

In [9]: df = pd.DataFrame({"col1": [9, 8, 7, 6], "weight_column": [0.5, 0.4, 0.1, 0]})

In [10]: df.sample(n=3, weights="weight_column")
Out[10]: 
 col1  weight_column
0     9            0.5
1     8            0.4
2     7            0.1

[3 rows x 2 columns] 
```### 字符串方法增强

继续从 v0.16.0 开始,以下增强使字符串操作更容易,并且与标准的 Python 字符串操作更一致。

+   将`StringMethods`(`.str`访问器)添加到`Index` ([GH 9068](https://github.com/pandas-dev/pandas/issues/9068))

    现在`.str`访问器对于`Series`和`Index`都可用。

    ```py
    In [11]: idx = pd.Index([" jack", "jill ", " jesse ", "frank"])

    In [12]: idx.str.strip()
    Out[12]: Index(['jack', 'jill', 'jesse', 'frank'], dtype='object') 
    ```

    `.str`访问器在`Index`上的一个特殊情况是,如果字符串方法返回`bool`,`.str`访问器将返回一个`np.array`而不是布尔`Index` ([GH 8875](https://github.com/pandas-dev/pandas/issues/8875))。 这使得以下表达式可以自然地工作:

    ```py
    In [13]: idx = pd.Index(["a1", "a2", "b1", "b2"])

    In [14]: s = pd.Series(range(4), index=idx)

    In [15]: s
    Out[15]: 
    a1    0
    a2    1
    b1    2
    b2    3
    Length: 4, dtype: int64

    In [16]: idx.str.startswith("a")
    Out[16]: array([ True,  True, False, False])

    In [17]: s[s.index.str.startswith("a")]
    Out[17]: 
    a1    0
    a2    1
    Length: 2, dtype: int64 
    ```

+   以下新方法可以通过`.str`访问器访问,以将函数应用于每个值。 ([GH 9766](https://github.com/pandas-dev/pandas/issues/9766), [GH 9773](https://github.com/pandas-dev/pandas/issues/9773), [GH 10031](https://github.com/pandas-dev/pandas/issues/10031), [GH 10045](https://github.com/pandas-dev/pandas/issues/10045), [GH 10052](https://github.com/pandas-dev/pandas/issues/10052))

    |  |  | 方法 |  |  |
    | --- | --- | --- | --- | --- |
    | `capitalize()` | `swapcase()` | `normalize()` | `partition()` | `rpartition()` |
    | `index()` | `rindex()` | `translate()` |  |  |

+   `split`现在使用`expand`关键字来指定是否扩展维度。`return_type`已弃用。 ([GH 9847](https://github.com/pandas-dev/pandas/issues/9847))

    ```py
    In [18]: s = pd.Series(["a,b", "a,c", "b,c"])

    # return Series
    In [19]: s.str.split(",")
    Out[19]: 
    0    [a, b]
    1    [a, c]
    2    [b, c]
    Length: 3, dtype: object

    # return DataFrame
    In [20]: s.str.split(",", expand=True)
    Out[20]: 
     0  1
    0  a  b
    1  a  c
    2  b  c

    [3 rows x 2 columns]

    In [21]: idx = pd.Index(["a,b", "a,c", "b,c"])

    # return Index
    In [22]: idx.str.split(",")
    Out[22]: Index([['a', 'b'], ['a', 'c'], ['b', 'c']], dtype='object')

    # return MultiIndex
    In [23]: idx.str.split(",", expand=True)
    Out[23]: 
    MultiIndex([('a', 'b'),
     ('a', 'c'),
     ('b', 'c')],
     ) 
    ```

+   改进了`Index.str`的`extract`和`get_dummies`方法 ([GH 9980](https://github.com/pandas-dev/pandas/issues/9980))  ### 其他增强

+   现在支持 `BusinessHour` 偏移量,它表示从默认情况下的 `BusinessDay` 上午 09:00 - 下午 17:00 开始的工作时间。详细信息请参阅这里。([GH 7905](https://github.com/pandas-dev/pandas/issues/7905))

    ```py
    In [24]: pd.Timestamp("2014-08-01 09:00") + pd.tseries.offsets.BusinessHour()
    Out[24]: Timestamp('2014-08-01 10:00:00')

    In [25]: pd.Timestamp("2014-08-01 07:00") + pd.tseries.offsets.BusinessHour()
    Out[25]: Timestamp('2014-08-01 10:00:00')

    In [26]: pd.Timestamp("2014-08-01 16:30") + pd.tseries.offsets.BusinessHour()
    Out[26]: Timestamp('2014-08-04 09:30:00') 
    ```

+   `DataFrame.diff` 现在接受一个 `axis` 参数,用于确定差分的方向。([GH 9727](https://github.com/pandas-dev/pandas/issues/9727))

+   允许 `clip`、`clip_lower` 和 `clip_upper` 接受类似数组的参数作为阈值(这是从 0.11.0 开始的一个回归)。这些方法现在有一个 `axis` 参数,确定 Series 或 DataFrame 与阈值的对齐方式。([GH 6966](https://github.com/pandas-dev/pandas/issues/6966))

+   `DataFrame.mask()` 和 `Series.mask()` 现在支持与 `where` 相同的关键字。([GH 8801](https://github.com/pandas-dev/pandas/issues/8801))

+   `drop` 函数现在可以接受 `errors` 关键字,以抑制在目标数据中任何标签不存在时引发的 `ValueError`。([GH 6736](https://github.com/pandas-dev/pandas/issues/6736))

    ```py
    In [27]: df = pd.DataFrame(np.random.randn(3, 3), columns=["A", "B", "C"])

    In [28]: df.drop(["A", "X"], axis=1, errors="ignore")
    Out[28]: 
     B         C
    0 -0.706771 -1.039575
    1 -0.424972  0.567020
    2 -1.087401 -0.673690

    [3 rows x 2 columns] 
    ```

+   添加对使用短划线分隔年份和季度的支持,例如 2014-Q1。([GH 9688](https://github.com/pandas-dev/pandas/issues/9688))

+   允许将具有 `datetime64` 或 `timedelta64` 类型的值转换为字符串,使用 `astype(str)`。([GH 9757](https://github.com/pandas-dev/pandas/issues/9757))

+   `get_dummies` 函数现在接受 `sparse` 关键字。如果设置为 `True`,返回的 `DataFrame` 是稀疏的,例如 `SparseDataFrame`。([GH 8823](https://github.com/pandas-dev/pandas/issues/8823))

+   `Period` 现在接受 `datetime64` 作为值输入。([GH 9054](https://github.com/pandas-dev/pandas/issues/9054))

+   当时间定义中缺少前导零时,允许时间差字符串转换,例如 `0:00:00` vs `00:00:00`。([GH 9570](https://github.com/pandas-dev/pandas/issues/9570))

+   允许 `Panel.shift` 与 `axis='items'`。([GH 9890](https://github.com/pandas-dev/pandas/issues/9890))

+   尝试写入 Excel 文件现在会引发 `NotImplementedError`,如果 `DataFrame` 具有 `MultiIndex`,而不是写入损坏的 Excel 文件。([GH 9794](https://github.com/pandas-dev/pandas/issues/9794))

+   允许 `Categorical.add_categories` 接受 `Series` 或 `np.array`。([GH 9927](https://github.com/pandas-dev/pandas/issues/9927))

+   动态添加/删除 `str/dt/cat` 访问器,从 `__dir__`。([GH 9910](https://github.com/pandas-dev/pandas/issues/9910))

+   将 `normalize` 添加为 `dt` 访问器方法。([GH 10047](https://github.com/pandas-dev/pandas/issues/10047))

+   `DataFrame` 和 `Series` 现在具有 `_constructor_expanddim` 属性,作为一个更高维度数据的可覆盖构造函数。只有在真正需要时才应该使用这个属性,请参阅这里

+   `pd.lib.infer_dtype` 现在在适当情况下在 Python 3 中返回 `'bytes'`。([GH 10032](https://github.com/pandas-dev/pandas/issues/10032))  ## API 变更

+   当传递一个 `ax` 给 `df.plot( ..., ax=ax)` 时,`sharex` 关键字参数现在默认为 `False`。结果是 xlabels 和 xticklabels 的可见性将不再改变。你必须自己为图中的正确轴设置 `sharex=True` 或明确设置(但这会改变图中所有轴的可见性,而不仅仅是传递的轴!)。如果 pandas 自己创建子图(例如没有传递 `ax` 关键字参数),那么默认值仍然为 `sharex=True`,并且应用了可见性更改。

+   `assign()` 现在按字母顺序插入新列。以前的顺序是任意的。([GH 9777](https://github.com/pandas-dev/pandas/issues/9777))

+   默认情况下,`read_csv` 和 `read_table` 现在将尝试根据文件扩展名推断压缩类型。设置 `compression=None` 来恢复先前的行为(无解压缩)。([GH 9770](https://github.com/pandas-dev/pandas/issues/9770))

### 废弃

+   `Series.str.split` 的 `return_type` 关键字已被移除,改用 `expand`。([GH 9847](https://github.com/pandas-dev/pandas/issues/9847))  ## 索引表示

`Index` 及其子类的字符串表示现在已统一。如果值很少,将显示单行显示;如果有很多值,则显示多行显示(但少于 `display.max_seq_items`;如果有很多项目(> `display.max_seq_items`),则显示截断显示(数据的头部和尾部)。`MultiIndex` 的格式化保持不变(多行包装显示)。显示宽度响应选项 `display.max_seq_items`,默认为 100([GH 6482](https://github.com/pandas-dev/pandas/issues/6482))

先前的行为

```py
In [2]: pd.Index(range(4), name='foo')
Out[2]: Int64Index([0, 1, 2, 3], dtype='int64')

In [3]: pd.Index(range(104), name='foo')
Out[3]: Int64Index([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 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, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, ...], dtype='int64')

In [4]: pd.date_range('20130101', periods=4, name='foo', tz='US/Eastern')
Out[4]:
<class 'pandas.tseries.index.DatetimeIndex'>
[2013-01-01 00:00:00-05:00, ..., 2013-01-04 00:00:00-05:00]
Length: 4, Freq: D, Timezone: US/Eastern

In [5]: pd.date_range('20130101', periods=104, name='foo', tz='US/Eastern')
Out[5]:
<class 'pandas.tseries.index.DatetimeIndex'>
[2013-01-01 00:00:00-05:00, ..., 2013-04-14 00:00:00-04:00]
Length: 104, Freq: D, Timezone: US/Eastern 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 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
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77
  • 78
  • 79
  • 80
  • 81
  • 82
  • 83
  • 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
  • 136
  • 137
  • 138
  • 139
  • 140
  • 141
  • 142
  • 143
  • 144
  • 145
  • 146
  • 147
  • 148
  • 149
  • 150
  • 151
  • 152
  • 153
  • 154
  • 155
  • 156
  • 157
  • 158
  • 159
  • 160
  • 161
  • 162
  • 163
  • 164
  • 165
  • 166
  • 167
  • 168
  • 169
  • 170
  • 171
  • 172
  • 173
  • 174
  • 175
  • 176
  • 177
  • 178
  • 179
  • 180
  • 181
  • 182
  • 183
  • 184
  • 185
  • 186
  • 187

新行为

In [29]: pd.set_option("display.width", 80)

In [30]: pd.Index(range(4), name="foo")
Out[30]: RangeIndex(start=0, stop=4, step=1, name='foo')

In [31]: pd.Index(range(30), name="foo")
Out[31]: RangeIndex(start=0, stop=30, step=1, name='foo')

In [32]: pd.Index(range(104), name="foo")
Out[32]: RangeIndex(start=0, stop=104, step=1, name='foo')

In [33]: pd.CategoricalIndex(["a", "bb", "ccc", "dddd"], ordered=True, name="foobar")
Out[33]: CategoricalIndex(['a', 'bb', 'ccc', 'dddd'], categories=['a', 'bb', 'ccc', 'dddd'], ordered=True, dtype='category', name='foobar')

In [34]: pd.CategoricalIndex(["a", "bb", "ccc", "dddd"] * 10, ordered=True, name="foobar")
Out[34]: 
CategoricalIndex(['a', 'bb', 'ccc', 'dddd', 'a', 'bb', 'ccc', 'dddd', 'a',
 'bb', 'ccc', 'dddd', 'a', 'bb', 'ccc', 'dddd', 'a', 'bb',
 'ccc', 'dddd', 'a', 'bb', 'ccc', 'dddd', 'a', 'bb', 'ccc',
 'dddd', 'a', 'bb', 'ccc', 'dddd', 'a', 'bb', 'ccc', 'dddd',
 'a', 'bb', 'ccc', 'dddd'],
 categories=['a', 'bb', 'ccc', 'dddd'], ordered=True, dtype='category', name='foobar')

In [35]: pd.CategoricalIndex(["a", "bb", "ccc", "dddd"] * 100, ordered=True, name="foobar")
Out[35]: 
CategoricalIndex(['a', 'bb', 'ccc', 'dddd', 'a', 'bb', 'ccc', 'dddd', 'a',
 'bb',
 ...
 'ccc', 'dddd', 'a', 'bb', 'ccc', 'dddd', 'a', 'bb', 'ccc',
 'dddd'],
 categories=['a', 'bb', 'ccc', 'dddd'], ordered=True, dtype='category', name='foobar', length=400)

In [36]: pd.date_range("20130101", periods=4, name="foo", tz="US/Eastern")
Out[36]: 
DatetimeIndex(['2013-01-01 00:00:00-05:00', '2013-01-02 00:00:00-05:00',
 '2013-01-03 00:00:00-05:00', '2013-01-04 00:00:00-05:00'],
 dtype='datetime64[ns, US/Eastern]', name='foo', freq='D')

In [37]: pd.date_range("20130101", periods=25, freq="D")
Out[37]: 
DatetimeIndex(['2013-01-01', '2013-01-02', '2013-01-03', '2013-01-04',
 '2013-01-05', '2013-01-06', '2013-01-07', '2013-01-08',
 '2013-01-09', '2013-01-10', '2013-01-11', '2013-01-12',
 '2013-01-13', '2013-01-14', '2013-01-15', '2013-01-16',
 '2013-01-17', '2013-01-18', '2013-01-19', '2013-01-20',
 '2013-01-21', '2013-01-22', '2013-01-23', '2013-01-24',
 '2013-01-25'],
 dtype='datetime64[ns]', freq='D')

In [38]: pd.date_range("20130101", periods=104, name="foo", tz="US/Eastern")
Out[38]: 
DatetimeIndex(['2013-01-01 00:00:00-05:00', '2013-01-02 00:00:00-05:00',
 '2013-01-03 00:00:00-05:00', '2013-01-04 00:00:00-05:00',
 '2013-01-05 00:00:00-05:00', '2013-01-06 00:00:00-05:00',
 '2013-01-07 00:00:00-05:00', '2013-01-08 00:00:00-05:00',
 '2013-01-09 00:00:00-05:00', '2013-01-10 00:00:00-05:00',
 ...
 '2013-04-05 00:00:00-04:00', '2013-04-06 00:00:00-04:00',
 '2013-04-07 00:00:00-04:00', '2013-04-08 00:00:00-04:00',
 '2013-04-09 00:00:00-04:00', '2013-04-10 00:00:00-04:00',
 '2013-04-11 00:00:00-04:00', '2013-04-12 00:00:00-04:00',
 '2013-04-13 00:00:00-04:00', '2013-04-14 00:00:00-04:00'],
 dtype='datetime64[ns, US/Eastern]', name='foo', length=104, freq='D') 
```## 性能改进

+   混合数据类型的 CSV 写入性能提高了多达 5 倍,包括日期时间。([GH 9940](https://github.com/pandas-dev/pandas/issues/9940))

+   一般情况下,CSV 写入性能提高了 2 倍。([GH 9940](https://github.com/pandas-dev/pandas/issues/9940))

+   将 `pd.lib.max_len_string_array` 的性能提高了 5-7 倍。([GH 10024](https://github.com/pandas-dev/pandas/issues/10024))  ## Bug 修复

+   在 `DataFrame.plot()` 的图例中标签未正确显示的 Bug,传递 `label=` 参数有效,并且 Series 索引不再被修改。([GH 9542](https://github.com/pandas-dev/pandas/issues/9542))

+   JSON 序列化中的 Bug 导致当帧长度为零时出现段错误。([GH 9805](https://github.com/pandas-dev/pandas/issues/9805))

+   `read_csv` 中的 Bug,缺少尾随分隔符会导致段错误。([GH 5664](https://github.com/pandas-dev/pandas/issues/5664))

+   在追加时保留索引名称中的 Bug。([GH 9862](https://github.com/pandas-dev/pandas/issues/9862))

+   `scatter_matrix` 中的 Bug 绘制了意外的轴刻度标签。([GH 5662](https://github.com/pandas-dev/pandas/issues/5662))

+   修复了`StataWriter`中的错误,导致保存时更改输入`DataFrame`([GH 9795](https://github.com/pandas-dev/pandas/issues/9795)+   在使用快速聚合器时,`transform`中的错误导致长度不匹配��存在空条目([GH 9697](https://github.com/pandas-dev/pandas/issues/9697)+   `equals`中的错误导致块顺序不同时出现假阴性([GH 9330](https://github.com/pandas-dev/pandas/issues/9330)+   在多个`pd.Grouper`组合中分组时出现一个非基于时间的错误([GH 10063](https://github.com/pandas-dev/pandas/issues/10063)+   使用时读取带有时区的 postgres 表时出现`read_sql_table`错误([GH 7139](https://github.com/pandas-dev/pandas/issues/7139)+   `DataFrame`切片中的错误可能不会保留元数据([GH 9776](https://github.com/pandas-dev/pandas/issues/9776)+   `TimdeltaIndex`在固定的`HDFStore`中未正确序列化的错误([GH 9635](https://github.com/pandas-dev/pandas/issues/9635)+   `TimedeltaIndex`构造函数中的错误忽略了给定另一个`TimedeltaIndex`作为数据时的`name`([GH 10025](https://github.com/pandas-dev/pandas/issues/10025)+   `DataFrameFormatter._get_formatted_index`中的错误未将`max_colwidth`应用于`DataFrame`索引([GH 7856](https://github.com/pandas-dev/pandas/issues/7856)+   在具有只读 ndarray 数据源的`.loc`中出现错误([GH 10043](https://github.com/pandas-dev/pandas/issues/10043)+   `groupby.apply()`中的错误,如果传递的用户定义函数只返回`None`(对于所有输入),则会引发错误([GH 9685](https://github.com/pandas-dev/pandas/issues/9685)+   在 pytables 测试中始终使用临时文件([GH 9992](https://github.com/pandas-dev/pandas/issues/9992)+   连续使用`secondary_y`绘图时可能无法正确显示图例([GH 9610](https://github.com/pandas-dev/pandas/issues/9610)[GH 9779](https://github.com/pandas-dev/pandas/issues/9779)+   `DataFrame.plot(kind="hist")`中的错误导致`DataFrame`包含非数值列时出现`TypeError`([GH 9853](https://github.com/pandas-dev/pandas/issues/9853)+   重复绘制具有`DatetimeIndex`的`DataFrame`可能引发`TypeError`的错误([GH 9852](https://github.com/pandas-dev/pandas/issues/9852)+   `setup.py`中的错误允许不兼容的 cython 版本构建([GH 9827](https://github.com/pandas-dev/pandas/issues/9827)+   绘制`secondary_y`时的错误,错误地将`right_ax`属性附加到递归指定自身的次要轴上([GH 9861](https://github.com/pandas-dev/pandas/issues/9861)+   `Series.quantile`在空`Datetime`或`Timedelta`类型的`Series`上的错误([GH 9675](https://github.com/pandas-dev/pandas/issues/9675)+   `where`中的错误导致需要向上转型时结果不正确([GH 9731](https://github.com/pandas-dev/pandas/issues/9731)+   `FloatArrayFormatter` 中的 Bug,导致以十进制格式显示“小”浮点数的决策边界偏离给定的 display.precision 一个数量级 ([GH 9764](https://github.com/pandas-dev/pandas/issues/9764))

+   修复了 `DataFrame.plot()` 在传递了 `color` 和 `style` 关键字并且样式字符串中没有颜色符号时引发错误的 Bug ([GH 9671](https://github.com/pandas-dev/pandas/issues/9671))

+   在将 list-likes 与 `Index` 结合时未显示 `DeprecationWarning` ([GH 10083](https://github.com/pandas-dev/pandas/issues/10083))

+   在使用 `skip_rows` 参数时,`read_csv` 和 `read_table` 中的 Bug 如果存在空行。 ([GH 9832](https://github.com/pandas-dev/pandas/issues/9832))

+   `read_csv()` 中的 Bug 将 `index_col=True` 解释为 `1` ([GH 9798](https://github.com/pandas-dev/pandas/issues/9798))

+   在使用 `==` 进行索引相等比较时的 Bug,在 Index/MultiIndex 类型不兼容时失败 ([GH 9785](https://github.com/pandas-dev/pandas/issues/9785))

+   `SparseDataFrame` 中的 Bug,无法将 `nan` 作为列名 ([GH 8822](https://github.com/pandas-dev/pandas/issues/8822))

+   `to_msgpack` 和 `read_msgpack` 中的 Bug,zlib 和 blosc 压缩支持 ([GH 9783](https://github.com/pandas-dev/pandas/issues/9783))

+   `GroupBy.size` 的 Bug,如果按 `TimeGrouper` 分组,则不正确地附加索引名称 ([GH 9925](https://github.com/pandas-dev/pandas/issues/9925))

+   导致切片赋值异常的 Bug,因为 `length_of_indexer` 返回错误结果 ([GH 9995](https://github.com/pandas-dev/pandas/issues/9995))

+   csv 解析器中的 Bug 导致以初始空格加一个非空格字符开头的行被跳过。([GH 9710](https://github.com/pandas-dev/pandas/issues/9710))

+   在 C csv 解析器中的 Bug 导致数据以换行符后跟空白开始时出现虚假 NaN。 ([GH 10022](https://github.com/pandas-dev/pandas/issues/10022))

+   Bug 导致具有空组的元素在按 `Categorical` 分组时溢出到最终组 ([GH 9603](https://github.com/pandas-dev/pandas/issues/9603))

+   Bug,.iloc 和 .loc 行为在空数据框上不一致 ([GH 9964](https://github.com/pandas-dev/pandas/issues/9964))

+   在 `TimedeltaIndex` 上无效属性访问的 Bug,错误地引发 `ValueError` 而不是 `AttributeError` ([GH 9680](https://github.com/pandas-dev/pandas/issues/9680))

+   在分类数据和标量之间的不相等比较中的 Bug,标量不在类别中 (例如 `Series(Categorical(list("abc"), ordered=True)) > "d"`。这对所有元素返回 `False`,但现在引发 `TypeError`。相等比较现在也对 `==` 返回 `False`,对 `!=` 返回 `True`。 ([GH 9848](https://github.com/pandas-dev/pandas/issues/9848))

+   当右侧为字典时,在 DataFrame `__setitem__` 中的 Bug ([GH 9874](https://github.com/pandas-dev/pandas/issues/9874))

+   在 `where` 中的 Bug,当 dtype 为 `datetime64/timedelta64` 时,但其他 dtype 不是。 ([GH 9804](https://github.com/pandas-dev/pandas/issues/9804))

+   在 `MultiIndex.sortlevel()` 中的 Bug 导致 Unicode 级别名称中断。 ([GH 9856](https://github.com/pandas-dev/pandas/issues/9856))

+   `groupby.transform` 中的 Bug 不正确强制输出 dtype 以匹配输入 dtype。 ([GH 9807](https://github.com/pandas-dev/pandas/issues/9807))

+   在 `DataFrame` 构造函数中,当设置了 `columns` 参数,并且 `data` 是空列表时的 Bug。 ([GH 9939](https://github.com/pandas-dev/pandas/issues/9939))

+   使用 `log=True` 的条形图中的 Bug,如果所有值都小于 1,则引发 `TypeError`。 ([GH 9905](https://github.com/pandas-dev/pandas/issues/9905))

+   水平条形图中的 Bug 忽略了 `log=True`。 ([GH 9905](https://github.com/pandas-dev/pandas/issues/9905))

+   PyTables 查询中的 Bug 未使用索引返回正确结果。 ([GH 8265](https://github.com/pandas-dev/pandas/issues/8265), [GH 9676](https://github.com/pandas-dev/pandas/issues/9676))

+   当将包含 `Decimal` 类型值的 DataFrame 除以另一个 `Decimal` 时会引发 Bug。 ([GH 9787](https://github.com/pandas-dev/pandas/issues/9787))

+   当使用 DataFrames 的 asfreq 时会移除索引的名称的 Bug。 ([GH 9885](https://github.com/pandas-dev/pandas/issues/9885))

+   在重采样 BM/BQ 时导致额外的索引点的 Bug。 ([GH 9756](https://github.com/pandas-dev/pandas/issues/9756))

+   将 `AbstractHolidayCalendar` 中的缓存更改为实例级别而不是类级别,因为后者可能导致意外行为。 ([GH 9552](https://github.com/pandas-dev/pandas/issues/9552))

+   修复了多级索引 DataFrame 的 LaTeX 输出。 ([GH 9778](https://github.com/pandas-dev/pandas/issues/9778))

+   使用 `DataFrame.loc` 设置空范围时引发异常的 Bug。 ([GH 9596](https://github.com/pandas-dev/pandas/issues/9596))

+   在向现有轴网格添加新绘图时,使用共享轴的子图隐藏刻度标签时出现 Bug。 ([GH 9158](https://github.com/pandas-dev/pandas/issues/9158))

+   在对分类变量进行分组时,`transform` 和 `filter` 中的 Bug。 ([GH 9921](https://github.com/pandas-dev/pandas/issues/9921))

+   在 `transform` 中的 Bug,当分组与输入索引的数字和 dtype 相等时。 ([GH 9700](https://github.com/pandas-dev/pandas/issues/9700))

+   Google BigQuery 连接器现在根据每个方法导入依赖项。([GH 9713](https://github.com/pandas-dev/pandas/issues/9713))

+   更新了 BigQuery 连接器,不再使用已弃用的 `oauth2client.tools.run()`。 ([GH 8327](https://github.com/pandas-dev/pandas/issues/8327))

+   在子类化的 `DataFrame` 中的 Bug。 在切片或子集化时,可能不会返回正确的类。 ([GH 9632](https://github.com/pandas-dev/pandas/issues/9632))

+   `.median()` 中的 Bug,非浮点型空值未正确处理 ([GH 10040](https://github.com/pandas-dev/pandas/issues/10040))

+   Series.fillna()中的错误,在给定可转换为数字的字符串时会引发错误 ([GH 10092](https://github.com/pandas-dev/pandas/issues/10092))  ## 贡献者

总共有 58 人为此版本贡献了补丁。名字后面带有“+”符号的人是第一次贡献补丁的。

+   Alfonso MHC +

+   Andy Hayden

+   Artemy Kolchinsky

+   Chris Gilmer +

+   Chris Grinolds +

+   Dan Birken

+   David BROCHART +

+   David Hirschfeld +

+   David Stephens

+   Dr. Leo +

+   Evan Wright +

+   Frans van Dunné +

+   Hatem Nassrat +

+   Henning Sperr +

+   Hugo Herter +

+   Jan Schulz

+   Jeff Blackburne +

+   Jeff Reback

+   Jim Crist +

+   Jonas Abernot +

+   Joris Van den Bossche

+   Kerby Shedden

+   Leo Razoumov +

+   Manuel Riel +

+   Mortada Mehyar

+   Nick Burns +

+   Nick Eubank +

+   Olivier Grisel

+   Phillip Cloud

+   Pietro Battiston

+   Roy Hyunjin Han

+   Sam Zhang +

+   Scott Sanderson +

+   Sinhrks +

+   Stephan Hoyer

+   Tiago Antao

+   Tom Ajamian +

+   Tom Augspurger

+   Tomaz Berisa +

+   Vikram Shirgur +

+   Vladimir Filimonov

+   William Hogman +

+   Yasin A +

+   Younggun Kim +

+   behzad nouri

+   dsm054

+   floydsoft +

+   flying-sheep +

+   gfr +

+   jnmclarty

+   jreback

+   ksanghai +

+   lucas +

+   mschmohl +

+   ptype +

+   rockg

+   scls19fr +

+   sinhrks

## 增强

### CategoricalIndex

我们引入了`CategoricalIndex`,这是一种新类型的索引对象,用于支持具有重复索引的索引。它是围绕`Categorical`(在 v0.15.0 中引入)的容器,允许有效地索引和存储具有大量重复元素的索引。在 0.16.1 之前,将`DataFrame/Series`的索引设置为`category` dtype 将其转换为常规基于对象的`Index`。

```py
In [1]: df = pd.DataFrame({'A': np.arange(6),
 ...:                   'B': pd.Series(list('aabbca'))
 ...:                          .astype('category', categories=list('cab'))
 ...:                   })
 ...:

In [2]: df
Out[2]:
 A  B
0  0  a
1  1  a
2  2  b
3  3  b
4  4  c
5  5  a

In [3]: df.dtypes
Out[3]:
A       int64
B    category
dtype: object

In [4]: df.B.cat.categories
Out[4]: Index(['c', 'a', 'b'], dtype='object') 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 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
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77
  • 78
  • 79
  • 80
  • 81
  • 82
  • 83
  • 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
  • 136
  • 137
  • 138
  • 139
  • 140
  • 141
  • 142
  • 143
  • 144
  • 145
  • 146
  • 147
  • 148
  • 149
  • 150
  • 151
  • 152
  • 153
  • 154
  • 155
  • 156
  • 157
  • 158
  • 159
  • 160
  • 161
  • 162
  • 163
  • 164
  • 165
  • 166
  • 167
  • 168
  • 169
  • 170
  • 171
  • 172
  • 173
  • 174
  • 175
  • 176
  • 177
  • 178
  • 179
  • 180
  • 181
  • 182
  • 183
  • 184
  • 185
  • 186
  • 187
  • 188
  • 189
  • 190
  • 191
  • 192
  • 193
  • 194
  • 195
  • 196
  • 197
  • 198
  • 199
  • 200
  • 201
  • 202
  • 203
  • 204
  • 205
  • 206
  • 207
  • 208
  • 209
  • 210
  • 211
  • 212
  • 213
  • 214
  • 215
  • 216
  • 217
  • 218
  • 219
  • 220
  • 221
  • 222
  • 223
  • 224
  • 225
  • 226
  • 227
  • 228
  • 229
  • 230
  • 231
  • 232
  • 233
  • 234
  • 235
  • 236
  • 237
  • 238
  • 239
  • 240
  • 241
  • 242
  • 243
  • 244
  • 245
  • 246
  • 247
  • 248
  • 249
  • 250
  • 251
  • 252
  • 253
  • 254
  • 255
  • 256
  • 257
  • 258
  • 259
  • 260
  • 261
  • 262
  • 263
  • 264
  • 265
  • 266
  • 267
  • 268
  • 269
  • 270
  • 271
  • 272
  • 273
  • 274
  • 275
  • 276
  • 277
  • 278
  • 279
  • 280
  • 281
  • 282
  • 283
  • 284
  • 285
  • 286
  • 287
  • 288
  • 289
  • 290
  • 291
  • 292
  • 293
  • 294
  • 295
  • 296
  • 297
  • 298
  • 299
  • 300
  • 301
  • 302
  • 303
  • 304
  • 305
  • 306
  • 307
  • 308
  • 309
  • 310
  • 311
  • 312
  • 313
  • 314
  • 315
  • 316
  • 317
  • 318
  • 319
  • 320
  • 321
  • 322
  • 323
  • 324
  • 325
  • 326
  • 327
  • 328
  • 329
  • 330
  • 331
  • 332
  • 333
  • 334
  • 335
  • 336
  • 337
  • 338
  • 339
  • 340
  • 341
  • 342
  • 343
  • 344

设置索引,将创建一个CategoricalIndex

In [5]: df2 = df.set_index('B')

In [6]: df2.index
Out[6]: CategoricalIndex(['a', 'a', 'b', 'b', 'c', 'a'], categories=['c', 'a', 'b'], ordered=False, name='B', dtype='category') 
  • 1
  • 2
  • 3
  • 4

使用__getitem__/.iloc/.loc/.ix进行索引的工作方式与具有重复索引的索引类似。索引器必须在类别中,否则操作将引发异常。

In [7]: df2.loc['a']
Out[7]:
 A
B
a  0
a  1
a  5 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7

并保留CategoricalIndex

In [8]: df2.loc['a'].index
Out[8]: CategoricalIndex(['a', 'a', 'a'], categories=['c', 'a', 'b'], ordered=False, name='B', dtype='category') 
  • 1
  • 2

排序将按类别的顺序排序

In [9]: df2.sort_index()
Out[9]:
 A
B
c  4
a  0
a  1
a  5
b  2
b  3 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10

对索引进行的分组操作也会保留索引的特性

In [10]: df2.groupby(level=0).sum()
Out[10]:
 A
B
c  4
a  6
b  5

In [11]: df2.groupby(level=0).sum().index
Out[11]: CategoricalIndex(['c', 'a', 'b'], categories=['c', 'a', 'b'], ordered=False, name='B', dtype='category') 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10

重新索引操作将根据传递的索引器类型返回结果索引,这意味着传递列表将返回一个普通的Index;使用Categorical进行索引将返回一个CategoricalIndex,其索引根据传递的Categorical dtype 的类别进行索引。这使得可以任意索引这些值,即使这些值不在类别中,类似于您可以重新索引任何 pandas 索引。

In [12]: df2.reindex(['a', 'e'])
Out[12]:
 A
B
a  0.0
a  1.0
a  5.0
e  NaN

In [13]: df2.reindex(['a', 'e']).index
Out[13]: pd.Index(['a', 'a', 'a', 'e'], dtype='object', name='B')

In [14]: df2.reindex(pd.Categorical(['a', 'e'], categories=list('abcde')))
Out[14]:
 A
B
a  0.0
a  1.0
a  5.0
e  NaN

In [15]: df2.reindex(pd.Categorical(['a', 'e'], categories=list('abcde'))).index
Out[15]: pd.CategoricalIndex(['a', 'a', 'a', 'e'],
 categories=['a', 'b', 'c', 'd', 'e'],
 ordered=False, name='B',
 dtype='category') 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26

查看文档获取更多信息。(GH 7629, GH 10038, GH 10039) ### 示例

Series、DataFrames 和 Panels 现在有一个新方法:sample()。该方法接受要返回的特定行数或列数,或总行数或列数的一部分。它还有关于是否使用替换进行抽样、是否传入列作为非均匀抽样的权重以及设置种子值以便复制的选项。 (GH 2419)

In [1]: example_series = pd.Series([0, 1, 2, 3, 4, 5])

# When no arguments are passed, returns 1
In [2]: example_series.sample()
Out[2]: 
3    3
Length: 1, dtype: int64

# One may specify either a number of rows:
In [3]: example_series.sample(n=3)
Out[3]: 
2    2
1    1
0    0
Length: 3, dtype: int64

# Or a fraction of the rows:
In [4]: example_series.sample(frac=0.5)
Out[4]: 
1    1
5    5
3    3
Length: 3, dtype: int64

# weights are accepted.
In [5]: example_weights = [0, 0, 0.2, 0.2, 0.2, 0.4]

In [6]: example_series.sample(n=3, weights=example_weights)
Out[6]: 
2    2
4    4
3    3
Length: 3, dtype: int64

# weights will also be normalized if they do not sum to one,
# and missing values will be treated as zeros.
In [7]: example_weights2 = [0.5, 0, 0, 0, None, np.nan]

In [8]: example_series.sample(n=1, weights=example_weights2)
Out[8]: 
0    0
Length: 1, dtype: int64 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42

当应用于 DataFrame 时,可以通过传递列的名称来指定行抽样权重。

In [9]: df = pd.DataFrame({"col1": [9, 8, 7, 6], "weight_column": [0.5, 0.4, 0.1, 0]})

In [10]: df.sample(n=3, weights="weight_column")
Out[10]: 
 col1  weight_column
0     9            0.5
1     8            0.4
2     7            0.1

[3 rows x 2 columns] 
```### 字符串方法增强

继续自 v0.16.0,以下增强使字符串操作更简单,并与标准 Python 字符串操作更一致。

+   向 `Index` 添加了 `StringMethods`(`.str` 访问器) ([GH 9068](https://github.com/pandas-dev/pandas/issues/9068))

    `.str` 访问器现在可用于 `Series` 和 `Index`。

    ```py
    In [11]: idx = pd.Index([" jack", "jill ", " jesse ", "frank"])

    In [12]: idx.str.strip()
    Out[12]: Index(['jack', 'jill', 'jesse', 'frank'], dtype='object') 
    ```

    关于 `Index` 上的 `.str` 访问器的一个特殊情况是,如果字符串方法返回 `bool`,则 `.str` 访问器将返回一个 `np.array` 而不是布尔型 `Index` ([GH 8875](https://github.com/pandas-dev/pandas/issues/8875))。这使得以下表达式可以自然地工作:

    ```py
    In [13]: idx = pd.Index(["a1", "a2", "b1", "b2"])

    In [14]: s = pd.Series(range(4), index=idx)

    In [15]: s
    Out[15]: 
    a1    0
    a2    1
    b1    2
    b2    3
    Length: 4, dtype: int64

    In [16]: idx.str.startswith("a")
    Out[16]: array([ True,  True, False, False])

    In [17]: s[s.index.str.startswith("a")]
    Out[17]: 
    a1    0
    a2    1
    Length: 2, dtype: int64 
    ```

+   以下新方法可通过 `.str` 访问器访问,以将函数应用于每个值。([GH 9766](https://github.com/pandas-dev/pandas/issues/9766), [GH 9773](https://github.com/pandas-dev/pandas/issues/9773), [GH 10031](https://github.com/pandas-dev/pandas/issues/10031), [GH 10045](https://github.com/pandas-dev/pandas/issues/10045), [GH 10052](https://github.com/pandas-dev/pandas/issues/10052))

    |  |  | 方法 |  |  |
    | --- | --- | --- | --- | --- |
    | `capitalize()` | `swapcase()` | `normalize()` | `partition()` | `rpartition()` |
    | `index()` | `rindex()` | `translate()` |  |  |

+   `split` 现在接受 `expand` 关键字来指定是否扩展维度。`return_type` 已被弃用。 ([GH 9847](https://github.com/pandas-dev/pandas/issues/9847))

    ```py
    In [18]: s = pd.Series(["a,b", "a,c", "b,c"])

    # return Series
    In [19]: s.str.split(",")
    Out[19]: 
    0    [a, b]
    1    [a, c]
    2    [b, c]
    Length: 3, dtype: object

    # return DataFrame
    In [20]: s.str.split(",", expand=True)
    Out[20]: 
     0  1
    0  a  b
    1  a  c
    2  b  c

    [3 rows x 2 columns]

    In [21]: idx = pd.Index(["a,b", "a,c", "b,c"])

    # return Index
    In [22]: idx.str.split(",")
    Out[22]: Index([['a', 'b'], ['a', 'c'], ['b', 'c']], dtype='object')

    # return MultiIndex
    In [23]: idx.str.split(",", expand=True)
    Out[23]: 
    MultiIndex([('a', 'b'),
     ('a', 'c'),
     ('b', 'c')],
     ) 
    ```

+   改进了 `Index.str` 的 `extract` 和 `get_dummies` 方法 ([GH 9980](https://github.com/pandas-dev/pandas/issues/9980))  ### 其他增强

+   `BusinessHour` 偏移现在受支持,它表示默认从 09:00 - 17:00 开始的 `BusinessDay` 的工作小时。详情请参见这里。([GH 7905](https://github.com/pandas-dev/pandas/issues/7905))

    ```py
    In [24]: pd.Timestamp("2014-08-01 09:00") + pd.tseries.offsets.BusinessHour()
    Out[24]: Timestamp('2014-08-01 10:00:00')

    In [25]: pd.Timestamp("2014-08-01 07:00") + pd.tseries.offsets.BusinessHour()
    Out[25]: Timestamp('2014-08-01 10:00:00')

    In [26]: pd.Timestamp("2014-08-01 16:30") + pd.tseries.offsets.BusinessHour()
    Out[26]: Timestamp('2014-08-04 09:30:00') 
    ```

+   `DataFrame.diff` 现在接受一个 `axis` 参数,该参数确定差分的方向 ([GH 9727](https://github.com/pandas-dev/pandas/issues/9727))

+   允许`clip`、`clip_lower`和`clip_upper`接受类似数组的阈值作为参数(这是从 0.11.0 开始的一个回归)。 这些方法现在具有一个`axis`参数,该参数确定 Series 或 DataFrame 将如何与阈值对齐。 ([GH 6966](https://github.com/pandas-dev/pandas/issues/6966))

+   `DataFrame.mask()`和`Series.mask()`现在支持与`where`相同的关键字。 ([GH 8801](https://github.com/pandas-dev/pandas/issues/8801))

+   当目标数据中不存在任何标签时,`drop`函数现在可以接受`errors`关键字来抑制引发的`ValueError`。 ([GH 6736](https://github.com/pandas-dev/pandas/issues/6736))

    ```py
    In [27]: df = pd.DataFrame(np.random.randn(3, 3), columns=["A", "B", "C"])

    In [28]: df.drop(["A", "X"], axis=1, errors="ignore")
    Out[28]: 
     B         C
    0 -0.706771 -1.039575
    1 -0.424972  0.567020
    2 -1.087401 -0.673690

    [3 rows x 2 columns] 
    ```

+   支持使用破折号分隔年份和季度,例如 2014-Q1\. ([GH 9688](https://github.com/pandas-dev/pandas/issues/9688))

+   允许使用`astype(str)`将 dtype 为`datetime64`或`timedelta64`的值转换为字符串。 ([GH 9757](https://github.com/pandas-dev/pandas/issues/9757))

+   `get_dummies`函数现在接受`sparse`关键字。 如果设置为`True`,则返回的`DataFrame`是稀疏的,例如`SparseDataFrame`。 ([GH 8823](https://github.com/pandas-dev/pandas/issues/8823))

+   现在可以将`datetime64`作为值输入。 ([GH 9054](https://github.com/pandas-dev/pandas/issues/9054))

+   在时间定义中缺少前导零时,允许时间间隔字符串转换,例如`0:00:00`与`00:00:00`。 ([GH 9570](https://github.com/pandas-dev/pandas/issues/9570))

+   允许使用`axis='items'`对`Panel.shift`进行偏移。 ([GH 9890](https://github.com/pandas-dev/pandas/issues/9890))

+   尝试写入 excel 文件现在会引发`NotImplementedError`,如果`DataFrame`具有`MultiIndex`而不是写入损坏的 Excel 文件。 ([GH 9794](https://github.com/pandas-dev/pandas/issues/9794))

+   允许`Categorical.add_categories`接受`Series`或`np.array`。 ([GH 9927](https://github.com/pandas-dev/pandas/issues/9927))

+   从`__dir__`动态添加/删除`str/dt/cat`访问器。 ([GH 9910](https://github.com/pandas-dev/pandas/issues/9910))

+   将`normalize`添加为`dt`访问器方法。([GH 10047](https://github.com/pandas-dev/pandas/issues/10047))

+   `DataFrame`和`Series`现在具有`_constructor_expanddim`属性,作为一种更高维度数据的可重写构造函数。 只有在真正需要时才应该使用此选项,详见此处

+   `pd.lib.infer_dtype`现在在适当的情况下在 Python 3 中返回`'bytes'`。 ([GH 10032](https://github.com/pandas-dev/pandas/issues/10032))  ### CategoricalIndex

我们引入了`CategoricalIndex`,这是一种新类型的索引对象,对于支持具有重复索引的索引非常有用。 这是围绕`Categorical`(在 v0.15.0 中引入)的一个容器,允许有效地索引和存储具有大量重复元素的索引。 在 0.16.1 之前,将具有类别 dtype 的 DataFrame/Series 的索引设置为常规基于对象的索引。

```py
In [1]: df = pd.DataFrame({'A': np.arange(6),
 ...:                   'B': pd.Series(list('aabbca'))
 ...:                          .astype('category', categories=list('cab'))
 ...:                   })
 ...:

In [2]: df
Out[2]:
 A  B
0  0  a
1  1  a
2  2  b
3  3  b
4  4  c
5  5  a

In [3]: df.dtypes
Out[3]:
A       int64
B    category
dtype: object

In [4]: df.B.cat.categories
Out[4]: Index(['c', 'a', 'b'], dtype='object') 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 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
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77
  • 78
  • 79
  • 80
  • 81
  • 82
  • 83
  • 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
  • 136
  • 137
  • 138
  • 139
  • 140
  • 141
  • 142
  • 143
  • 144
  • 145
  • 146
  • 147
  • 148
  • 149
  • 150
  • 151
  • 152
  • 153
  • 154
  • 155
  • 156
  • 157
  • 158
  • 159
  • 160
  • 161
  • 162
  • 163
  • 164
  • 165
  • 166
  • 167
  • 168
  • 169
  • 170
  • 171
  • 172
  • 173
  • 174
  • 175
  • 176
  • 177
  • 178
  • 179
  • 180
  • 181
  • 182

设置索引将创建一个CategoricalIndex

In [5]: df2 = df.set_index('B')

In [6]: df2.index
Out[6]: CategoricalIndex(['a', 'a', 'b', 'b', 'c', 'a'], categories=['c', 'a', 'b'], ordered=False, name='B', dtype='category') 
  • 1
  • 2
  • 3
  • 4

使用 __getitem__/.iloc/.loc/.ix 进行索引工作方式类似于具有重复项的索引。索引器必须在分类中,否则操作将引发异常。

In [7]: df2.loc['a']
Out[7]:
 A
B
a  0
a  1
a  5 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7

并保留 CategoricalIndex

In [8]: df2.loc['a'].index
Out[8]: CategoricalIndex(['a', 'a', 'a'], categories=['c', 'a', 'b'], ordered=False, name='B', dtype='category') 
  • 1
  • 2

排序将按照类别的顺序排序

In [9]: df2.sort_index()
Out[9]:
 A
B
c  4
a  0
a  1
a  5
b  2
b  3 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10

对索引进行的 groupby 操作也将保留索引的性质

In [10]: df2.groupby(level=0).sum()
Out[10]:
 A
B
c  4
a  6
b  5

In [11]: df2.groupby(level=0).sum().index
Out[11]: CategoricalIndex(['c', 'a', 'b'], categories=['c', 'a', 'b'], ordered=False, name='B', dtype='category') 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10

重新索引操作将根据传递的索引器的类型返回结果索引,这意味着传递列表将返回一个普通的 Index;使用 Categorical 进行索引将返回一个 CategoricalIndex,根据传递的 Categorical dtype 的类别进行索引。这允许任意索引这些,即使值不在类别中,类似于如何重新索引任何 pandas 索引。

In [12]: df2.reindex(['a', 'e'])
Out[12]:
 A
B
a  0.0
a  1.0
a  5.0
e  NaN

In [13]: df2.reindex(['a', 'e']).index
Out[13]: pd.Index(['a', 'a', 'a', 'e'], dtype='object', name='B')

In [14]: df2.reindex(pd.Categorical(['a', 'e'], categories=list('abcde')))
Out[14]:
 A
B
a  0.0
a  1.0
a  5.0
e  NaN

In [15]: df2.reindex(pd.Categorical(['a', 'e'], categories=list('abcde'))).index
Out[15]: pd.CategoricalIndex(['a', 'a', 'a', 'e'],
 categories=['a', 'b', 'c', 'd', 'e'],
 ordered=False, name='B',
 dtype='category') 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26

有关更多信息,请参见文档。(GH 7629, GH 10038, GH 10039)

示例

SeriesDataFramesPanels 现在有了一个新的方法:sample()。该方法接受要返回的特定行数或列数,或总行数或列数的一部分的分数。它还具有使用或不使用替换进行抽样的选项,用于传入权重列以进行非均匀抽样的选项,并设置种子值以便进行复制。(GH 2419)

In [1]: example_series = pd.Series([0, 1, 2, 3, 4, 5])

# When no arguments are passed, returns 1
In [2]: example_series.sample()
Out[2]: 
3    3
Length: 1, dtype: int64

# One may specify either a number of rows:
In [3]: example_series.sample(n=3)
Out[3]: 
2    2
1    1
0    0
Length: 3, dtype: int64

# Or a fraction of the rows:
In [4]: example_series.sample(frac=0.5)
Out[4]: 
1    1
5    5
3    3
Length: 3, dtype: int64

# weights are accepted.
In [5]: example_weights = [0, 0, 0.2, 0.2, 0.2, 0.4]

In [6]: example_series.sample(n=3, weights=example_weights)
Out[6]: 
2    2
4    4
3    3
Length: 3, dtype: int64

# weights will also be normalized if they do not sum to one,
# and missing values will be treated as zeros.
In [7]: example_weights2 = [0.5, 0, 0, 0, None, np.nan]

In [8]: example_series.sample(n=1, weights=example_weights2)
Out[8]: 
0    0
Length: 1, dtype: int64 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42

当应用于 DataFrame 时,可以传递列的名称以指定从行中抽样时的抽样权重。

In [9]: df = pd.DataFrame({"col1": [9, 8, 7, 6], "weight_column": [0.5, 0.4, 0.1, 0]})

In [10]: df.sample(n=3, weights="weight_column")
Out[10]: 
 col1  weight_column
0     9            0.5
1     8            0.4
2     7            0.1

[3 rows x 2 columns] 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10

字符串方法增强

从 v0.16.0 继续,以下增强使字符串操作更加简单且与标准 python 字符串操作更一致。

  • Index 添加了 StringMethods.str 访问器)(GH 9068)

    .str 访问器现在对 SeriesIndex 都可用。

    In [11]: idx = pd.Index([" jack", "jill ", " jesse ", "frank"])
    
    In [12]: idx.str.strip()
    Out[12]: Index(['jack', 'jill', 'jesse', 'frank'], dtype='object') 
    
    • 1
    • 2
    • 3
    • 4

    .str 访问器在 Index 上的一个特殊情况是,如果字符串方法返回 bool,则 .str 访问器将返回一个 np.array 而不是布尔值 Index (GH 8875)。这使得以下表达式自然地工作:

    In [13]: idx = pd.Index(["a1", "a2", "b1", "b2"])
    
    In [14]: s = pd.Series(range(4), index=idx)
    
    In [15]: s
    Out[15]: 
    a1    0
    a2    1
    b1    2
    b2    3
    Length: 4, dtype: int64
    
    In [16]: idx.str.startswith("a")
    Out[16]: array([ True,  True, False, False])
    
    In [17]: s[s.index.str.startswith("a")]
    Out[17]: 
    a1    0
    a2    1
    Length: 2, dtype: int64 
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
  • 以下新方法可以通过 .str 访问器访问以将函数应用于每个值。(GH 9766, GH 9773, GH 10031, GH 10045, GH 10052)

    方法
    capitalize()swapcase()normalize()partition()rpartition()
    index()rindex()translate()
  • split 现在采用 expand 关键字来指定是否扩展维度。return_type 已弃用。(GH 9847

    In [18]: s = pd.Series(["a,b", "a,c", "b,c"])
    
    # return Series
    In [19]: s.str.split(",")
    Out[19]: 
    0    [a, b]
    1    [a, c]
    2    [b, c]
    Length: 3, dtype: object
    
    # return DataFrame
    In [20]: s.str.split(",", expand=True)
    Out[20]: 
     0  1
    0  a  b
    1  a  c
    2  b  c
    
    [3 rows x 2 columns]
    
    In [21]: idx = pd.Index(["a,b", "a,c", "b,c"])
    
    # return Index
    In [22]: idx.str.split(",")
    Out[22]: Index([['a', 'b'], ['a', 'c'], ['b', 'c']], dtype='object')
    
    # return MultiIndex
    In [23]: idx.str.split(",", expand=True)
    Out[23]: 
    MultiIndex([('a', 'b'),
     ('a', 'c'),
     ('b', 'c')],
     ) 
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
  • 改进了 Index.strextractget_dummies 方法。(GH 9980

其他增强

  • 现在支持 BusinessHour 偏移,它默认表示从 BusinessDay 上的 09:00 - 17:00 开始的工作时间。详情请参阅此处。(GH 7905

    In [24]: pd.Timestamp("2014-08-01 09:00") + pd.tseries.offsets.BusinessHour()
    Out[24]: Timestamp('2014-08-01 10:00:00')
    
    In [25]: pd.Timestamp("2014-08-01 07:00") + pd.tseries.offsets.BusinessHour()
    Out[25]: Timestamp('2014-08-01 10:00:00')
    
    In [26]: pd.Timestamp("2014-08-01 16:30") + pd.tseries.offsets.BusinessHour()
    Out[26]: Timestamp('2014-08-04 09:30:00') 
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
  • DataFrame.diff 现在接受一个 axis 参数,该参数确定差分的方向。(GH 9727

  • 允许 clipclip_lowerclip_upper 接受类似数组的阈值作为参数(这是从 0.11.0 版本中的一个回归)。这些方法现在有一个 axis 参数,确定 Series 或 DataFrame 将如何与阈值对齐。(GH 6966

  • DataFrame.mask()Series.mask() 现在支持与 where 相同的关键字。(GH 8801

  • drop 函数现在可以接受 errors 关键字以抑制在目标数据中任何标签不存在时引发的 ValueError。(GH 6736

    In [27]: df = pd.DataFrame(np.random.randn(3, 3), columns=["A", "B", "C"])
    
    In [28]: df.drop(["A", "X"], axis=1, errors="ignore")
    Out[28]: 
     B         C
    0 -0.706771 -1.039575
    1 -0.424972  0.567020
    2 -1.087401 -0.673690
    
    [3 rows x 2 columns] 
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
  • 添加了使用破折号分隔年份和季度的支持,例如 2014-Q1。(GH 9688

  • 允许使用 astype(str) 将 dtype 为 datetime64timedelta64 的值转换为字符串。(GH 9757

  • get_dummies 函数现在接受 sparse 关键字。如果设置为 True,返回的 DataFrame 是稀疏的,例如 SparseDataFrame。(GH 8823

  • Period 现在接受 datetime64 作为值输入。(GH 9054

  • 允许在时间定义中省略前导零时进行时间差字符串转换,即 0:00:0000:00:00。(GH 9570

  • 允许使用 axis='items' 进行 Panel.shift。(GH 9890

  • 如果 DataFrame 具有 MultiIndex,尝试写入 Excel 文件现在会引发 NotImplementedError,而不是写入损坏的 Excel 文件。(GH 9794

  • 允许 Categorical.add_categories 接受 Seriesnp.array。(GH 9927

  • __dir__ 动态添加/删除 str/dt/cat 访问器。(GH 9910

  • normalize 添加为 dt 访问器方法。(GH 10047

  • DataFrameSeries现在有了_constructor_expanddim属性,作为可重写的构造函数,用于一维更高维度数据。仅在确实需要时使用,参见这里

  • pd.lib.infer_dtype现在在适当的情况下,在 Python 3 中返回'bytes'GH 10032

API 更改

  • 当向 df.plot( ..., ax=ax)传入 ax 时,sharex关键字现在默认为False。其结果是 xlabels 和 xticklabels 的可见性不再改变。您必须自行设置正确的轴以使其生效,或者显式设置sharex=True(但这会改变图中所有轴的可见性,而不仅仅是传入的一个!)。如果 pandas 自己创建子图(例如没有传入ax关键字),则默认仍为sharex=True,并且可见性更改会被应用。

  • assign()现在按字母顺序插入新列。之前的顺序是任意的(GH 9777

  • 默认情况下,read_csvread_table现在将尝试根据文件扩展名推断压缩类型。设置compression=None以恢复先前的行为(无解压缩)(GH 9770

废弃

  • Series.str.splitreturn_type关键字已被移除,改用expandGH 9847

  • Series.str.splitreturn_type关键字已被移除,改用expandGH 9847

索引表示

The string representation of Index and its sub-classes have now been unified. These will show a single-line display if there are few values; a wrapped multi-line display for a lot of values (but less than display.max_seq_items; if lots of items (> display.max_seq_items) will show a truncated display (the head and tail of the data). The formatting for MultiIndex is unchanged (a multi-line wrapped display). The display width responds to the option display.max_seq_items, which is defaulted to 100. (GH 6482)

先前行为

In [2]: pd.Index(range(4), name='foo')
Out[2]: Int64Index([0, 1, 2, 3], dtype='int64')

In [3]: pd.Index(range(104), name='foo')
Out[3]: Int64Index([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 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, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, ...], dtype='int64')

In [4]: pd.date_range('20130101', periods=4, name='foo', tz='US/Eastern')
Out[4]:
<class 'pandas.tseries.index.DatetimeIndex'>
[2013-01-01 00:00:00-05:00, ..., 2013-01-04 00:00:00-05:00]
Length: 4, Freq: D, Timezone: US/Eastern

In [5]: pd.date_range('20130101', periods=104, name='foo', tz='US/Eastern')
Out[5]:
<class 'pandas.tseries.index.DatetimeIndex'>
[2013-01-01 00:00:00-05:00, ..., 2013-04-14 00:00:00-04:00]
Length: 104, Freq: D, Timezone: US/Eastern 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17

新行为

In [29]: pd.set_option("display.width", 80)

In [30]: pd.Index(range(4), name="foo")
Out[30]: RangeIndex(start=0, stop=4, step=1, name='foo')

In [31]: pd.Index(range(30), name="foo")
Out[31]: RangeIndex(start=0, stop=30, step=1, name='foo')

In [32]: pd.Index(range(104), name="foo")
Out[32]: RangeIndex(start=0, stop=104, step=1, name='foo')

In [33]: pd.CategoricalIndex(["a", "bb", "ccc", "dddd"], ordered=True, name="foobar")
Out[33]: CategoricalIndex(['a', 'bb', 'ccc', 'dddd'], categories=['a', 'bb', 'ccc', 'dddd'], ordered=True, dtype='category', name='foobar')

In [34]: pd.CategoricalIndex(["a", "bb", "ccc", "dddd"] * 10, ordered=True, name="foobar")
Out[34]: 
CategoricalIndex(['a', 'bb', 'ccc', 'dddd', 'a', 'bb', 'ccc', 'dddd', 'a',
 'bb', 'ccc', 'dddd', 'a', 'bb', 'ccc', 'dddd', 'a', 'bb',
 'ccc', 'dddd', 'a', 'bb', 'ccc', 'dddd', 'a', 'bb', 'ccc',
 'dddd', 'a', 'bb', 'ccc', 'dddd', 'a', 'bb', 'ccc', 'dddd',
 'a', 'bb', 'ccc', 'dddd'],
 categories=['a', 'bb', 'ccc', 'dddd'], ordered=True, dtype='category', name='foobar')

In [35]: pd.CategoricalIndex(["a", "bb", "ccc", "dddd"] * 100, ordered=True, name="foobar")
Out[35]: 
CategoricalIndex(['a', 'bb', 'ccc', 'dddd', 'a', 'bb', 'ccc', 'dddd', 'a',
 'bb',
 ...
 'ccc', 'dddd', 'a', 'bb', 'ccc', 'dddd', 'a', 'bb', 'ccc',
 'dddd'],
 categories=['a', 'bb', 'ccc', 'dddd'], ordered=True, dtype='category', name='foobar', length=400)

In [36]: pd.date_range("20130101", periods=4, name="foo", tz="US/Eastern")
Out[36]: 
DatetimeIndex(['2013-01-01 00:00:00-05:00', '2013-01-02 00:00:00-05:00',
 '2013-01-03 00:00:00-05:00', '2013-01-04 00:00:00-05:00'],
 dtype='datetime64[ns, US/Eastern]', name='foo', freq='D')

In [37]: pd.date_range("20130101", periods=25, freq="D")
Out[37]: 
DatetimeIndex(['2013-01-01', '2013-01-02', '2013-01-03', '2013-01-04',
 '2013-01-05', '2013-01-06', '2013-01-07', '2013-01-08',
 '2013-01-09', '2013-01-10', '2013-01-11', '2013-01-12',
 '2013-01-13', '2013-01-14', '2013-01-15', '2013-01-16',
 '2013-01-17', '2013-01-18', '2013-01-19', '2013-01-20',
 '2013-01-21', '2013-01-22', '2013-01-23', '2013-01-24',
 '2013-01-25'],
 dtype='datetime64[ns]', freq='D')

In [38]: pd.date_range("20130101", periods=104, name="foo", tz="US/Eastern")
Out[38]: 
DatetimeIndex(['2013-01-01 00:00:00-05:00', '2013-01-02 00:00:00-05:00',
 '2013-01-03 00:00:00-05:00', '2013-01-04 00:00:00-05:00',
 '2013-01-05 00:00:00-05:00', '2013-01-06 00:00:00-05:00',
 '2013-01-07 00:00:00-05:00', '2013-01-08 00:00:00-05:00',
 '2013-01-09 00:00:00-05:00', '2013-01-10 00:00:00-05:00',
 ...
 '2013-04-05 00:00:00-04:00', '2013-04-06 00:00:00-04:00',
 '2013-04-07 00:00:00-04:00', '2013-04-08 00:00:00-04:00',
 '2013-04-09 00:00:00-04:00', '2013-04-10 00:00:00-04:00',
 '2013-04-11 00:00:00-04:00', '2013-04-12 00:00:00-04:00',
 '2013-04-13 00:00:00-04:00', '2013-04-14 00:00:00-04:00'],
 dtype='datetime64[ns, US/Eastern]', name='foo', length=104, freq='D') 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 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
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63

性能改进

  • 改善了 csv 写入性能,包括混合 dtype 和 datetimes,最多提高了 5 倍(GH 9940

  • csv 写入性能总体提升了 2 倍(GH 9940

  • pd.lib.max_len_string_array的性能提升了 5-7 倍(GH 10024

Bug 修复

  • DataFrame.plot() 的图例中标签未正确显示的 Bug,传递 label= 参数可以解决,并且不再改变 Series 的索引。 (GH 9542)

  • 在 json 序列化中存在的 Bug,在一个框架的长度为零时会导致段错误。 (GH 9805)

  • read_csv 中存在的 Bug,缺少尾随分隔符会导致段错误。 (GH 5664)

  • 在附加时保留索引名称的 Bug。 (GH 9862)

  • scatter_matrix 中绘制意外的轴刻度标签的 Bug。 (GH 5662)

  • 修复了 StataWriter 中的 Bug,导致保存后更改输入的 DataFrame。 (GH 9795).

  • transform 中存在的 Bug,当存在空值条目并且正在使用快速聚合器时会导致长度不匹配。 (GH 9697)

  • equals 中存在的 Bug,在块顺序不同的情况下会导致误报负例。 (GH 9330)

  • 具有多个 pd.Grouper 的分组中存在 Bug,其中一个不基于时间。 (GH 10063)

  • 在读取带有时区的 postgres 表时存在 read_sql_table 错误。 (GH 7139)

  • 切片 DataFrame 中可能不保留元数据的 Bug。 (GH 9776)

  • TimdeltaIndex 在固定 HDFStore 中未正确序列化的 Bug。 (GH 9635)

  • 使用另一个 TimedeltaIndex 作为数据时,TimedeltaIndex 构造函数忽略 name 的 Bug。 (GH 10025).

  • DataFrameFormatter._get_formatted_index 中存在的 Bug,未将max_colwidth应用于 DataFrame 索引。 (GH 7856)

  • 使用只读 ndarray 数据源时.loc 中存在的 Bug。 (GH 10043)

  • groupby.apply() 中存在的一个 Bug,如果传入的用户定义函数只返回None(对于所有输入),会引发错误。 (GH 9685)

  • 在 pytables 测试中始终使用临时文件。 (GH 9992)

  • 持续使用 secondary_y 绘图可能不正确显示图例的 Bug。 (GH 9610, GH 9779)

  • DataFrame.plot(kind="hist") 中存在的 Bug,当 DataFrame 包含非数值列时会导致 TypeError。 (GH 9853)

  • 在重复绘制具有 DatetimeIndexDataFrame 可能会引发 TypeError 的 Bug。 (GH 9852)

  • setup.py 中的 Bug 允许不兼容的 cython 版本构建 (GH 9827)

  • 绘制 secondary_y 时的 Bug 错误地将 right_ax 属性附加到递归指定自身的次要轴上。 (GH 9861)

  • Series.quantile 中的 Bug 在空的 DatetimeTimedelta 类型的 Series 上 (GH 9675)

  • where 中的 Bug 导致需要上转时出现不正确的结果 (GH 9731)

  • FloatArrayFormatter 中的 Bug,其中在十进制格式中显示“小”浮点数的决策边界与给定的 display.precision 的数量级相差一个数量级。 (GH 9764)

  • 修复了 DataFrame.plot() 在传递 colorstyle 关键字且样式字符串中没有颜色符号时引发错误的 Bug (GH 9671)

  • 在将列表样式与 Index 结合时未显示 DeprecationWarning (GH 10083)

  • 在使用 skip_rows 参数时,read_csvread_table 中的 Bug 如果存在空行会导致跳过。 (GH 9832)

  • read_csv() 中的 Bug 将 index_col=True 解释为 1 (GH 9798)

  • 在使用 == 进行索引相等比较时,Index/MultiIndex 类型不兼容导致失败的 Bug (GH 9785)

  • SparseDataFrame 中的 Bug 无法将 nan 作为列名 (GH 8822)

  • to_msgpackread_msgpack 中的 Bug zlib 和 blosc 压缩支持 (GH 9783)

  • GroupBy.size 中的 Bug 如果按 TimeGrouper 分组,则未正确附加索引名称。 (GH 9925)

  • 在切片赋值中引发异常的 Bug,因为 length_of_indexer 返回错误��结果 (GH 9995)

  • 在 csv 解析器中导致以初始空格加一个非空格字符开头的行被跳过的 Bug。 (GH 9710)

  • 在 C csv 解析器中的 Bug 导致数据以换行符开头,后跟空格时出现虚假的 NaN。 (GH 10022)

  • 分组时,具有空组的元素会溢出到最终组的 Bug,当按 Categorical 分组时 (GH 9603)

  • 空数据框上的 .iloc 和 .loc 行为不一致的 Bug (GH 9964)

  • TimedeltaIndex 上无效属性访问的 Bug 错误地引发 ValueError 而不是 AttributeError (GH 9680)

  • 分类数据和标量之间不相等比较的错误,这些数据不在类别中(例如Series(Categorical(list("abc"), ordered=True)) > "d"。对于所有元素,这返回False,但现在会引发TypeError。相等比较现在也会对==返回False,对!=返回True。(GH 9848)

  • 在 DataFrame __setitem__中,当右侧是字典时的错误。(GH 9874)

  • where中的错误,当 dtype 为datetime64/timedelta64,但其他的 dtype 不是时。(GH 9804)

  • MultiIndex.sortlevel()中的错误导致 unicode 级别名称中断。(GH 9856)

  • groupby.transform中的错误,错误地强制输出 dtype 与输入 dtype 匹配。(GH 9807)

  • DataFrame构造函数中,当设置columns参数时,data是空列表时的错误。(GH 9939)

  • 使用log=True的条形图中的错误,如果所有值都小于 1,则会引发TypeError。(GH 9905)

  • 在水平条形图中忽略log=True的错误。(GH 9905)

  • 在 PyTables 查询中的错误,未使用索引返回正确结果。(GH 8265, GH 9676)

  • 在包含Decimal类型值的数据框除以另一个Decimal时会引发错误。(GH 9787)

  • 使用 DataFrames 作为频率时会导致索引名称丢失的错误。(GH 9885)

  • 导致在重新采样 BM/BQ 时出现额外索引点的错误。(GH 9756)

  • AbstractHolidayCalendar中的缓存更改为实例级别,而不是类级别,因为后者可能导致意外行为。(GH 9552)

  • 修复了多重索引数据框的 Latex 输出。(GH 9778)

  • 使用DataFrame.loc设置空范围时会引发异常的错误。(GH 9596)

  • 在添加新绘图到现有轴网格时,隐藏子图和共享轴的刻度标签时的错误。(GH 9158)

  • 在对分类变量进行分组时,在transformfilter中的错误。(GH 9921)

  • 在输入索引中组数和 dtype 与输入索引相等时,在transform中的错误。(GH 9700)

  • Google BigQuery 连接器现在按方法导入依赖项。(GH 9713)

  • 将 BigQuery 连接器更新为不再使用已弃用的oauth2client.tools.run()GH 8327

  • 在子类化的DataFrame中存在的错误。在对其进行切片或子集化时,可能不会返回正确的类。(GH 9632)

  • .median()中的错误,未正确处理非浮点数空值(GH 10040)

  • Series.fillna()中的错误,当给出可以转换为数字的字符串时引发错误(GH 10092)

贡献者

共有 58 人为此版本提交了补丁。名字后面带有“+”符号的人是首次贡献补丁的。

  • Alfonso MHC +

  • Andy Hayden

  • Artemy Kolchinsky

  • Chris Gilmer +

  • Chris Grinolds +

  • Dan Birken

  • David BROCHART +

  • David Hirschfeld +

  • David Stephens

  • Dr. Leo +

  • Evan Wright +

  • Frans van Dunné +

  • Hatem Nassrat +

  • Henning Sperr +

  • Hugo Herter +

  • Jan Schulz

  • Jeff Blackburne +

  • Jeff Reback

  • Jim Crist +

  • Jonas Abernot +

  • Joris Van den Bossche

  • Kerby Shedden

  • Leo Razoumov +

  • Manuel Riel +

  • Mortada Mehyar

  • Nick Burns +

  • Nick Eubank +

  • Olivier Grisel

  • Phillip Cloud

  • Pietro Battiston

  • Roy Hyunjin Han

  • Sam Zhang +

  • Scott Sanderson +

  • Sinhrks +

  • Stephan Hoyer

  • Tiago Antao

  • Tom Ajamian +

  • Tom Augspurger

  • Tomaz Berisa +

  • Vikram Shirgur +

  • Vladimir Filimonov

  • William Hogman +

  • Yasin A +

  • Younggun Kim +

  • Behzad Nouri

  • Dsm054

  • Floydsoft +

  • Flying-sheep +

  • Gfr +

  • Jnmclarty

  • Jreback

  • Ksanghai +

  • Lucas +

  • Mschmohl +

  • Ptype +

  • Rockg

  • Scls19fr +

  • Sinhrks
    ,而不是类级别,因为后者可能导致意外行为。(GH 9552)

  • 修复了多重索引数据框的 Latex 输出。(GH 9778)

  • 使用DataFrame.loc设置空范围时会引发异常的错误。(GH 9596)

  • 在添加新绘图到现有轴网格时,隐藏子图和共享轴的刻度标签时的错误。(GH 9158)

  • 在对分类变量进行分组时,在transformfilter中的错误。(GH 9921)

  • 在输入索引中组数和 dtype 与输入索引相等时,在transform中的错误。(GH 9700)

  • Google BigQuery 连接器现在按方法导入依赖项。(GH 9713)

  • 将 BigQuery 连接器更新为不再使用已弃用的oauth2client.tools.run()GH 8327

  • 在子类化的DataFrame中存在的错误。在对其进行切片或子集化时,可能不会返回正确的类。(GH 9632)

  • .median()中的错误,未正确处理非浮点数空值(GH 10040)

  • Series.fillna()中的错误,当给出可以转换为数字的字符串时引发错误(GH 10092)

贡献者

共有 58 人为此版本提交了补丁。名字后面带有“+”符号的人是首次贡献补丁的。

  • Alfonso MHC +

  • Andy Hayden

  • Artemy Kolchinsky

  • Chris Gilmer +

  • Chris Grinolds +

  • Dan Birken

  • David BROCHART +

  • David Hirschfeld +

  • David Stephens

  • Dr. Leo +

  • Evan Wright +

  • Frans van Dunné +

  • Hatem Nassrat +

  • Henning Sperr +

  • Hugo Herter +

  • Jan Schulz

  • Jeff Blackburne +

  • Jeff Reback

  • Jim Crist +

  • Jonas Abernot +

  • Joris Van den Bossche

  • Kerby Shedden

  • Leo Razoumov +

  • Manuel Riel +

  • Mortada Mehyar

  • Nick Burns +

  • Nick Eubank +

  • Olivier Grisel

  • Phillip Cloud

  • Pietro Battiston

  • Roy Hyunjin Han

  • Sam Zhang +

  • Scott Sanderson +

  • Sinhrks +

  • Stephan Hoyer

  • Tiago Antao

  • Tom Ajamian +

  • Tom Augspurger

  • Tomaz Berisa +

  • Vikram Shirgur +

  • Vladimir Filimonov

  • William Hogman +

  • Yasin A +

  • Younggun Kim +

  • Behzad Nouri

  • Dsm054

  • Floydsoft +

  • Flying-sheep +

  • Gfr +

  • Jnmclarty

  • Jreback

  • Ksanghai +

  • Lucas +

  • Mschmohl +

  • Ptype +

  • Rockg

  • Scls19fr +

  • Sinhrks

本文内容由网友自发贡献,转载请注明出处:【wpsshop博客】
推荐阅读
相关标签
  

闽ICP备14008679号