1.0.0 版本有什么新变化 (2020 年 1 月 29 日)#
以下是 pandas 1.0.0 版本中的变化。有关完整的更改日志,包括其他版本的 pandas,请参阅发行说明。
注意
pandas 1.0 版本移除了之前版本中许多已弃用的功能(概览请参见下方)。建议您先升级到 pandas 0.25 并确保您的代码没有警告,然后再升级到 pandas 1.0。
新的弃用策略#
从 pandas 1.0.0 版本开始,pandas 将采用 SemVer 的变体来管理版本发布。简而言之,
弃用将在次要版本中引入(例如 1.1.0, 1.2.0, 2.1.0, …)
弃用将在主要版本中强制执行(例如 1.0.0, 2.0.0, 3.0.0, …)
API 破坏性更改仅在主要版本中进行(实验性功能除外)
详情请参见版本策略。
增强功能#
在 rolling.apply
和 expanding.apply
中使用 Numba#
我们在 apply()
和 apply()
中添加了一个 engine
关键字,允许用户使用 Numba 而不是 Cython 执行例程。如果 apply 函数可以在 numpy 数组上操作并且数据集较大(100 万行或更多),使用 Numba 引擎可以显著提高性能。更多详情请参见滚动应用文档 (GH 28987, GH 30936)
为滚动操作定义自定义窗口#
我们添加了一个 pandas.api.indexers.BaseIndexer()
类,允许用户定义在 rolling
操作期间如何创建窗口边界。用户可以在 pandas.api.indexers.BaseIndexer()
子类上定义自己的 get_window_bounds
方法,该方法将在滚动聚合期间生成每个窗口使用的起始和结束索引。有关更多详细信息和示例用法,请参见自定义窗口滚动文档
转换为 markdown#
我们添加了 to_markdown()
,用于创建 markdown 表格 (GH 11052)
In [1]: df = pd.DataFrame({"A": [1, 2, 3], "B": [1, 2, 3]}, index=['a', 'a', 'b'])
In [2]: print(df.to_markdown())
| | A | B |
|:---|----:|----:|
| a | 1 | 1 |
| a | 2 | 2 |
| b | 3 | 3 |
实验性新功能#
实验性 NA
标量表示缺失值#
引入了一个新的 pd.NA
值(单例)来表示标量缺失值。到目前为止,pandas 使用了几个值来表示缺失数据:np.nan
用于浮点数据,np.nan
或 None
用于对象-dtype 数据,以及 pd.NaT
用于日期时间类数据。pd.NA
的目标是提供一个可在不同数据类型中一致使用的“缺失”指示符。pd.NA
目前由可空整数和布尔数据类型以及新的字符串数据类型使用 (GH 28095)。
警告
实验性功能:pd.NA
的行为仍可能在不发出警告的情况下发生变化。
例如,使用可空整数 dtype 创建一个 Series
In [3]: s = pd.Series([1, 2, None], dtype="Int64")
In [4]: s
Out[4]:
0 1
1 2
2 <NA>
Length: 3, dtype: Int64
In [5]: s[2]
Out[5]: <NA>
与 np.nan
相比,pd.NA
在某些操作中的行为不同。除了算术运算外,pd.NA
在比较操作中也会传播为“缺失”或“未知”状态
In [6]: np.nan > 1
Out[6]: False
In [7]: pd.NA > 1
Out[7]: <NA>
对于逻辑运算,pd.NA
遵循三值逻辑(或称 Kleene 逻辑)的规则。例如
In [8]: pd.NA | True
Out[8]: True
更多详情请参见用户指南中关于缺失数据的NA 部分。
专用字符串数据类型#
我们添加了 StringDtype
,这是一种专门用于字符串数据的扩展类型。以前,字符串通常存储在 object-dtype 的 NumPy 数组中。(GH 29975)
警告
StringDtype
目前被认为是实验性的。其实现和部分 API 可能会在不发出警告的情况下发生变化。
The 'string'
扩展类型解决了 object-dtype NumPy 数组的几个问题
你可能会意外地在
object
dtype 数组中存储字符串和非字符串的混合。而StringArray
只能存储字符串。object
dtype 会破坏 dtype 特定的操作,例如DataFrame.select_dtypes()
。没有明确的方法可以在排除非文本(但仍然是 object-dtype)列的同时,仅选择文本。阅读代码时,
object
dtype 数组的内容不如string
清晰。
In [9]: pd.Series(['abc', None, 'def'], dtype=pd.StringDtype())
Out[9]:
0 abc
1 <NA>
2 def
Length: 3, dtype: string
你也可以使用别名 "string"
。
In [10]: s = pd.Series(['abc', None, 'def'], dtype="string")
In [11]: s
Out[11]:
0 abc
1 <NA>
2 def
Length: 3, dtype: string
常用的字符串访问器方法(string accessor methods)仍然有效。在适当的情况下,Series 或 DataFrame 列的返回类型也将具有 string dtype。
In [12]: s.str.upper()
Out[12]:
0 ABC
1 <NA>
2 DEF
Length: 3, dtype: string
In [13]: s.str.split('b', expand=True).dtypes
Out[13]:
0 string[python]
1 string[python]
Length: 2, dtype: object
返回整数的字符串访问器方法将返回一个具有 Int64Dtype
类型的值
In [14]: s.str.count("a")
Out[14]:
0 1
1 <NA>
2 0
Length: 3, dtype: Int64
我们建议在处理字符串时明确使用 string
数据类型。更多详情请参见文本数据类型。
支持缺失值的布尔数据类型#
我们添加了 BooleanDtype
/ BooleanArray
,这是一种专门用于布尔数据的扩展类型,可以存储缺失值。基于 bool-dtype NumPy 数组的默认 bool
数据类型列只能存储 True
或 False
,不能存储缺失值。这种新的 BooleanArray
通过在一个单独的掩码中跟踪缺失情况,也可以存储缺失值。(GH 29555, GH 30095, GH 31131)
In [15]: pd.Series([True, False, None], dtype=pd.BooleanDtype())
Out[15]:
0 True
1 False
2 <NA>
Length: 3, dtype: boolean
你也可以使用别名 "boolean"
。
In [16]: s = pd.Series([True, False, None], dtype="boolean")
In [17]: s
Out[17]:
0 True
1 False
2 <NA>
Length: 3, dtype: boolean
方法 convert_dtypes
简化支持的扩展 dtype 的使用#
为了鼓励使用支持 pd.NA
的扩展 dtype,例如 StringDtype
, BooleanDtype
, Int64Dtype
, Int32Dtype
等,我们引入了 DataFrame.convert_dtypes()
和 Series.convert_dtypes()
方法。(GH 29752) (GH 30929)
示例
In [18]: df = pd.DataFrame({'x': ['abc', None, 'def'],
....: 'y': [1, 2, np.nan],
....: 'z': [True, False, True]})
....:
In [19]: df
Out[19]:
x y z
0 abc 1.0 True
1 None 2.0 False
2 def NaN True
[3 rows x 3 columns]
In [20]: df.dtypes
Out[20]:
x object
y float64
z bool
Length: 3, dtype: object
In [21]: converted = df.convert_dtypes()
In [22]: converted
Out[22]:
x y z
0 abc 1 True
1 <NA> 2 False
2 def <NA> True
[3 rows x 3 columns]
In [23]: converted.dtypes
Out[23]:
x string[python]
y Int64
z boolean
Length: 3, dtype: object
这在使用 read_csv()
和 read_excel()
等读取器读取数据后特别有用。有关描述,请参见此处。
其他增强功能#
DataFrame.to_string()
添加了max_colwidth
参数,用于控制何时截断宽列 (GH 9784)为
Series.to_numpy()
,Index.to_numpy()
和DataFrame.to_numpy()
添加了na_value
参数,用于控制缺失数据使用的值 (GH 30322)如果未明确提供,
MultiIndex.from_product()
将从输入推断级别名称 (GH 27292)DataFrame.to_latex()
现在接受caption
和label
参数 (GH 25436)具有可空整数、新字符串 dtype 和 period 数据类型的 DataFrame 现在可以转换为
pyarrow
(>=0.15.0),这意味着在使用pyarrow
引擎时,支持写入 Parquet 文件格式 (GH 28368)。从 pyarrow >= 0.16 开始,支持完整的 parquet 往返(使用to_parquet()
/read_parquet()
写入和读回)(GH 20612)。to_parquet()
现在在 pyarrow 引擎中为用户定义的 schema 正确处理schema
参数。(GH 30270)DataFrame.to_json()
现在接受一个整数参数indent
,以启用 JSON 输出的美化打印 (GH 12004)read_stata()
可以读取 Stata 119 版本的 dta 文件。(GH 28250)实现了
Window.var()
和Window.std()
函数 (GH 26597)为
DataFrame.to_string()
添加了encoding
参数,用于非 ASCII 文本 (GH 28766)为
DataFrame.to_html()
添加了encoding
参数,用于非 ASCII 文本 (GH 28663)Styler.background_gradient()
现在接受vmin
和vmax
参数 (GH 12145)Styler.format()
添加了na_rep
参数,用于帮助格式化缺失值 (GH 21527, GH 28358)read_excel()
现在可以通过传递engine='pyxlsb'
来读取二进制 Excel (.xlsb
) 文件。有关更多详细信息和示例用法,请参见二进制 Excel 文件文档。解决 GH 8540。DataFrame.to_parquet()
中的partition_cols
参数现在接受字符串 (GH 27117)pandas.read_json()
现在可以解析NaN
,Infinity
和-Infinity
(GH 12213)DataFrame 构造函数在使用
ExtensionArray
时保留其 dtype (GH 11363)DataFrame.sort_values()
和Series.sort_values()
新增了ignore_index
关键字,以便在排序后重置索引 (GH 30114)DataFrame.sort_index()
和Series.sort_index()
新增了ignore_index
关键字以重置索引 (GH 30114)DataFrame.drop_duplicates()
新增了ignore_index
关键字以重置索引 (GH 30114)添加了新的写入器,用于导出 Stata 118 和 119 版本 dta 文件,即
StataWriterUTF8
。这些文件格式支持导出包含 Unicode 字符的字符串。格式 119 支持变量数超过 32,767 的数据集 (GH 23573, GH 30959)Series.map()
现在接受collections.abc.Mapping
子类作为映射器 (GH 29733)Timestamp.fromisocalendar()
现在与 python 3.8 及以上版本兼容 (GH 28115)DataFrame.to_pickle()
和read_pickle()
现在接受 URL (GH 30163)
向后不兼容的 API 变更#
避免使用 MultiIndex.levels
中的名称#
作为 MultiIndex
重大重构的一部分,级别名称现在与级别分开存储 (GH 27242)。我们建议使用 MultiIndex.names
来访问名称,并使用 Index.set_names()
来更新名称。
为了向后兼容,您仍然可以通过级别访问名称。
In [24]: mi = pd.MultiIndex.from_product([[1, 2], ['a', 'b']], names=['x', 'y'])
In [25]: mi.levels[0].name
Out[25]: 'x'
但是,不再可能通过级别更新 MultiIndex
的名称。
In [26]: mi.levels[0].name = "new name"
---------------------------------------------------------------------------
RuntimeError Traceback (most recent call last)
Cell In[26], line 1
----> 1 mi.levels[0].name = "new name"
File ~/work/pandas/pandas/pandas/core/indexes/base.py:1690, in Index.name(self, value)
1686 @name.setter
1687 def name(self, value: Hashable) -> None:
1688 if self._no_setting_name:
1689 # Used in MultiIndex.levels to avoid silently ignoring name updates.
-> 1690 raise RuntimeError(
1691 "Cannot set name on a level of a MultiIndex. Use "
1692 "'MultiIndex.set_names' instead."
1693 )
1694 maybe_extract_name(value, None, type(self))
1695 self._name = value
RuntimeError: Cannot set name on a level of a MultiIndex. Use 'MultiIndex.set_names' instead.
In [27]: mi.names
Out[27]: FrozenList(['x', 'y'])
要更新,请使用 MultiIndex.set_names
,该方法返回一个新的 MultiIndex
。
In [28]: mi2 = mi.set_names("new name", level=0)
In [29]: mi2.names
Out[29]: FrozenList(['new name', 'y'])
IntervalArray
的新 repr#
pandas.arrays.IntervalArray
采用了一种新的 __repr__
,与其他数组类一致 (GH 25022)
pandas 0.25.x
In [1]: pd.arrays.IntervalArray.from_tuples([(0, 1), (2, 3)])
Out[2]:
IntervalArray([(0, 1], (2, 3]],
closed='right',
dtype='interval[int64]')
pandas 1.0.0
In [30]: pd.arrays.IntervalArray.from_tuples([(0, 1), (2, 3)])
Out[30]:
<IntervalArray>
[(0, 1], (2, 3]]
Length: 2, dtype: interval[int64, right]
DataFrame.rename
现在只接受一个位置参数#
DataFrame.rename()
之前会接受可能导致歧义或未定义行为的位置参数。从 pandas 1.0 开始,只有第一个参数,即沿默认轴将标签映射到新名称的参数,允许通过位置传递 (GH 29136)。
pandas 0.25.x
In [1]: df = pd.DataFrame([[1]])
In [2]: df.rename({0: 1}, {0: 2})
Out[2]:
FutureWarning: ...Use named arguments to resolve ambiguity...
2
1 1
pandas 1.0.0
In [3]: df.rename({0: 1}, {0: 2})
Traceback (most recent call last):
...
TypeError: rename() takes from 1 to 2 positional arguments but 3 were given
请注意,现在提供冲突或可能含糊不清的参数时会引发错误。
pandas 0.25.x
In [4]: df.rename({0: 1}, index={0: 2})
Out[4]:
0
1 1
In [5]: df.rename(mapper={0: 1}, index={0: 2})
Out[5]:
0
2 1
pandas 1.0.0
In [6]: df.rename({0: 1}, index={0: 2})
Traceback (most recent call last):
...
TypeError: Cannot specify both 'mapper' and any of 'index' or 'columns'
In [7]: df.rename(mapper={0: 1}, index={0: 2})
Traceback (most recent call last):
...
TypeError: Cannot specify both 'mapper' and any of 'index' or 'columns'
您仍然可以通过提供 axis
关键字参数来更改应用第一个位置参数的轴。
In [31]: df.rename({0: 1})
Out[31]:
0
1 1
[1 rows x 1 columns]
In [32]: df.rename({0: 1}, axis=1)
Out[32]:
1
0 1
[1 rows x 1 columns]
如果您想同时更新索引和列标签,请务必使用相应的关键字参数。
In [33]: df.rename(index={0: 1}, columns={0: 2})
Out[33]:
2
1 1
[1 rows x 1 columns]
DataFrame
扩展了详细信息输出#
DataFrame.info()
现在显示列摘要的行号 (GH 17304)
pandas 0.25.x
In [1]: df = pd.DataFrame({"int_col": [1, 2, 3],
... "text_col": ["a", "b", "c"],
... "float_col": [0.0, 0.1, 0.2]})
In [2]: df.info(verbose=True)
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 3 entries, 0 to 2
Data columns (total 3 columns):
int_col 3 non-null int64
text_col 3 non-null object
float_col 3 non-null float64
dtypes: float64(1), int64(1), object(1)
memory usage: 152.0+ bytes
pandas 1.0.0
In [34]: df = pd.DataFrame({"int_col": [1, 2, 3],
....: "text_col": ["a", "b", "c"],
....: "float_col": [0.0, 0.1, 0.2]})
....:
In [35]: df.info(verbose=True)
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 3 entries, 0 to 2
Data columns (total 3 columns):
# Column Non-Null Count Dtype
--- ------ -------------- -----
0 int_col 3 non-null int64
1 text_col 3 non-null object
2 float_col 3 non-null float64
dtypes: float64(1), int64(1), object(1)
memory usage: 200.0+ bytes
pandas.array()
推断变更#
pandas.array()
现在在几种情况下推断 pandas 的新扩展类型 (GH 29791)
字符串数据(包括缺失值)现在返回
arrays.StringArray
。整数数据(包括缺失值)现在返回
arrays.IntegerArray
。布尔数据(包括缺失值)现在返回新的
arrays.BooleanArray
pandas 0.25.x
In [1]: pd.array(["a", None])
Out[1]:
<PandasArray>
['a', None]
Length: 2, dtype: object
In [2]: pd.array([1, None])
Out[2]:
<PandasArray>
[1, None]
Length: 2, dtype: object
pandas 1.0.0
In [36]: pd.array(["a", None])
Out[36]:
<StringArray>
['a', <NA>]
Length: 2, dtype: string
In [37]: pd.array([1, None])
Out[37]:
<IntegerArray>
[1, <NA>]
Length: 2, dtype: Int64
提醒一下,您可以指定 dtype
来禁用所有推断。
arrays.IntegerArray
现在使用 pandas.NA
#
arrays.IntegerArray
现在使用 pandas.NA
而不是 numpy.nan
作为其缺失值标记 (GH 29964)。
pandas 0.25.x
In [1]: a = pd.array([1, 2, None], dtype="Int64")
In [2]: a
Out[2]:
<IntegerArray>
[1, 2, NaN]
Length: 3, dtype: Int64
In [3]: a[2]
Out[3]:
nan
pandas 1.0.0
In [38]: a = pd.array([1, 2, None], dtype="Int64")
In [39]: a
Out[39]:
<IntegerArray>
[1, 2, <NA>]
Length: 3, dtype: Int64
In [40]: a[2]
Out[40]: <NA>
这带来了一些 API 破坏性后果。
转换为 NumPy ndarray
转换为NumPy数组时,缺失值将是 pd.NA
,它不能转换为浮点数。因此,调用 np.asarray(integer_array, dtype="float")
现在将引发错误。
pandas 0.25.x
In [1]: np.asarray(a, dtype="float")
Out[1]:
array([ 1., 2., nan])
pandas 1.0.0
In [41]: np.asarray(a, dtype="float")
Out[41]: array([ 1., 2., nan])
请改用 arrays.IntegerArray.to_numpy()
并明确指定 na_value
。
In [42]: a.to_numpy(dtype="float", na_value=np.nan)
Out[42]: array([ 1., 2., nan])
聚合运算可以返回 pd.NA
当执行聚合运算(如求和)并设置 skipna=False
时,如果存在缺失值,结果现在将是 pd.NA
而不是 np.nan
(GH 30958)。
pandas 0.25.x
In [1]: pd.Series(a).sum(skipna=False)
Out[1]:
nan
pandas 1.0.0
In [43]: pd.Series(a).sum(skipna=False)
Out[43]: <NA>
value_counts 返回可空整数数据类型
Series.value_counts()
当输入是可空整数数据类型时,现在为结果值返回可空整数数据类型。
pandas 0.25.x
In [1]: pd.Series([2, 1, 1, None], dtype="Int64").value_counts().dtype
Out[1]:
dtype('int64')
pandas 1.0.0
In [44]: pd.Series([2, 1, 1, None], dtype="Int64").value_counts().dtype
Out[44]: Int64Dtype()
有关 pandas.NA
与 numpy.nan
的区别的更多信息,请参阅 NA semantics 。
arrays.IntegerArray
比较运算返回 arrays.BooleanArray
#
对 arrays.IntegerArray
执行比较运算时,现在返回 arrays.BooleanArray
,而不是NumPy数组 (GH 29964)。
pandas 0.25.x
In [1]: a = pd.array([1, 2, None], dtype="Int64")
In [2]: a
Out[2]:
<IntegerArray>
[1, 2, NaN]
Length: 3, dtype: Int64
In [3]: a > 1
Out[3]:
array([False, True, False])
pandas 1.0.0
In [45]: a = pd.array([1, 2, None], dtype="Int64")
In [46]: a > 1
Out[46]:
<BooleanArray>
[False, True, <NA>]
Length: 3, dtype: boolean
注意,缺失值现在会传播(propagate),而不是像 numpy.nan
那样总是比较不相等。详情请参阅 NA semantics 。
默认情况下 Categorical.min()
现在返回最小值而不是 np.nan#
当 Categorical
包含 np.nan
时, Categorical.min()
默认情况下(skipna=True)不再返回 np.nan
(GH 25303)
pandas 0.25.x
In [1]: pd.Categorical([1, 2, np.nan], ordered=True).min()
Out[1]: nan
pandas 1.0.0
In [47]: pd.Categorical([1, 2, np.nan], ordered=True).min()
Out[47]: 1
空 pandas.Series
的默认数据类型 (dtype)#
初始化一个空的 pandas.Series
而不指定 dtype 现在将引发一个 DeprecationWarning
(GH 17261)。默认的 dtype 在未来的版本中将从 float64
变为 object
,以便与 DataFrame
以及 Index
的行为保持一致。
pandas 1.0.0
In [1]: pd.Series()
Out[2]:
DeprecationWarning: The default dtype for empty Series will be 'object' instead of 'float64' in a future version. Specify a dtype explicitly to silence this warning.
Series([], dtype: float64)
resample 运算的结果 dtype 推断变化#
在 DataFrame.resample()
聚合运算中,扩展类型的结果 dtype 规则已更改 (GH 31359)。以前,pandas 会尝试将结果转换回原始 dtype,如果不可能则回退到通常的推断规则。现在,只有当结果中的标量值是扩展类型的标量类型的实例时,pandas 才会返回原始 dtype 的结果。
In [48]: df = pd.DataFrame({"A": ['a', 'b']}, dtype='category',
....: index=pd.date_range('2000', periods=2))
....:
In [49]: df
Out[49]:
A
2000-01-01 a
2000-01-02 b
[2 rows x 1 columns]
pandas 0.25.x
In [1]> df.resample("2D").agg(lambda x: 'a').A.dtype
Out[1]:
CategoricalDtype(categories=['a', 'b'], ordered=False)
pandas 1.0.0
In [50]: df.resample("2D").agg(lambda x: 'a').A.dtype
Out[50]: CategoricalDtype(categories=['a', 'b'], ordered=False, categories_dtype=object)
这修复了 resample
与 groupby
之间的不一致性。这也修复了一个潜在的错误,即结果的值可能会因结果如何被强制转换回原始 dtype 而改变。
pandas 0.25.x
In [1] df.resample("2D").agg(lambda x: 'c')
Out[1]:
A
0 NaN
pandas 1.0.0
In [51]: df.resample("2D").agg(lambda x: 'c')
Out[51]:
A
2000-01-01 c
[1 rows x 1 columns]
Python 的最低版本要求提高#
pandas 1.0.0 支持 Python 3.6.1 及更高版本 (GH 29212)。
依赖项的最低版本要求提高#
一些依赖项的最低支持版本已更新 (GH 29766, GH 29723)。如果已安装,我们现在要求
包 |
最低版本 |
必需 |
已更改 |
---|---|---|---|
numpy |
1.13.3 |
X |
|
pytz |
2015.4 |
X |
|
python-dateutil |
2.6.1 |
X |
|
bottleneck |
1.2.1 |
||
numexpr |
2.6.2 |
||
pytest (dev) |
4.0.2 |
对于 optional libraries ,一般建议使用最新版本。下表列出了在 pandas 开发过程中当前正在测试的每个库的最低版本。低于最低测试版本的可选库可能仍然有效,但不被视为支持。
包 |
最低版本 |
已更改 |
---|---|---|
beautifulsoup4 |
4.6.0 |
|
fastparquet |
0.3.2 |
X |
gcsfs |
0.2.2 |
|
lxml |
3.8.0 |
|
matplotlib |
2.2.2 |
|
numba |
0.46.0 |
X |
openpyxl |
2.5.7 |
X |
pyarrow |
0.13.0 |
X |
pymysql |
0.7.1 |
|
pytables |
3.4.2 |
|
s3fs |
0.3.0 |
X |
scipy |
0.19.0 |
|
sqlalchemy |
1.1.4 |
|
xarray |
0.8.2 |
|
xlrd |
1.1.0 |
|
xlsxwriter |
0.9.8 |
|
xlwt |
1.2.0 |
详情请参阅 Dependencies 以及 Optional dependencies 。
构建变更#
pandas 已添加了一个 pyproject.toml 文件,并且将不再在上传到 PyPI 的源码发布版中包含 cythonized 文件 (GH 28341, GH 20775)。如果你正在安装一个构建好的发布版 (wheel) 或通过 conda 安装,这应该对你没有任何影响。如果你从源码构建 pandas,你不再需要在调用 pip install pandas
前将 Cython 安装到你的构建环境中。
其他 API 变更#
DataFrameGroupBy.transform()
以及SeriesGroupBy.transform()
现在在遇到无效的操作名称时会引发错误 (GH 27489)pandas.api.types.infer_dtype()
现在将针对整数和np.nan
的混合情况返回 “integer-na” (GH 27283)MultiIndex.from_arrays()
如果在明确提供names=None
时,将不再从数组推断名称 (GH 27292)为了改善 tab 键补全体验,在使用
dir
对 pandas 对象进行自省(introspecting)时,pandas 不会包含大多数已弃用的属性(例如dir(df)
)。要查看哪些属性被排除,请查看对象的_deprecations
属性,例如pd.DataFrame._deprecations
(GH 28805)。options.matplotlib.register_converters
的默认配置值已从True
更改为"auto"
(GH 18720)。现在,pandas 的自定义格式化程序仅应用于通过plot()
创建的图。以前,在调用plot()
之后创建的所有图都会应用 pandas 的格式化程序。详情请参阅 units registration 。Series.dropna()
已移除了其**kwargs
参数,取而代之的是一个单独的how
参数。之前,除了how
以外的任何内容传递给**kwargs
都会引发一个TypeError
(GH 29388)测试 pandas 时,pytest 的新的最低要求版本是 5.0.1 (GH 29664)
Series.str.__iter__()
已弃用,并将在未来版本中移除 (GH 28277)。已将
<NA>
添加到read_csv()
的默认 NA 值列表中 (GH 30821)
文档改进#
新增了关于 Scaling to large datasets 的章节 (GH 28315)。
新增了关于 Query MultiIndex 用于 HDF5 数据集的子章节 (GH 28791)。
弃用项#
Series.item()
以及Index.item()
已恢复弃用(undeprecated) (GH 29250)Index.set_value
已弃用。对于给定的索引idx
,数组arr
,idx
中的值idx_val
以及新值val
,idx.set_value(arr, idx_val, val)
相当于arr[idx.get_loc(idx_val)] = val
,应改用此方法 (GH 28621)。is_extension_type()
已弃用,应改用is_extension_array_dtype()
(GH 29457)DateOffset.isAnchored()
以及DatetOffset.onOffset()
已弃用,并将在未来版本中移除;请改用DateOffset.is_anchored()
以及DateOffset.is_on_offset()
(GH 30340)pandas.tseries.frequencies.get_offset
已弃用,并将在未来版本中移除;请改用pandas.tseries.frequencies.to_offset
(GH 4205)Categorical.take_nd()
以及CategoricalIndex.take_nd()
已弃用,请改用Categorical.take()
以及CategoricalIndex.take()
(GH 27745)Categorical.min()
以及Categorical.max()
的参数numeric_only
已弃用,并被skipna
取代 (GH 25303)参数
label
在lreshape()
中已弃用,并将在未来版本中移除 (GH 29742)pandas.core.index
已弃用,并将在未来版本中移除;公共类已在顶层命名空间中可用 (GH 19711)pandas.json_normalize()
现在已在顶层命名空间中公开。将json_normalize
用作pandas.io.json.json_normalize
现在已弃用,建议改用pandas.json_normalize()
(GH 27586)。pandas.read_json()
的参数numpy
已弃用 (GH 28512)。DataFrame.to_stata()
,DataFrame.to_feather()
, 以及DataFrame.to_parquet()
的参数 “fname” 已弃用,请改用 “path” (GH 23574)RangeIndex
的已弃用内部属性_start
,_stop
以及_step
现在会引发FutureWarning
,而不是DeprecationWarning
(GH 26581)pandas.util.testing
模块已弃用。请改用pandas.testing
中记录的公共 API (Assertion functions) (GH 16232)。pandas.SparseArray
已弃用。请改用pandas.arrays.SparseArray
(arrays.SparseArray
)。 (GH 30642)Series.take()
以及DataFrame.take()
的参数is_copy
已弃用,并将在未来版本中移除。 (GH 27357)对
Index
进行多维索引(例如index[:, None]
)的支持已弃用,并将在未来版本中移除;请改在索引前将其转换为 numpy 数组 (GH 30588)pandas.np
子模块现在已弃用。请改直接导入 numpy (GH 30296)pandas.datetime
类现在已弃用。请改从datetime
导入 (GH 30610)diff
未来将引发TypeError
,而不是隐式地丢失扩展类型的 dtype。请改在调用diff
前将其转换为正确的 dtype (GH 31025)
从分组 DataFrame 中选择列
从 DataFrameGroupBy
对象中选择列时,使用单方括号传递单个键(或键的元组)已弃用,应改用列表。 (GH 23566) 例如
df = pd.DataFrame({
"A": ["foo", "bar", "foo", "bar", "foo", "bar", "foo", "foo"],
"B": np.random.randn(8),
"C": np.random.randn(8),
})
g = df.groupby('A')
# single key, returns SeriesGroupBy
g['B']
# tuple of single key, returns SeriesGroupBy
g[('B',)]
# tuple of multiple keys, returns DataFrameGroupBy, raises FutureWarning
g[('B', 'C')]
# multiple keys passed directly, returns DataFrameGroupBy, raises FutureWarning
# (implicitly converts the passed strings into a single tuple)
g['B', 'C']
# proper way, returns DataFrameGroupBy
g[['B', 'C']]
移除先前版本的弃用项/变更#
已移除 SparseSeries 以及 SparseDataFrame
SparseSeries
, SparseDataFrame
以及 DataFrame.to_sparse
方法已移除 (GH 28425)。我们建议改用具有稀疏值的 Series
或 DataFrame
。
Matplotlib 单元注册
以前,pandas 在导入时会作为副作用向 matplotlib 注册转换器 (GH 18720)。这改变了在导入 pandas 后通过 matplotlib plots 生成的图的输出,即使你直接使用 matplotlib 而不是 plot()
。
要在 matplotlib 图中使用 pandas 格式化程序,请指定
In [1]: import pandas as pd
In [2]: pd.options.plotting.matplotlib.register_converters = True
请注意,由 DataFrame.plot()
以及 Series.plot()
创建的图会自动注册转换器。唯一的变化是当通过 matplotlib.pyplot.plot
或 matplotlib.Axes.plot
绘制日期类对象时的行为。详情请参阅 Custom formatters for timeseries plots 。
其他移除项
已从
read_stata()
,StataReader
, 以及StataReader.read()
移除先前已弃用的关键字参数 “index”,请改用 “index_col” (GH 17328)已移除
StataReader.data
方法,请改用StataReader.read()
(GH 9493)已移除
pandas.plotting._matplotlib.tsplot
,请改用Series.plot()
(GH 19980)pandas.tseries.converter.register
已移至pandas.plotting.register_matplotlib_converters()
(GH 18307)Series.plot()
不再接受位置参数,请改传关键字参数 (GH 30003)DataFrame.hist()
以及Series.hist()
不再允许使用figsize="default"
,请改用元组指定图的大小 (GH 30003)整数类型数组与
Timedelta
的整除运算 (Floordiv) 现在会引发TypeError
(GH 21036)TimedeltaIndex
以及DatetimeIndex
不再接受非纳秒 (non-nanosecond) dtype 字符串,如 “timedelta64” 或 “datetime64”;请改用 “timedelta64[ns]” 以及 “datetime64[ns]” (GH 24806)已将
pandas.api.types.infer_dtype()
的默认 “skipna” 参数从False
更改为True
(GH 24050)已移除
Series.ix
以及DataFrame.ix
(GH 26438)已移除
Index.summary
(GH 18217)已移除
Series.get_value
,Series.set_value
,DataFrame.get_value
, 以及DataFrame.set_value
(GH 17739)已移除
Series.compound
以及DataFrame.compound
(GH 26405)已将
DataFrame.set_index()
以及Series.set_axis()
的默认 “inplace” 参数从None
更改为False
(GH 27600)已移除
Series.cat.categorical
,Series.cat.index
, 以及Series.cat.name
(GH 24751)已从
to_datetime()
以及to_timedelta()
移除先前已弃用的关键字参数 “box”;此外,它们现在总是返回DatetimeIndex
,TimedeltaIndex
,Index
,Series
, 或DataFrame
(GH 24486)to_timedelta()
,Timedelta
, 以及TimedeltaIndex
的 “unit” 参数不再允许使用 “M”, “y”, 或 “Y” (GH 23264)已从(非公共)
offsets.generate_range
移除先前已弃用的关键字参数 “time_rule”,它已移至core.arrays._ranges.generate_range()
(GH 24157)DataFrame.loc()
或Series.loc()
使用列表状索引器 (listlike indexers) 和缺失标签时,将不再重新索引 (reindex) (GH 17295)DataFrame.to_excel()
以及Series.to_excel()
在使用不存在的列时,将不再重新索引 (reindex) (GH 17295)已从
concat()
移除先前已弃用的关键字参数 “join_axes”;请改对结果使用reindex_like
(GH 22318)移除了 previously deprecated (已弃用) 关键字 “by” 从
DataFrame.sort_index()
,请改用DataFrame.sort_values()
(GH 10726)移除了对
DataFrame.aggregate()
、Series.aggregate()
、core.groupby.DataFrameGroupBy.aggregate()
、core.groupby.SeriesGroupBy.aggregate()
、core.window.rolling.Rolling.aggregate()
中嵌套重命名的支持 (GH 18529)将
datetime64
数据传递给TimedeltaIndex
或将timedelta64
数据传递给DatetimeIndex
现在会引发TypeError
(GH 23539, GH 23937)将
int64
值及一个时区传递给DatetimeIndex
现在会将这些值解释为 UTC 中的纳秒级时间戳,而不是给定 timezone 中的实际时间 (GH 24559)传递给
DataFrame.groupby()
的元组现在被唯一视为单个键 (GH 18314)移除了
Index.contains
,请改用key in index
(GH 30103)在
Timestamp
、DatetimeIndex
、TimedeltaIndex
中不再允许加减int
或整型数组,请改用obj + n * obj.freq
而不是obj + n
(GH 22535)移除了
Series.ptp
(GH 21614)移除了
Series.from_array
(GH 18258)移除了
DataFrame.from_items
(GH 18458)移除了
DataFrame.as_matrix
、Series.as_matrix
(GH 18458)移除了
Series.asobject
(GH 18477)移除了
DataFrame.as_blocks
、Series.as_blocks
、DataFrame.blocks
、Series.blocks
(GH 17656)pandas.Series.str.cat()
现在默认对others
进行对齐,使用join='left'
(GH 27611)pandas.Series.str.cat()
不再接受 list-likes 嵌套 list-likes 的形式 (GH 27611)Series.where()
(带有Categorical
dtype)或DataFrame.where()
(带有Categorical
列)不再允许设置新的分类 (GH 24114)移除了
DatetimeIndex
、TimedeltaIndex
和PeriodIndex
构造函数中 previously deprecated (已弃用) 的关键字 “start”、“end” 和 “periods”,请改用date_range()
、timedelta_range()
和period_range()
(GH 23919)移除了
DatetimeIndex
和TimedeltaIndex
构造函数中 previously deprecated (已弃用) 的关键字 “verify_integrity” (GH 23919)移除了
pandas.core.internals.blocks.make_block
中 previously deprecated (已弃用) 的关键字 “fastpath” (GH 19265)移除了
Block.make_block_same_class()
中 previously deprecated (已弃用) 的关键字 “dtype” (GH 19434)移除了
ExtensionArray._formatting_values
。请改用ExtensionArray._formatter
(GH 23601)移除了
MultiIndex.to_hierarchical
(GH 21613)移除了
MultiIndex.labels
,请改用MultiIndex.codes
(GH 23752)移除了
MultiIndex
构造函数中 previously deprecated (已弃用) 的关键字 “labels”,请改用 “codes” (GH 23752)移除了
MultiIndex.set_labels
,请改用MultiIndex.set_codes()
(GH 23752)移除了
MultiIndex.set_codes()
、MultiIndex.copy()
、MultiIndex.drop()
中 previously deprecated (已弃用) 的关键字 “labels”,请改用 “codes” (GH 23752)移除了对 legacy HDF5 格式的支持 (GH 29787)
将 dtype 别名(例如 ‘datetime64[ns, UTC]’)传递给
DatetimeTZDtype
不再允许,请改用DatetimeTZDtype.construct_from_string()
(GH 23990)移除了
read_excel()
中 previously deprecated (已弃用) 的关键字 “skip_footer”,请改用 “skipfooter” (GH 18836)read_excel()
不再允许为参数usecols
传递整型值,请改为传递一个包含从 0 到usecols
的整数列表 (GH 23635)移除了
DataFrame.to_records()
中 previously deprecated (已弃用) 的关键字 “convert_datetime64” (GH 18902)移除了
IntervalIndex.from_intervals
,请转而使用IntervalIndex
构造函数 (GH 19263)更改了
DatetimeIndex.to_series()
中默认参数 “keep_tz” 的值,从None
改为True
(GH 23739)移除了
api.types.is_period
和api.types.is_datetimetz
(GH 23917)读取包含用 pandas 0.16 版本之前创建的
Categorical
实例的 pickle 文件的能力已被移除 (GH 27538)移除了
pandas.tseries.plotting.tsplot
(GH 18627)移除了
DataFrame.apply()
中 previously deprecated (已弃用) 的关键字 “reduce” 和 “broadcast” (GH 18577)移除了
pandas._testing
中 previously deprecated (已弃用) 的函数assert_raises_regex
(GH 29174)移除了
pandas.core.indexes.frozen
中 previously deprecated (已弃用) 的类FrozenNDArray
(GH 29335)移除了
read_feather()
中 previously deprecated (已弃用) 的关键字 “nthreads”,请改用 “use_threads” (GH 23053)移除了
Index.is_lexsorted_for_tuple
(GH 29305)移除了对
DataFrame.aggregate()
、Series.aggregate()
、core.groupby.DataFrameGroupBy.aggregate()
、core.groupby.SeriesGroupBy.aggregate()
、core.window.rolling.Rolling.aggregate()
中嵌套重命名的支持 (GH 29608)移除了
Series.valid
;请改用Series.dropna()
(GH 18800)移除了
DataFrame.is_copy
、Series.is_copy
(GH 18812)移除了
DataFrame.get_ftype_counts
、Series.get_ftype_counts
(GH 18243)移除了
DataFrame.ftypes
、Series.ftypes
、Series.ftype
(GH 26744)移除了
Index.get_duplicates
,请改用idx[idx.duplicated()].unique()
(GH 20239)移除了
Series.clip_upper
、Series.clip_lower
、DataFrame.clip_upper
、DataFrame.clip_lower
(GH 24203)移除了更改
DatetimeIndex.freq
、TimedeltaIndex.freq
或PeriodIndex.freq
的能力 (GH 20772)移除了
DatetimeIndex.offset
(GH 20730)移除了
DatetimeIndex.asobject
、TimedeltaIndex.asobject
、PeriodIndex.asobject
,请改用astype(object)
(GH 29801)移除了
factorize()
中 previously deprecated (已弃用) 的关键字 “order” (GH 19751)移除了
read_stata()
和DataFrame.to_stata()
中 previously deprecated (已弃用) 的关键字 “encoding” (GH 21400)移除了
DataFrame.update()
中 previously deprecated (已弃用) 的关键字 “raise_conflict”,请改用 “errors” (GH 23585)移除了
DatetimeIndex.shift()
、TimedeltaIndex.shift()
、PeriodIndex.shift()
中 previously deprecated (已弃用) 的关键字 “n”,请改用 “periods” (GH 22458)移除了
DataFrame.resample()
中 previously deprecated (已弃用) 的关键字 “how”、“fill_method” 和 “limit” (GH 30139)使用
timedelta64[ns]
dtype 时,将整数传递给Series.fillna()
或DataFrame.fillna()
现在会引发TypeError
(GH 24694)DataFrame.dropna()
不再支持传递多个轴 (GH 20995)移除了
Series.nonzero
,请改用to_numpy().nonzero()
(GH 24048)Categorical.from_codes()
不再支持传递浮点 dtype 的codes
,请改为传递codes.astype(np.int64)
(GH 21775)移除了
Series.str.partition()
和Series.str.rpartition()
中 previously deprecated (已弃用) 的关键字 “pat”,请改用 “sep” (GH 23767)移除了
Series.put
(GH 27106)移除了
Series.real
、Series.imag
(GH 27106)移除了
Series.to_dense
、DataFrame.to_dense
(GH 26684)移除了
Index.dtype_str
,请改用str(index.dtype)
(GH 27106)Categorical.ravel()
返回Categorical
而不是ndarray
(GH 27199)Numpy ufuncs 上的 ‘outer’ 方法(例如作用于
Series
对象的np.subtract.outer
)不再受支持,并将引发NotImplementedError
(GH 27198)移除了
Series.get_dtype_counts
和DataFrame.get_dtype_counts
(GH 27145)更改了
Categorical.take()
中默认参数 “fill_value” 的值,从True
改为False
(GH 20841)更改了
Series.rolling().apply()
、DataFrame.rolling().apply()
、Series.expanding().apply()
和DataFrame.expanding().apply()
中raw
参数的默认值,从None
改为False
(GH 20584)移除了
Series.argmin()
和Series.argmax()
的 deprecated (已弃用) 行为,请改用Series.idxmin()
和Series.idxmax()
来获得旧行为 (GH 16955)在带有
tz
参数的Timestamp
构造函数中传递 tz-aware 的datetime.datetime
或Timestamp
现在会引发ValueError
(GH 23621)移除了
Series.base
、Index.base
、Categorical.base
、Series.flags
、Index.flags
、PeriodArray.flags
、Series.strides
、Index.strides
、Series.itemsize
、Index.itemsize
、Series.data
、Index.data
(GH 20721)更改了
Timedelta.resolution()
以匹配标准库datetime.timedelta.resolution
的行为,对于旧行为,请改用Timedelta.resolution_string()
(GH 26839)移除了
Timestamp.weekday_name
、DatetimeIndex.weekday_name
和Series.dt.weekday_name
(GH 18164)移除了
Timestamp.tz_localize()
、DatetimeIndex.tz_localize()
和Series.tz_localize()
中 previously deprecated (已弃用) 的关键字 “errors” (GH 22644)更改了
CategoricalDtype
中默认参数 “ordered” 的值,从None
改为False
(GH 26336)Series.set_axis()
和DataFrame.set_axis()
现在要求将“labels”作为第一个参数,并将“axis”作为可选的命名参数 (GH 30089)移除了
to_msgpack
、read_msgpack
、DataFrame.to_msgpack
、Series.to_msgpack
(GH 27103)移除了
Series.compress
(GH 21930)移除了之前已弃用的
Categorical.fillna()
的关键字参数 “fill_value”,请改用 “value” (GH 19269)移除了之前已弃用的
andrews_curves()
的关键字参数 “data”,请改用 “frame” (GH 6956)移除了之前已弃用的
parallel_coordinates()
的关键字参数 “data”,请改用 “frame” (GH 6956)移除了之前已弃用的
parallel_coordinates()
的关键字参数 “colors”,请改用 “color” (GH 6956)移除了
read_gbq()
中之前已弃用的关键字参数 “verbose” 和 “private_key” (GH 30200)在时区感知
Series
和DatetimeIndex
上调用np.array
和np.asarray
现在将返回一个包含时区感知Timestamp
的对象数组 (GH 24596)
性能改进#
在使用非唯一
IntervalIndex
进行索引时性能得到改进 (GH 27489)在
MultiIndex.is_monotonic
中性能得到改进 (GH 27495)当
bins
是IntervalIndex
时,cut()
的性能得到改进 (GH 27668)当
method
为"spearman"
时,DataFrame.corr()
的性能得到改进 (GH 28139)在提供要替换的值列表时,
DataFrame.replace()
的性能得到改进 (GH 28099)通过使用向量化而不是循环迭代,
DataFrame.select_dtypes()
的性能得到改进 (GH 28317)在
Categorical.searchsorted()
和CategoricalIndex.searchsorted()
中性能得到改进 (GH 28795)当比较
Categorical
与标量且该标量不在类别中时,性能得到改进 (GH 29750)在检查
Categorical
中的值是否等于、大于等于或大于给定标量时,性能得到改进。在检查Categorical
是否小于或小于等于该标量时没有此改进 (GH 29820)在
Index.equals()
和MultiIndex.equals()
中性能得到改进 (GH 29134)当
skipna
为True
时,infer_dtype()
的性能得到改进 (GH 28814)
错误修复#
分类数据 (Categorical)#
添加了测试以断言当值不是类别中的值时,
fillna()
会引发正确的ValueError
消息 (GH 13628)在
Categorical.astype()
中,当转换为 int 类型时,NaN
值处理不正确,存在错误 (GH 28406)DataFrame.reindex()
在使用CategoricalIndex
时,如果目标包含重复项则会失败,如果源包含重复项则不会失败,存在错误 (GH 28107)在
Categorical.astype()
中不允许转换为扩展数据类型 (extension dtypes),存在错误 (GH 28668)Categorical.searchsorted()
和CategoricalIndex.searchsorted()
现在也适用于无序分类数据 (GH 21667)添加了测试以断言使用
DataFrame.to_parquet()
或read_parquet()
往返 parquet 文件时,将保留字符串类型的 Categorical 数据类型 (GH 27955)更改了
Categorical.remove_categories()
中的错误消息,使其始终将无效移除项显示为一个集合 (GH 28669)在分类数据类型的
Series
(包含 datetime 值)上使用日期访问器时,返回的对象类型与在具有该类型的Series
上使用str.()
/dt.()
时不同,存在错误。例如,在包含重复项的Categorical
上访问Series.dt.tz_localize()
时,访问器会跳过重复项 (GH 27952)在
DataFrame.replace()
和Series.replace()
中,对于分类数据会给出不正确的结果,存在错误 (GH 26988)在空 Categorical 上调用
Categorical.min()
或Categorical.max()
会引发 numpy 异常,存在错误 (GH 30227)通过
groupby(..., observed=False)
调用以下方法时,现在也能正确输出未观测类别的对应值 (GH 17605):*core.groupby.SeriesGroupBy.count()
*core.groupby.SeriesGroupBy.size()
*core.groupby.SeriesGroupBy.nunique()
*core.groupby.SeriesGroupBy.nth()
日期/时间类型 (Datetimelike)#
在
Series.__setitem__()
中,将np.timedelta64("NaT")
错误地转换为np.datetime64("NaT")
,当将其插入 datetime64 数据类型的Series
时,存在错误 (GH 27311)在
Series.dt()
属性查找中,当底层数据为只读时存在错误 (GH 27529)在
HDFStore.__getitem__
中读取 Python 2 中创建的 tz 属性不正确,存在错误 (GH 26443)在
to_datetime()
中,当传入格式错误的str
数组且 errors=”coerce” 时,可能错误地引发ValueError
,存在错误 (GH 28299)在
core.groupby.SeriesGroupBy.nunique()
中,NaT
值会干扰唯一值的计数,存在错误 (GH 27951)在
Timestamp
减法中,当从np.datetime64
对象中减去一个Timestamp
时,错误地引发TypeError
,存在错误 (GH 28286)Timestamp
与整数或整数数据类型数组相加或相减现在将引发NullFrequencyError
而不是ValueError
(GH 28268)在
Series
和DataFrame
中,整数 dtype 在添加或减去np.datetime64
对象时未能引发TypeError
的错误 (GH 28080)在
Series.astype()
、Index.astype()
和DataFrame.astype()
中,当转换为整数数据类型时未能处理NaT
,存在错误 (GH 28492)在具有
weekday
的Week
中,当添加或减去无效类型时,错误地引发AttributeError
而不是TypeError
,存在错误 (GH 28530)在
DataFrame
算术运算中,当与数据类型为'timedelta64[ns]'
的Series
进行操作时存在错误 (GH 28049)在
core.groupby.generic.SeriesGroupBy.apply()
中,当原始 DataFrame 中的列是 datetime 且列标签不是标准整数时,引发ValueError
,存在错误 (GH 28247)在
pandas._config.localization.get_locales()
中,locales -a
将区域设置列表编码为 windows-1252,存在错误 (GH 23638, GH 24760, GH 27368)在
Series.var()
中,当使用timedelta64[ns]
数据类型调用时未能引发TypeError
,存在错误 (GH 28289)在
DatetimeIndex.strftime()
和Series.dt.strftime()
中,NaT
被转换为字符串'NaT'
而不是np.nan
,存在错误 (GH 29578)使用长度不正确的布尔掩码来掩码 datetime-like 数组时未能引发
IndexError
的错误 (GH 30308)在
Timestamp.resolution
中,其是一个属性而不是类属性,存在错误 (GH 29910)在
pandas.to_datetime()
中,当使用None
调用时引发TypeError
而不是返回NaT
,存在错误 (GH 30011)在
pandas.to_datetime()
中,当使用cache=True
(默认值) 时,对deque
对象会失败,存在错误 (GH 29403)在数据类型为
datetime64
或timedelta64
的Series.item()
、DatetimeIndex.item()
和TimedeltaIndex.item()
中,返回的是整数而不是Timestamp
或Timedelta
,存在错误 (GH 30175)在
DatetimeIndex
加法中,当添加非优化的DateOffset
时,错误地丢弃时区信息,存在错误 (GH 30336)在
DataFrame.drop()
中,尝试从 DatetimeIndex 中删除不存在的值时会产生令人困惑的错误消息,存在错误 (GH 30399)在
DataFrame.append()
中,会移除新数据的时区感知性,存在错误 (GH 30238)在
Series.cummin()
和Series.cummax()
中,对于时区感知的数据类型,错误地丢弃其时区,存在错误 (GH 15553)在
DatetimeArray
、TimedeltaArray
和PeriodArray
中,原地加法和减法实际上并未在原地操作,存在错误 (GH 24115)在
pandas.to_datetime()
中,当使用存储IntegerArray
的Series
调用时引发TypeError
而不是返回Series
,存在错误 (GH 30050)在
date_range()
中,当使用自定义工作时间作为freq
并给定periods
数量时存在错误 (GH 30593)在
PeriodIndex
比较中,错误地将整数转换为Period
对象,与Period
的比较行为不一致,存在错误 (GH 30722)在
DatetimeIndex.insert()
中,尝试将时区感知Timestamp
插入到时区不感知DatetimeIndex
中,或反之,会引发ValueError
而不是TypeError
,存在错误 (GH 30806)
时间差 (Timedelta)#
在从
np.datetime64
对象中减去TimedeltaIndex
或TimedeltaArray
时存在错误 (GH 29558)
时区 (Timezones)#
数值 (Numeric)#
在
DataFrame.quantile()
中,对于零列的DataFrame
错误地引发异常,存在错误 (GH 23925)具有 object-dtype 和
complex
条目的DataFrame
灵活不等式比较方法 (DataFrame.lt()
、DataFrame.le()
、DataFrame.gt()
、DataFrame.ge()
) 未能像其Series
对应项那样引发TypeError
的错误 (GH 28079)DataFrame
逻辑运算 (&
,|
,^
) 在填充 NA 值时不匹配Series
行为的错误 (GH 28741)在
DataFrame.interpolate()
中,按名称指定轴时引用了未赋值的变量的错误 (GH 29142)在
Series.var()
中,对于未传递 ddof 参数的可空整数 dtype Series 计算值不正确的错误 (GH 29128)使用
frac
> 1 且replace
= False 时改进了错误消息 (GH 27451)数字索引中的错误导致可以使用无效的 dtype (例如 datetime-like) 实例化
Int64Index
、UInt64Index
或Float64Index
(GH 29539)从包含
np.uint64
范围内值的列表构造UInt64Index
时精度丢失的错误 (GH 29526)NumericIndex
构造中的错误导致在使用np.uint64
范围内的整数进行索引时失败 (GH 28023)NumericIndex
构造中的错误导致在使用np.uint64
范围内的整数索引DataFrame
时,UInt64Index
被转换为Float64Index
(GH 28279)在
Series.interpolate()
中,当使用 method=`index` 处理未排序的索引时,以前会返回不正确结果的错误 (GH 21037)在
DataFrame.round()
中,包含IntervalIndex
列的CategoricalIndex
的DataFrame
会错误地引发TypeError
的错误 (GH 30063)在
Series.pct_change()
和DataFrame.pct_change()
中存在重复索引时的错误 (GH 30463)DataFrame
累积操作 (例如 cumsum, cummax) 错误地转换为 object-dtype 的错误 (GH 19296)DataFrame.diff
在其中一列是可空整数 dtype 时引发IndexError
的错误 (GH 30967)
转换#
字符串#
在空
Series
上调用Series.str.isalnum()
(及其他“ismethods”) 会返回object
dtype 而非bool
的错误 (GH 29624)
区间#
在
IntervalIndex.get_indexer()
中,当target
是Categorical
或CategoricalIndex
时会错误地引发TypeError
的错误 (GH 30063)在
pandas.core.dtypes.cast.infer_dtype_from_scalar
中,传递pandas_dtype=True
时未能推断出IntervalDtype
的错误 (GH 30337)在
Series
构造函数中,从list
的Interval
对象构造Series
时导致 object dtype 而非IntervalDtype
的错误 (GH 23563)在
IntervalDtype
中,kind
属性错误地设置为None
而非"O"
的错误 (GH 30568)在包含区间数据的
IntervalIndex
、IntervalArray
和Series
中,相等性比较不正确的错误 (GH 24112)
索引#
使用反向切片器进行赋值时的错误 (GH 26939)
在
DataFrame.explode()
中,当索引存在重复时会复制 DataFrame 的错误 (GH 28010)使用包含
Period
的另一种类型的索引重新索引PeriodIndex()
时的错误 (GH 28323) (GH 28337)修复使用
.loc
对 numpy 非纳秒 (non-ns) datetime 类型列进行赋值的问题 (GH 27395)在
Float64Index.astype()
中,将np.inf
转换为整数 dtype 时未能正确处理的错误 (GH 28475)当左侧包含重复项时,
Index.union()
可能会失败 (GH 28257)使用
.loc
索引时,当索引是包含非字符串类别的CategoricalIndex
时不起作用的错误 (GH 17569, GH 30225)在某些情况下,例如在字符串索引中搜索整数时,
Index.get_indexer_non_unique()
可能会因TypeError
失败 (GH 28257)Float64Index.get_loc()
错误地引发TypeError
而非KeyError
的错误 (GH 29189)在 1 行
DataFrame
中设置 Categorical 值时,DataFrame.loc()
使用了不正确的 dtype 的错误 (GH 25495)当输入包含缺失值时,
MultiIndex.get_loc()
找不到缺失值 (GH 19132)在
Series.__setitem__()
中,当新数据的长度与True
值的数量匹配且新数据不是Series
或np.array
时,使用布尔索引器错误赋值的错误 (GH 30567)使用
PeriodIndex
索引时错误地接受表示年份的整数的错误,应使用例如ser.loc["2007"]
而非ser.loc[2007]
(GH 30763)
缺失值#
多级索引#
如果
verify_integrity
参数为True
(默认值),MultiIndex
的构造函数会验证给定的sortorder
与实际的lexsort_depth
是否兼容 (GH 28735)当标签不在给定级别中时,带有
MultiIndex
的 Series 和 MultiIndex.drop
会引发异常 (GH 8594)
IO#
使用 Python csv 引擎时,
read_csv()
现在接受二进制模式的文件缓冲区 (GH 23779)在
DataFrame.to_json()
中,当使用 Tuple 作为列或索引值并使用orient="columns"
或orient="index"
时会生成无效 JSON 的错误 (GH 20500)改进了无穷大解析。
read_csv()
现在将Infinity
、+Infinity
、-Infinity
解析为浮点值 (GH 10065)在
DataFrame.to_csv()
中,当na_rep
的长度短于文本输入数据时值被截断的错误 (GH 25099)在
DataFrame.to_string()
中,使用显示选项截断值而不是输出完整内容的错误 (GH 9784)在
DataFrame.to_json()
中,当使用orient="table"
时 datetime 列标签不会以 ISO 格式写入的错误 (GH 28130)在
DataFrame.to_parquet()
中,如果文件不存在,使用engine='fastparquet'
写入 GCS 会失败的错误 (GH 28326)在
read_hdf()
中,当异常发生时关闭它未打开的 store 的错误 (GH 28699)在
DataFrame.read_json()
中,使用orient="index"
时未能保持顺序的错误 (GH 28557)在
DataFrame.to_html()
中,未验证formatters
参数长度的错误 (GH 28469)在
DataFrame.read_excel()
中,当engine='ods'
且sheet_name
参数引用不存在的工作表时的错误 (GH 27676)在
pandas.io.formats.style.Styler()
中,浮点值格式化时未正确显示小数位的错误 (GH 13257)在
DataFrame.to_html()
中,同时使用formatters=<list>
和max_cols
时的错误 (GH 25955)Styler.background_gradient()
无法处理 dtypeInt64
的错误 (GH 28869)DataFrame.to_clipboard()
在 ipython 中工作不可靠的错误 (GH 22707)在
read_json()
中,默认编码未设置为utf-8
的错误 (GH 29565)在
PythonParser
中,处理 decimal 字段时混合使用了 str 和 bytes 的错误 (GH 29650)read_gbq()
现在接受progress_bar_type
参数,用于在数据下载时显示进度条 (GH 29857)在
pandas.io.json.json_normalize()
中,当record_path
指定的位置存在缺失值时会引发TypeError
的错误 (GH 30148)read_excel()
现在接受二进制数据 (GH 15914)在
read_csv()
中,C 引擎的编码处理仅限于字符串utf-16
的错误 (GH 24130)
绘图#
Series.plot()
无法绘制布尔值的错误 (GH 23719)在没有行时
DataFrame.plot()
无法绘制的错误 (GH 27758)在
DataFrame.plot()
中,当在同一轴上绘制多个 series 时生成不正确的图例标记的错误 (GH 18222)在
DataFrame.plot()
中,当kind='box'
且数据包含 datetime 或 timedelta 数据时的错误。这些类型现在会自动丢弃 (GH 22799)在
DataFrame.plot.line()
和DataFrame.plot.area()
中,x 轴的 xlim 生成错误的错误 (GH 27686, GH 25160, GH 24784)DataFrame.boxplot()
不接受DataFrame.plot.box()
那样的color
参数的错误 (GH 26214)DataFrame.plot.bar()
中xticks
参数被忽略的错误 (GH 14119)set_option()
现在在设置选项时而非创建绘图时验证提供给'plotting.backend'
的绘图后端是否实现了该后端 (GH 28163)DataFrame.plot()
现在允许使用backend
关键字参数,以便在一个会话中切换不同的后端 (GH 28619)。颜色验证错误地对非颜色样式引发异常的错误 (GH 29122)。
允许
DataFrame.plot.scatter()
绘制objects
和datetime
类型数据 (GH 18755, GH 30391)在
DataFrame.hist()
中,xrot=0
在使用by
和 subplots 时不起作用的错误 (GH 30288)。
GroupBy/重采样/rolling#
在
core.groupby.DataFrameGroupBy.apply()
中,当函数返回Index
时仅显示单个组输出的错误 (GH 28652)在包含多个分组的
DataFrame.groupby()
中,如果任何分组包含所有 NA 值,会引发IndexError
的错误 (GH 20519)在
Resampler.size()
和Resampler.count()
中,与空Series
或DataFrame
一起使用时返回错误的 dtype 的错误 (GH 28427)在
DataFrame.rolling()
中,当axis=1
时不允许对 datetimes 进行 rolling 操作的错误 (GH 28192)在
DataFrame.rolling()
中,不允许对多级索引级别进行 rolling 操作的错误 (GH 15584)。Bug in
DataFrame.rolling()
not allowing rolling on monotonic decreasing time indexes (GH 19248)。Bug in
DataFrame.groupby()
not offering selection by column name whenaxis=1
(GH 27614)Bug in
core.groupby.DataFrameGroupby.agg()
not able to use lambda function with named aggregation (GH 27519)Bug in
DataFrame.groupby()
losing column name information when grouping by a categorical column (GH 28787)Remove error raised due to duplicated input functions in named aggregation in
DataFrame.groupby()
andSeries.groupby()
. Previously error will be raised if the same function is applied on the same column and now it is allowed if new assigned names are different. (GH 28426)core.groupby.SeriesGroupBy.value_counts()
will be able to handle the case even when theGrouper
makes empty groups (GH 28479)Bug in
core.window.rolling.Rolling.quantile()
ignoringinterpolation
keyword argument when used within a groupby (GH 28779)Bug in
DataFrame.groupby()
whereany
,all
,nunique
and transform functions would incorrectly handle duplicate column labels (GH 21668)Bug in
core.groupby.DataFrameGroupBy.agg()
with timezone-aware datetime64 column incorrectly casting results to the original dtype (GH 29641)Bug in
DataFrame.groupby()
when using axis=1 and having a single level columns index (GH 30208)Bug in
DataFrame.groupby()
when using nunique on axis=1 (GH 30253)Bug in
DataFrameGroupBy.quantile()
andSeriesGroupBy.quantile()
with multiple list-like q value and integer column names (GH 30289)Bug in
DataFrameGroupBy.pct_change()
andSeriesGroupBy.pct_change()
causesTypeError
whenfill_method
isNone
(GH 30463)Bug in
Rolling.count()
andExpanding.count()
argument wheremin_periods
was ignored (GH 26996)
重塑#
Bug in
DataFrame.apply()
that caused incorrect output with emptyDataFrame
(GH 28202, GH 21959)Bug in
DataFrame.stack()
not handling non-unique indexes correctly when creating MultiIndex (GH 28301)Bug in
pivot_table()
not returning correct typefloat
whenmargins=True
andaggfunc='mean'
(GH 24893)Bug
merge_asof()
could not usedatetime.timedelta
fortolerance
kwarg (GH 28098)Bug in
merge()
, did not append suffixes correctly with MultiIndex (GH 28518)Fix to ensure all int dtypes can be used in
merge_asof()
when using a tolerance value. Previously every non-int64 type would raise an erroneousMergeError
(GH 28870)。Better error message in
get_dummies()
whencolumns
isn’t a list-like value (GH 28383)Bug in
Index.join()
that caused infinite recursion error for mismatchedMultiIndex
name orders. (GH 25760, GH 28956)Bug
Series.pct_change()
where supplying an anchored frequency would throw aValueError
(GH 28664)Bug where
DataFrame.equals()
returned True incorrectly in some cases when two DataFrames had the same columns in different orders (GH 28839)Bug in
DataFrame.replace()
that caused non-numeric replacer’s dtype not respected (GH 26632)Bug in
melt()
where supplying mixed strings and numeric values forid_vars
orvalue_vars
would incorrectly raise aValueError
(GH 29718)Dtypes are now preserved when transposing a
DataFrame
where each column is the same extension dtype (GH 30091)Bug in
merge_asof()
merging on a tz-awareleft_index
andright_on
a tz-aware column (GH 29864)Improved error message and docstring in
cut()
andqcut()
whenlabels=True
(GH 13318)Bug in missing
fill_na
parameter toDataFrame.unstack()
with list of levels (GH 30740)
稀疏#
Bug in
SparseDataFrame
arithmetic operations incorrectly casting inputs to float (GH 28107)Bug in
DataFrame.sparse
returning aSeries
when there was a column namedsparse
rather than the accessor (GH 30758)Fixed
operator.xor()
with a boolean-dtypeSparseArray
. Now returns a sparse result, rather than object dtype (GH 31025)
扩展数组#
其他#
Trying to set the
display.precision
,display.max_rows
ordisplay.max_columns
usingset_option()
to anything but aNone
or a positive int will raise aValueError
(GH 23348)Using
DataFrame.replace()
with overlapping keys in a nested dictionary will no longer raise, now matching the behavior of a flat dictionary (GH 27660)DataFrame.to_csv()
andSeries.to_csv()
now support dicts ascompression
argument with key'method'
being the compression method and others as additional compression options when the compression method is'zip'
. (GH 26023)Bug in
Series.diff()
where a boolean series would incorrectly raise aTypeError
(GH 17294)Series.append()
will no longer raise aTypeError
when passed a tuple ofSeries
(GH 28410)Fix corrupted error message when calling
pandas.libs._json.encode()
on a 0d array (GH 18878)Backtick quoting in
DataFrame.query()
andDataFrame.eval()
can now also be used to use invalid identifiers like names that start with a digit, are python keywords, or are using single character operators. (GH 27017)Bug in
pd.core.util.hashing.hash_pandas_object
where arrays containing tuples were incorrectly treated as non-hashable (GH 28969)Bug in
DataFrame.append()
that raisedIndexError
when appending with empty list (GH 28769)Fix
AbstractHolidayCalendar
to return correct results for years after 2030 (now goes up to 2200) (GH 27790)Fixed
IntegerArray
returninginf
rather thanNaN
for operations dividing by0
(GH 27398)Fixed
pow
operations forIntegerArray
when the other value is0
or1
(GH 29997)Bug in
Series.count()
raises if use_inf_as_na is enabled (GH 29478)Bug in
Index
where a non-hashable name could be set without raisingTypeError
(GH 29069)Bug in
DataFrame
constructor when passing a 2Dndarray
and an extension dtype (GH 12513)Bug in
DataFrame.to_csv()
when supplied a series with adtype="string"
and ana_rep
, thena_rep
was being truncated to 2 characters. (GH 29975)Bug where
DataFrame.itertuples()
would incorrectly determine whether or not namedtuples could be used for dataframes of 255 columns (GH 28282)Handle nested NumPy
object
arrays intesting.assert_series_equal()
for ExtensionArray implementations (GH 30841)Bug in
Index
constructor incorrectly allowing 2-dimensional input arrays (GH 13601, GH 27125)
贡献者#
共有 308 人为此版本贡献了补丁。姓名旁边带有“+”的人员是首次贡献补丁。
Aaditya Panikath +
Abdullah İhsan Seçer
Abhijeet Krishnan +
Adam J. Stewart
Adam Klaum +
Addison Lynch
Aivengoe +
Alastair James +
Albert Villanova del Moral
Alex Kirko +
Alfredo Granja +
Allen Downey
Alp Arıbal +
Andreas Buhr +
Andrew Munch +
Andy
Angela Ambroz +
Aniruddha Bhattacharjee +
Ankit Dhankhar +
Antonio Andraues Jr +
Arda Kosar +
Asish Mahapatra +
Austin Hackett +
Avi Kelman +
AyowoleT +
Bas Nijholt +
Ben Thayer
Bharat Raghunathan
Bhavani Ravi
Bhuvana KA +
Big Head
Blake Hawkins +
Bobae Kim +
Brett Naul
Brian Wignall
Bruno P. Kinoshita +
Bryant Moscon +
Cesar H +
Chris Stadler
Chris Zimmerman +
Christopher Whelan
Clemens Brunner
Clemens Tolboom +
Connor Charles +
Daniel Hähnke +
Daniel Saxton
Darin Plutchok +
Dave Hughes
David Stansby
DavidRosen +
Dean +
Deepan Das +
Deepyaman Datta
DorAmram +
Dorothy Kabarozi +
Drew Heenan +
Eliza Mae Saret +
Elle +
Endre Mark Borza +
Eric Brassell +
Eric Wong +
Eunseop Jeong +
Eyden Villanueva +
Felix Divo
ForTimeBeing +
Francesco Truzzi +
Gabriel Corona +
Gabriel Monteiro +
Galuh Sahid +
Georgi Baychev +
Gina
GiuPassarelli +
Grigorios Giannakopoulos +
Guilherme Leite +
Guilherme Salomé +
Gyeongjae Choi +
Harshavardhan Bachina +
Harutaka Kawamura +
Hassan Kibirige
Hielke Walinga
Hubert
Hugh Kelley +
Ian Eaves +
Ignacio Santolin +
Igor Filippov +
Irv Lustig
Isaac Virshup +
Ivan Bessarabov +
JMBurley +
Jack Bicknell +
Jacob Buckheit +
Jan Koch
Jan Pipek +
Jan Škoda +
Jan-Philip Gehrcke
Jasper J.F. van den Bosch +
Javad +
Jeff Reback
Jeremy Schendel
Jeroen Kant +
Jesse Pardue +
Jethro Cao +
Jiang Yue
Jiaxiang +
Jihyung Moon +
Jimmy Callin
Jinyang Zhou +
Joao Victor Martinelli +
Joaq Almirante +
John G Evans +
John Ward +
Jonathan Larkin +
Joris Van den Bossche
Josh Dimarsky +
Joshua Smith +
Josiah Baker +
Julia Signell +
Jung Dong Ho +
Justin Cole +
Justin Zheng
Kaiqi Dong
Karthigeyan +
Katherine Younglove +
Katrin Leinweber
Kee Chong Tan +
Keith Kraus +
Kevin Nguyen +
Kevin Sheppard
Kisekka David +
Koushik +
Kyle Boone +
Kyle McCahill +
Laura Collard, PhD +
LiuSeeker +
Louis Huynh +
Lucas Scarlato Astur +
Luiz Gustavo +
Luke +
Luke Shepard +
MKhalusova +
Mabel Villalba
Maciej J +
Mak Sze Chun
Manu NALEPA +
Marc
Marc Garcia
Marco Gorelli +
Marco Neumann +
Martin Winkel +
Martina G. Vilas +
Mateusz +
Matthew Roeschke
Matthew Tan +
Max Bolingbroke
Max Chen +
MeeseeksMachine
Miguel +
MinGyo Jung +
Mohamed Amine ZGHAL +
Mohit Anand +
MomIsBestFriend +
Naomi Bonnin +
Nathan Abel +
Nico Cernek +
Nigel Markey +
Noritada Kobayashi +
Oktay Sabak +
Oliver Hofkens +
Oluokun Adedayo +
Osman +
Oğuzhan Öğreden +
Pandas Development Team +
Patrik Hlobil +
Paul Lee +
Paul Siegel +
Petr Baev +
Pietro Battiston
Prakhar Pandey +
Puneeth K +
Raghav +
Rajat +
Rajhans Jadhao +
Rajiv Bharadwaj +
Rik-de-Kort +
Roei.r
Rohit Sanjay +
Ronan Lamy +
Roshni +
Roymprog +
Rushabh Vasani +
Ryan Grout +
Ryan Nazareth
Samesh Lakhotia +
Samuel Sinayoko
Samyak Jain +
Sarah Donehower +
Sarah Masud +
Saul Shanabrook +
Scott Cole +
SdgJlbl +
Seb +
Sergei Ivko +
Shadi Akiki
Shorokhov Sergey
Siddhesh Poyarekar +
Sidharthan Nair +
Simon Gibbons
Simon Hawkins
Simon-Martin Schröder +
Sofiane Mahiou +
Sourav kumar +
Souvik Mandal +
Soyoun Kim +
Sparkle Russell-Puleri +
Srinivas Reddy Thatiparthy (శ్రీనివాస్ రెడ్డి తాటిపర్తి)
Stuart Berg +
Sumanau Sareen
Szymon Bednarek +
Tambe Tabitha Achere +
Tan Tran
Tang Heyi +
Tanmay Daripa +
Tanya Jain
Terji Petersen
Thomas Li +
Tirth Jain +
Tola A +
Tom Augspurger
Tommy Lynch +
Tomoyuki Suzuki +
Tony Lorenzo
Unprocessable +
Uwe L. Korn
Vaibhav Vishal
Victoria Zdanovskaya +
Vijayant +
Vishwak Srinivasan +
WANG Aiyong
Wenhuan
Wes McKinney
Will Ayd
Will Holmgren
William Ayd
William Blan +
Wouter Overmeire
Wuraola Oyewusi +
YaOzI +
Yash Shukla +
Yu Wang +
Yusei Tahara +
alexander135 +
alimcmaster1
avelineg +
bganglia +
bolkedebruin
bravech +
chinhwee +
cruzzoe +
dalgarno +
daniellebrown +
danielplawrence
est271 +
francisco souza +
ganevgv +
garanews +
gfyoung
h-vetinari
hasnain2808 +
ianzur +
jalbritt +
jbrockmendel
jeschwar +
jlamborn324 +
joy-rosie +
kernc
killerontherun1
krey +
lexy-lixinyu +
lucyleeow +
lukasbk +
maheshbapatu +
mck619 +
nathalier
naveenkaushik2504 +
nlepleux +
nrebena
ohad83 +
pilkibun
pqzx +
proost +
pv8493013j +
qudade +
rhstanton +
rmunjal29 +
sangarshanan +
sardonick +
saskakarsi +
shaido987 +
ssikdar1
steveayers124 +
tadashigaki +
timcera +
tlaytongoogle +
tobycheese
tonywu1999 +
tsvikas +
yogendrasoni +
zys5945 +