2.0.0 版本新特性 (2023 年 4 月 3 日)#

这是 pandas 2.0.0 版本中的变更。请参阅发布说明,以查看包括其他 pandas 版本在内的完整变更日志。

增强功能#

使用 pip extras 安装可选依赖#

使用 pip 安装 pandas 时,还可以通过指定 extra 来安装可选依赖集。

pip install "pandas[performance, aws]>=2.0.0"

可在安装指南中找到的可用 extra 包括 [all, performance, computation, fss, aws, gcp, excel, parquet, feather, hdf5, spss, postgresql, mysql, sql-other, html, xml, plot, output_formatting, clipboard, compression, test] (GH 39164)。

Index 现在可以持有 numpy 数字 dtype#

现在可以在 Index 中使用任何 numpy 数字 dtype (GH 42717)。

以前,只能使用 int64uint64float64 dtype

In [1]: pd.Index([1, 2, 3], dtype=np.int8)
Out[1]: Int64Index([1, 2, 3], dtype="int64")
In [2]: pd.Index([1, 2, 3], dtype=np.uint16)
Out[2]: UInt64Index([1, 2, 3], dtype="uint64")
In [3]: pd.Index([1, 2, 3], dtype=np.float32)
Out[3]: Float64Index([1.0, 2.0, 3.0], dtype="float64")

Int64IndexUInt64IndexFloat64Index 在 pandas 1.4 版本中已被弃用,现已移除。现在应直接使用 Index,它可以接受所有 numpy 数字 dtype,即 int8/int16/int32/int64/uint8/uint16/uint32/uint64/float32/float64 dtype。

In [1]: pd.Index([1, 2, 3], dtype=np.int8)
Out[1]: Index([1, 2, 3], dtype='int8')

In [2]: pd.Index([1, 2, 3], dtype=np.uint16)
Out[2]: Index([1, 2, 3], dtype='uint16')

In [3]: pd.Index([1, 2, 3], dtype=np.float32)
Out[3]: Index([1.0, 2.0, 3.0], dtype='float32')

Index 能够持有 numpy 数字 dtype 的能力带来了 Pandas 功能的一些变化。特别是,以前强制创建 64 位索引的操作,现在可以创建具有较低位大小的索引,例如 32 位索引。

以下是可能不完全的变更列表

  1. 现在使用 numpy 数字数组实例化 Index 会遵循 numpy 数组的 dtype。以前,所有从 numpy 数字数组创建的索引都被强制转换为 64 位。现在,例如,Index(np.array([1, 2, 3])) 在 32 位系统上将是 int32,而以前即使在 32 位系统上也是 int64。使用数字列表实例化 Index 仍将返回 64 位 dtype,例如 Index([1, 2, 3]) 将具有 int64 dtype,这与以前相同。

  2. DatetimeIndex 的各种数字日期时间属性(daymonthyear 等)以前是 int64 dtype,而对于 arrays.DatetimeArray 它们是 int32。现在在 DatetimeIndex 上也是 int32

    In [4]: idx = pd.date_range(start='1/1/2018', periods=3, freq='ME')
    
    In [5]: idx.array.year
    Out[5]: array([2018, 2018, 2018], dtype=int32)
    
    In [6]: idx.year
    Out[6]: Index([2018, 2018, 2018], dtype='int32')
    
  3. 来自 Series.sparse.from_coo() 的 Index 上的 Level dtypes 现在是 int32 dtype,与 scipy 稀疏矩阵上的 rows/cols 相同。以前它们是 int64 dtype。

    In [7]: from scipy import sparse
    
    In [8]: A = sparse.coo_matrix(
       ...:     ([3.0, 1.0, 2.0], ([1, 0, 0], [0, 2, 3])), shape=(3, 4)
       ...: )
       ...: 
    
    In [9]: ser = pd.Series.sparse.from_coo(A)
    
    In [10]: ser.index.dtypes
    Out[10]: 
    level_0    int32
    level_1    int32
    dtype: object
    
  4. 无法使用 float16 dtype 实例化 Index。以前使用 float16 dtype 实例化 Index 会生成一个 Float64Index,其 dtype 为 float64。现在会引发 NotImplementedError

    In [11]: pd.Index([1, 2, 3], dtype=np.float16)
    ---------------------------------------------------------------------------
    NotImplementedError                       Traceback (most recent call last)
    Cell In[11], line 1
    ----> 1 pd.Index([1, 2, 3], dtype=np.float16)
    
    File ~/work/pandas/pandas/pandas/core/indexes/base.py:576, in Index.__new__(cls, data, dtype, copy, name, tupleize_cols)
        572 arr = ensure_wrapped_if_datetimelike(arr)
        574 klass = cls._dtype_to_subclass(arr.dtype)
    --> 576 arr = klass._ensure_array(arr, arr.dtype, copy=False)
        577 result = klass._simple_new(arr, name, refs=refs)
        578 if dtype is None and is_pandas_object and data_dtype == np.object_:
    
    File ~/work/pandas/pandas/pandas/core/indexes/base.py:601, in Index._ensure_array(cls, data, dtype, copy)
        598     raise ValueError("Index data must be 1-dimensional")
        599 elif dtype == np.float16:
        600     # float16 not supported (no indexing engine)
    --> 601     raise NotImplementedError("float16 indexes are not supported")
        603 if copy:
        604     # asarray_tuplesafe does not always copy underlying data,
        605     #  so need to make sure that this happens
        606     data = data.copy()
    
    NotImplementedError: float16 indexes are not supported
    

参数 dtype_backend,用于返回 pyarrow 支持的或 numpy 支持的可空 dtype#

以下函数新增了一个关键字 dtype_backend (GH 36712)

当此选项设置为 "numpy_nullable" 时,将返回一个由可空 dtype 支持的 DataFrame

当此关键字设置为 "pyarrow" 时,这些函数将返回由 pyarrow 支持的可空 ArrowDtype DataFrames (GH 48957, GH 49997)。

In [12]: import io

In [13]: data = io.StringIO("""a,b,c,d,e,f,g,h,i
   ....:     1,2.5,True,a,,,,,
   ....:     3,4.5,False,b,6,7.5,True,a,
   ....: """)
   ....: 

In [14]: df = pd.read_csv(data, dtype_backend="pyarrow")

In [15]: df.dtypes
Out[15]: 
a     int64[pyarrow]
b    double[pyarrow]
c      bool[pyarrow]
d    string[pyarrow]
e     int64[pyarrow]
f    double[pyarrow]
g      bool[pyarrow]
h    string[pyarrow]
i      null[pyarrow]
dtype: object

In [16]: data.seek(0)
Out[16]: 0

In [17]: df_pyarrow = pd.read_csv(data, dtype_backend="pyarrow", engine="pyarrow")

In [18]: df_pyarrow.dtypes
Out[18]: 
a     int64[pyarrow]
b    double[pyarrow]
c      bool[pyarrow]
d    string[pyarrow]
e     int64[pyarrow]
f    double[pyarrow]
g      bool[pyarrow]
h    string[pyarrow]
i      null[pyarrow]
dtype: object

写时复制改进#

  • 写时复制优化 中列出的方法中新增了一种延迟复制机制,该机制会将复制操作推迟到相关对象被修改时进行。启用写时复制后,这些方法会返回视图,与常规执行相比,这提供了显著的性能改进 (GH 49473)。

  • 启用写时复制后,将 DataFrame 的单列作为 Series 访问(例如 df["col"])现在每次构造时都会返回一个新对象(而不是多次返回相同的缓存 Series 对象)。这确保了这些 Series 对象正确遵循写时复制规则 (GH 49450)。

  • 使用默认参数 copy=False 从现有 Series 构造 Series 时,Series 构造函数现在会创建一个延迟复制(将复制推迟到数据发生修改时进行)(GH 50471)。

  • 使用默认参数 copy=False 从现有 DataFrame 构造时,DataFrame 构造函数现在会创建一个延迟复制(将复制推迟到数据发生修改时进行)(GH 51239)。

  • 当使用 Series 对象字典构造 DataFrame 并指定 copy=False 时,DataFrame 构造函数现在将使用这些 Series 对象的延迟复制作为 DataFrame 的列 (GH 50777)。

  • 当使用 SeriesIndex 构造 DataFrame 并指定 copy=False 时,DataFrame 构造函数现在将遵守写时复制规则。

  • DataFrameSeries 构造函数在从 NumPy 数组构造时,现在默认会复制数组,以避免在修改数组时同时修改 DataFrame / Series。指定 copy=False 以获得旧的行为。当设置 copy=False 时,如果在创建 DataFrame / Series 后修改了 NumPy 数组,pandas 不保证正确的写时复制行为。

  • 当使用 DataFrame 调用时,DataFrame.from_records() 现在将遵守写时复制规则。

  • 启用写时复制后,尝试使用链式赋值(例如,df["a"][1:3] = 0)设置值将始终引发警告。在此模式下,链式赋值永远无法工作,因为我们始终在设置到一个临时对象,该对象是索引操作(getitem)的结果,在写时复制下,索引操作始终表现为复制。因此,通过链式赋值永远无法更新原始的 Series 或 DataFrame。为此,会向用户发出一个信息性警告,以避免无声地不执行任何操作 (GH 49467)。

  • inplace=True 时,DataFrame.replace() 现在将遵守写时复制机制。

  • DataFrame.transpose() 现在将遵守写时复制机制。

  • 可以就地执行的算术运算,例如 ser *= 2,现在将遵守写时复制机制。

  • DataFrame 包含 MultiIndex 列时,DataFrame.__getitem__() 现在将遵守写时复制机制。

  • Series.__getitem__() 现在将遵守写时复制机制,当

    Series 包含 MultiIndex 时。

  • Series.view() 现在将遵守写时复制机制。

写时复制可以通过以下方式之一启用

pd.set_option("mode.copy_on_write", True)
pd.options.mode.copy_on_write = True

或者,写时复制可以通过本地方式启用

with pd.option_context("mode.copy_on_write", True):
    ...

其他增强功能#

重要 Bug 修复#

这些 bug 修复可能会带来显著的行为改变。

DataFrameGroupBy.cumsum()DataFrameGroupBy.cumprod() 现在会溢出,而不是有损地转换为浮点数#

在之前的版本中,应用 cumsumcumprod 时会转换为浮点数,这即使结果可以由 int64 dtype 表示,也可能导致不正确的结果。此外,当达到 int64 的限制时,聚合行为现在与 numpy 以及常规的 DataFrame.cumprod()DataFrame.cumsum() 方法一致,会发生溢出 (GH 37493)。

旧行为

In [1]: df = pd.DataFrame({"key": ["b"] * 7, "value": 625})
In [2]: df.groupby("key")["value"].cumprod()[5]
Out[2]: 5.960464477539062e+16

第六个值返回不正确的结果。

新行为

In [19]: df = pd.DataFrame({"key": ["b"] * 7, "value": 625})

In [20]: df.groupby("key")["value"].cumprod()
Out[20]: 
0                   625
1                390625
2             244140625
3          152587890625
4        95367431640625
5     59604644775390625
6    359414837200037393
Name: value, dtype: int64

第七个值会溢出,但第六个值仍然正确。

DataFrameGroupBy.nth()SeriesGroupBy.nth() 现在表现为过滤操作#

在之前的 pandas 版本中,DataFrameGroupBy.nth()SeriesGroupBy.nth() 的行为类似于聚合操作。然而,对于大多数输入 n,它们可能返回每组零行或多行。这意味着它们是过滤操作,类似于例如 DataFrameGroupBy.head()。pandas 现在将其视为过滤操作 (GH 13666)。

In [21]: df = pd.DataFrame({"a": [1, 1, 2, 1, 2], "b": [np.nan, 2.0, 3.0, 4.0, 5.0]})

In [22]: gb = df.groupby("a")

旧行为

In [5]: gb.nth(n=1)
Out[5]:
   A    B
1  1  2.0
4  2  5.0

新行为

In [23]: gb.nth(n=1)
Out[23]: 
   a    b
1  1  2.0
4  2  5.0

特别地,结果的索引是通过选择相应的输入行来派生的。此外,当 n 大于组的大小时,返回零行而不是 NaN

旧行为

In [5]: gb.nth(n=3, dropna="any")
Out[5]:
    B
A
1 NaN
2 NaN

新行为

In [24]: gb.nth(n=3, dropna="any")
Out[24]: 
Empty DataFrame
Columns: [a, b]
Index: []

向后不兼容的 API 变更#

使用不支持分辨率的 datetime64 或 timedelta64 dtype 进行构造#

在过去的版本中,当构造一个 SeriesDataFrame 并传入不支持分辨率(即除 “ns” 以外的任何分辨率)的 “datetime64” 或 “timedelta64” dtype 时,pandas 会静默地将给定的 dtype 替换为其纳秒对应的 dtype

之前的行为:

In [5]: pd.Series(["2016-01-01"], dtype="datetime64[s]")
Out[5]:
0   2016-01-01
dtype: datetime64[ns]

In [6] pd.Series(["2016-01-01"], dtype="datetime64[D]")
Out[6]:
0   2016-01-01
dtype: datetime64[ns]

在 pandas 2.0 中,我们支持 “s”, “ms”, “us”, 和 “ns” 分辨率。当传递支持的 dtype(例如 “datetime64[s]”)时,结果现在具有完全请求的 dtype。

新行为:

In [25]: pd.Series(["2016-01-01"], dtype="datetime64[s]")
Out[25]: 
0   2016-01-01
dtype: datetime64[s]

对于不支持的 dtype,pandas 现在会引发错误,而不是静默地替换为支持的 dtype。

新行为:

In [26]: pd.Series(["2016-01-01"], dtype="datetime64[D]")
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
Cell In[26], line 1
----> 1 pd.Series(["2016-01-01"], dtype="datetime64[D]")

File ~/work/pandas/pandas/pandas/core/series.py:584, in Series.__init__(self, data, index, dtype, name, copy, fastpath)
    582         data = data.copy()
    583 else:
--> 584     data = sanitize_array(data, index, dtype, copy)
    586     manager = _get_option("mode.data_manager", silent=True)
    587     if manager == "block":

File ~/work/pandas/pandas/pandas/core/construction.py:651, in sanitize_array(data, index, dtype, copy, allow_2d)
    648     subarr = np.array([], dtype=np.float64)
    650 elif dtype is not None:
--> 651     subarr = _try_cast(data, dtype, copy)
    653 else:
    654     subarr = maybe_convert_platform(data)

File ~/work/pandas/pandas/pandas/core/construction.py:811, in _try_cast(arr, dtype, copy)
    806     return lib.ensure_string_array(arr, convert_na_value=False, copy=copy).reshape(
    807         shape
    808     )
    810 elif dtype.kind in "mM":
--> 811     return maybe_cast_to_datetime(arr, dtype)
    813 # GH#15832: Check if we are requesting a numeric dtype and
    814 # that we can convert the data to the requested dtype.
    815 elif dtype.kind in "iu":
    816     # this will raise if we have e.g. floats

File ~/work/pandas/pandas/pandas/core/dtypes/cast.py:1218, in maybe_cast_to_datetime(value, dtype)
   1214     raise TypeError("value must be listlike")
   1216 # TODO: _from_sequence would raise ValueError in cases where
   1217 #  _ensure_nanosecond_dtype raises TypeError
-> 1218 _ensure_nanosecond_dtype(dtype)
   1220 if lib.is_np_dtype(dtype, "m"):
   1221     res = TimedeltaArray._from_sequence(value, dtype=dtype)

File ~/work/pandas/pandas/pandas/core/dtypes/cast.py:1275, in _ensure_nanosecond_dtype(dtype)
   1272     raise ValueError(msg)
   1273 # TODO: ValueError or TypeError? existing test
   1274 #  test_constructor_generic_timestamp_bad_frequency expects TypeError
-> 1275 raise TypeError(
   1276     f"dtype={dtype} is not supported. Supported resolutions are 's', "
   1277     "'ms', 'us', and 'ns'"
   1278 )

TypeError: dtype=datetime64[D] is not supported. Supported resolutions are 's', 'ms', 'us', and 'ns'

Value counts 将结果的名称设置为 count#

在过去的版本中,运行 Series.value_counts() 时,结果会继承原始对象的名称,并且结果索引会没有名称。这在重置索引时会引起混淆,并且列名与列值不对应。现在,结果名称将是 'count'(如果传入 normalize=True,则为 'proportion'),并且索引将以原始对象命名 (GH 49497)。

之前的行为:

In [8]: pd.Series(['quetzal', 'quetzal', 'elk'], name='animal').value_counts()

Out[2]:
quetzal    2
elk        1
Name: animal, dtype: int64

新行为:

In [27]: pd.Series(['quetzal', 'quetzal', 'elk'], name='animal').value_counts()
Out[27]: 
animal
quetzal    2
elk        1
Name: count, dtype: int64

对于其他 value_counts 方法(例如 DataFrame.value_counts())也是如此。

禁止 astype 转换为不支持的 datetime64/timedelta64 dtypes#

在之前的版本中,将 SeriesDataFramedatetime64[ns] 转换为不同的 datetime64[X] dtype 时,返回的结果仍然是 datetime64[ns] dtype,而不是请求的 dtype。在 pandas 2.0 中,添加了对 “datetime64[s]”、“datetime64[ms]” 和 “datetime64[us]” dtypes 的支持,因此转换为这些 dtype 会得到完全请求的 dtype。

之前的行为:

In [28]: idx = pd.date_range("2016-01-01", periods=3)

In [29]: ser = pd.Series(idx)

之前的行为:

In [4]: ser.astype("datetime64[s]")
Out[4]:
0   2016-01-01
1   2016-01-02
2   2016-01-03
dtype: datetime64[ns]

在新行为下,我们得到完全请求的 dtype。

新行为:

In [30]: ser.astype("datetime64[s]")
Out[30]: 
0   2016-01-01
1   2016-01-02
2   2016-01-03
dtype: datetime64[s]

对于不支持的分辨率,例如 “datetime64[D]”,我们会引发错误,而不是静默忽略请求的 dtype。

新行为:

In [31]: ser.astype("datetime64[D]")
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
Cell In[31], line 1
----> 1 ser.astype("datetime64[D]")

File ~/work/pandas/pandas/pandas/core/generic.py:6643, in NDFrame.astype(self, dtype, copy, errors)
   6637     results = [
   6638         ser.astype(dtype, copy=copy, errors=errors) for _, ser in self.items()
   6639     ]
   6641 else:
   6642     # else, only a single dtype is given
-> 6643     new_data = self._mgr.astype(dtype=dtype, copy=copy, errors=errors)
   6644     res = self._constructor_from_mgr(new_data, axes=new_data.axes)
   6645     return res.__finalize__(self, method="astype")

File ~/work/pandas/pandas/pandas/core/internals/managers.py:430, in BaseBlockManager.astype(self, dtype, copy, errors)
    427 elif using_copy_on_write():
    428     copy = False
--> 430 return self.apply(
    431     "astype",
    432     dtype=dtype,
    433     copy=copy,
    434     errors=errors,
    435     using_cow=using_copy_on_write(),
    436 )

File ~/work/pandas/pandas/pandas/core/internals/managers.py:363, in BaseBlockManager.apply(self, f, align_keys, **kwargs)
    361         applied = b.apply(f, **kwargs)
    362     else:
--> 363         applied = getattr(b, f)(**kwargs)
    364     result_blocks = extend_blocks(applied, result_blocks)
    366 out = type(self).from_blocks(result_blocks, self.axes)

File ~/work/pandas/pandas/pandas/core/internals/blocks.py:758, in Block.astype(self, dtype, copy, errors, using_cow, squeeze)
    755         raise ValueError("Can not squeeze with more than one column.")
    756     values = values[0, :]  # type: ignore[call-overload]
--> 758 new_values = astype_array_safe(values, dtype, copy=copy, errors=errors)
    760 new_values = maybe_coerce_values(new_values)
    762 refs = None

File ~/work/pandas/pandas/pandas/core/dtypes/astype.py:237, in astype_array_safe(values, dtype, copy, errors)
    234     dtype = dtype.numpy_dtype
    236 try:
--> 237     new_values = astype_array(values, dtype, copy=copy)
    238 except (ValueError, TypeError):
    239     # e.g. _astype_nansafe can fail on object-dtype of strings
    240     #  trying to convert to float
    241     if errors == "ignore":

File ~/work/pandas/pandas/pandas/core/dtypes/astype.py:179, in astype_array(values, dtype, copy)
    175     return values
    177 if not isinstance(values, np.ndarray):
    178     # i.e. ExtensionArray
--> 179     values = values.astype(dtype, copy=copy)
    181 else:
    182     values = _astype_nansafe(values, dtype, copy=copy)

File ~/work/pandas/pandas/pandas/core/arrays/datetimes.py:739, in DatetimeArray.astype(self, dtype, copy)
    737 elif isinstance(dtype, PeriodDtype):
    738     return self.to_period(freq=dtype.freq)
--> 739 return dtl.DatetimeLikeArrayMixin.astype(self, dtype, copy)

File ~/work/pandas/pandas/pandas/core/arrays/datetimelike.py:494, in DatetimeLikeArrayMixin.astype(self, dtype, copy)
    490 elif (dtype.kind in "mM" and self.dtype != dtype) or dtype.kind == "f":
    491     # disallow conversion between datetime/timedelta,
    492     # and conversions for any datetimelike to float
    493     msg = f"Cannot cast {type(self).__name__} to dtype {dtype}"
--> 494     raise TypeError(msg)
    495 else:
    496     return np.asarray(self, dtype=dtype)

TypeError: Cannot cast DatetimeArray to dtype datetime64[D]

对于从 timedelta64[ns] dtypes 的转换,旧行为会转换为浮点格式。

之前的行为:

In [32]: idx = pd.timedelta_range("1 Day", periods=3)

In [33]: ser = pd.Series(idx)

之前的行为:

In [7]: ser.astype("timedelta64[s]")
Out[7]:
0     86400.0
1    172800.0
2    259200.0
dtype: float64

In [8]: ser.astype("timedelta64[D]")
Out[8]:
0    1.0
1    2.0
2    3.0
dtype: float64

新行为与 datetime64 类似,要么给出完全请求的 dtype,要么引发错误。

新行为:

In [34]: ser.astype("timedelta64[s]")
Out[34]: 
0   1 days
1   2 days
2   3 days
dtype: timedelta64[s]

In [35]: ser.astype("timedelta64[D]")
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
Cell In[35], line 1
----> 1 ser.astype("timedelta64[D]")

File ~/work/pandas/pandas/pandas/core/generic.py:6643, in NDFrame.astype(self, dtype, copy, errors)
   6637     results = [
   6638         ser.astype(dtype, copy=copy, errors=errors) for _, ser in self.items()
   6639     ]
   6641 else:
   6642     # else, only a single dtype is given
-> 6643     new_data = self._mgr.astype(dtype=dtype, copy=copy, errors=errors)
   6644     res = self._constructor_from_mgr(new_data, axes=new_data.axes)
   6645     return res.__finalize__(self, method="astype")

File ~/work/pandas/pandas/pandas/core/internals/managers.py:430, in BaseBlockManager.astype(self, dtype, copy, errors)
    427 elif using_copy_on_write():
    428     copy = False
--> 430 return self.apply(
    431     "astype",
    432     dtype=dtype,
    433     copy=copy,
    434     errors=errors,
    435     using_cow=using_copy_on_write(),
    436 )

File ~/work/pandas/pandas/pandas/core/internals/managers.py:363, in BaseBlockManager.apply(self, f, align_keys, **kwargs)
    361         applied = b.apply(f, **kwargs)
    362     else:
--> 363         applied = getattr(b, f)(**kwargs)
    364     result_blocks = extend_blocks(applied, result_blocks)
    366 out = type(self).from_blocks(result_blocks, self.axes)

File ~/work/pandas/pandas/pandas/core/internals/blocks.py:758, in Block.astype(self, dtype, copy, errors, using_cow, squeeze)
    755         raise ValueError("Can not squeeze with more than one column.")
    756     values = values[0, :]  # type: ignore[call-overload]
--> 758 new_values = astype_array_safe(values, dtype, copy=copy, errors=errors)
    760 new_values = maybe_coerce_values(new_values)
    762 refs = None

File ~/work/pandas/pandas/pandas/core/dtypes/astype.py:237, in astype_array_safe(values, dtype, copy, errors)
    234     dtype = dtype.numpy_dtype
    236 try:
--> 237     new_values = astype_array(values, dtype, copy=copy)
    238 except (ValueError, TypeError):
    239     # e.g. _astype_nansafe can fail on object-dtype of strings
    240     #  trying to convert to float
    241     if errors == "ignore":

File ~/work/pandas/pandas/pandas/core/dtypes/astype.py:179, in astype_array(values, dtype, copy)
    175     return values
    177 if not isinstance(values, np.ndarray):
    178     # i.e. ExtensionArray
--> 179     values = values.astype(dtype, copy=copy)
    181 else:
    182     values = _astype_nansafe(values, dtype, copy=copy)

File ~/work/pandas/pandas/pandas/core/arrays/timedeltas.py:358, in TimedeltaArray.astype(self, dtype, copy)
    354         return type(self)._simple_new(
    355             res_values, dtype=res_values.dtype, freq=self.freq
    356         )
    357     else:
--> 358         raise ValueError(
    359             f"Cannot convert from {self.dtype} to {dtype}. "
    360             "Supported resolutions are 's', 'ms', 'us', 'ns'"
    361         )
    363 return dtl.DatetimeLikeArrayMixin.astype(self, dtype, copy=copy)

ValueError: Cannot convert from timedelta64[ns] to timedelta64[D]. Supported resolutions are 's', 'ms', 'us', 'ns'

UTC 和固定偏移时区默认使用标准库的 tzinfo 对象#

在之前的版本中,用于表示 UTC 的默认 tzinfo 对象是 pytz.UTC。在 pandas 2.0 中,我们默认使用 datetime.timezone.utc。类似地,对于表示固定 UTC 偏移的时区,我们使用 datetime.timezone 对象而不是 pytz.FixedOffset 对象。参见 (GH 34916)

之前的行为:

In [2]: ts = pd.Timestamp("2016-01-01", tz="UTC")
In [3]: type(ts.tzinfo)
Out[3]: pytz.UTC

In [4]: ts2 = pd.Timestamp("2016-01-01 04:05:06-07:00")
In [3]: type(ts2.tzinfo)
Out[5]: pytz._FixedOffset

新行为:

In [36]: ts = pd.Timestamp("2016-01-01", tz="UTC")

In [37]: type(ts.tzinfo)
Out[37]: datetime.timezone

In [38]: ts2 = pd.Timestamp("2016-01-01 04:05:06-07:00")

In [39]: type(ts2.tzinfo)
Out[39]: datetime.timezone

对于既非 UTC 也非固定偏移的时区,例如 “US/Pacific”,我们仍然默认使用 pytz 对象。

空的 DataFrame/Series 现在默认使用 RangeIndex#

之前,构造一个空的(其中 dataNone 或空的类列表参数)SeriesDataFrame 且不指定轴 (index=None, columns=None) 时,轴会返回为空的具有 object dtype 的 Index

现在,轴返回空的 RangeIndex (GH 49572)。

之前的行为:

In [8]: pd.Series().index
Out[8]:
Index([], dtype='object')

In [9] pd.DataFrame().axes
Out[9]:
[Index([], dtype='object'), Index([], dtype='object')]

新行为:

In [40]: pd.Series().index
Out[40]: RangeIndex(start=0, stop=0, step=1)

In [41]: pd.DataFrame().axes
Out[41]: [RangeIndex(start=0, stop=0, step=1), RangeIndex(start=0, stop=0, step=1)]

DataFrame 转换为 LaTeX 现在使用新的渲染引擎#

现有的 DataFrame.to_latex() 经过重构,以利用先前在 Styler.to_latex() 下可用的扩展实现。参数签名类似,尽管 col_space 已被移除,因为它会被 LaTeX 引擎忽略。此渲染引擎还需要安装 jinja2 作为依赖项,因为渲染基于 jinja2 模板。

以下 pandas latex 选项已不再使用并被移除。通用的最大行和列参数保留,但对于此功能应替换为 Styler 对应的参数。提供类似功能的替代选项如下所示

  • display.latex.escape:替换为 styler.format.escape

  • display.latex.longtable:替换为 styler.latex.environment

  • display.latex.multicolumndisplay.latex.multicolumn_formatdisplay.latex.multirow:替换为 styler.sparse.rowsstyler.sparse.columnsstyler.latex.multirow_alignstyler.latex.multicol_align

  • display.latex.repr:替换为 styler.render.repr

  • display.max_rowsdisplay.max_columns:替换为 styler.render.max_rowsstyler.render.max_columnsstyler.render.max_elements

请注意,由于此更改,一些默认值也发生了变化

  • multirow 现在默认为 True

  • multirow_align 默认值为 “r” 而不是 “l”

  • multicol_align 默认值为 “r” 而不是 “l”

  • escape 现在默认为 False

请注意,_repr_latex_ 的行为也发生了变化。之前设置 display.latex.repr 只在使用 nbconvert 转换 Jupyter Notebook 时生成 LaTeX,而在用户运行 Notebook 时不会。现在 styler.render.repr 选项允许控制在 Jupyter Notebook 中针对操作(不仅仅是 nbconvert)的特定输出。参见 (GH 39911)。

提高了依赖项的最低版本要求#

一些依赖项的最低支持版本已更新。如果已安装,现在需要

最低版本

必需

已更改

mypy (开发)

1.0

X

pytest (开发)

7.0.0

X

pytest-xdist (开发)

2.2.0

X

hypothesis (开发)

6.34.2

X

python-dateutil

2.8.2

X

X

tzdata

2022.1

X

X

对于可选库,一般建议使用最新版本。下表列出了 pandas 开发过程中当前测试的每个库的最低版本。低于最低测试版本的可选库可能仍然可用,但不支持。

最低版本

已更改

pyarrow

7.0.0

X

matplotlib

3.6.1

X

fastparquet

0.6.3

X

xarray

0.21.0

X

更多信息请参见 DependenciesOptional dependencies

日期时间现在以一致的格式解析#

过去,to_datetime() 会独立猜测每个元素的格式。这对于元素具有混合日期格式的某些情况是合适的——然而,当用户期望一致的格式但函数在元素之间切换格式时,这会经常导致问题。从 2.0.0 版本开始,解析将使用一致的格式,由第一个非 NA 值确定(除非用户指定了格式,在这种情况下使用指定的格式)。

旧行为:

In [1]: ser = pd.Series(['13-01-2000', '12-01-2000'])
In [2]: pd.to_datetime(ser)
Out[2]:
0   2000-01-13
1   2000-12-01
dtype: datetime64[ns]

新行为:

In [42]: ser = pd.Series(['13-01-2000', '12-01-2000'])

In [43]: pd.to_datetime(ser)
Out[43]: 
0   2000-01-13
1   2000-01-12
dtype: datetime64[ns]

请注意,这也影响 read_csv()

如果你仍然需要解析格式不一致的日期,可以使用 format='mixed'(可能 همراه dayfirst 一起使用)

ser = pd.Series(['13-01-2000', '12 January 2000'])
pd.to_datetime(ser, format='mixed', dayfirst=True)

或者,如果你的格式都是 ISO8601(但格式可能不完全相同)

ser = pd.Series(['2020-01-01', '2020-01-01 03:00'])
pd.to_datetime(ser, format='ISO8601')

其他 API 变更#

  • Timestamp 构造函数中的 freqtznanosecondunit 关键字现在仅为关键字参数 (GH 45307, GH 32526)

  • Timestamp 中传入大于 999 或小于 0 的 nanoseconds 现在会引发 ValueError (GH 48538, GH 48255)

  • read_csv():使用 C 解析器时,使用 index_col 指定不正确的列数现在会引发 ParserError 而不是 IndexError

  • get_dummies()dtype 的默认值从 uint8 更改为 bool (GH 45848)

  • DataFrame.astype()Series.astype()DatetimeIndex.astype() 将 datetime64 数据转换为 “datetime64[s]”、“datetime64[ms]” 或 “datetime64[us]” 中的任何一种,将返回具有指定分辨率的对象,而不是强制转换回 “datetime64[ns]” (GH 48928)

  • DataFrame.astype()Series.astype()DatetimeIndex.astype() 将 timedelta64 数据转换为 “timedelta64[s]”、“timedelta64[ms]” 或 “timedelta64[us]” 中的任何一种,将返回具有指定分辨率的对象,而不是强制转换为 “float64” dtype (GH 48963)

  • DatetimeIndex.astype()TimedeltaIndex.astype()PeriodIndex.astype()Series.astype()DataFrame.astype() 对于 datetime64timedelta64PeriodDtype dtypes 的数据,不再允许转换为除 “int64” 以外的整数 dtypes,请改为执行 obj.astype('int64', copy=False).astype(dtype) (GH 49715)

  • Index.astype() 现在允许将 float64 dtype 转换为类似 datetime 的 dtypes,与 Series 的行为一致 (GH 49660)

  • 将具有 “timedelta64[s]”、“timedelta64[ms]” 或 “timedelta64[us]” dtype 的数据传递给 TimedeltaIndexSeriesDataFrame 构造函数时,现在将保留该 dtype 而不是强制转换为 “timedelta64[ns]”;分辨率较低的 timedelta64 数据将被强制转换为最低支持的分辨率 “timedelta64[s]” (GH 49014)

  • dtype “timedelta64[s]”、“timedelta64[ms]”或“timedelta64[us]”传递给 TimedeltaIndexSeriesDataFrame 构造函数时,现在会保留该 dtype,而不是将其转换为“timedelta64[ns]”;对于 SeriesDataFrame 传递较低分辨率的 dtype 时,会将其转换为最低支持的分辨率“timedelta64[s]” (GH 49014)

  • 将非纳秒分辨率的 np.datetime64 对象传递给 Timestamp 时,如果分辨率是“s”、“ms”、“us”或“ns”,则会保留输入分辨率;否则会将其转换为最接近的支持分辨率 (GH 49008)

  • 将分辨率不是纳秒的 datetime64 值传递给 to_datetime() 时,如果分辨率是“s”、“ms”、“us”或“ns”,则会保留输入分辨率;否则会将其转换为最接近的支持分辨率 (GH 50369)

  • 将整数值和非纳秒 datetime64 dtype(例如“datetime64[s]”)传递给 DataFrameSeriesIndex 时,会将被视为 dtype 单位的倍数,与例如 Series(np.array(values, dtype="M8[s]")) 的行为一致 (GH 51092)

  • 将 ISO-8601 格式的字符串传递给 Timestamp 时,如果解析输入的精度是“s”、“ms”、“us”或“ns”,则会保留该精度;否则会将其转换为最接近的支持精度 (GH 49737)

  • DataFrame.mask()Series.mask() 中的 other 参数现在默认为 no_default,而不是 np.nan,与 DataFrame.where()Series.where() 的行为一致。条目将填充相应的 NULL 值(numpy dtypes 对应 np.nan,扩展 dtypes 对应 pd.NA)。(GH 49111)

  • 改变了 Series.quantile()DataFrame.quantile() 处理 SparseDtype 时的行为,现在会保留稀疏 dtype (GH 49583)

  • 使用包含 datetime 对象的 object-dtype Index 创建 Series 时,pandas 不再静默地将索引转换为 DatetimeIndex (GH 39307, GH 23598)

  • 参数为 exact="equiv"pandas.testing.assert_index_equal() 现在认为当两个索引都是 RangeIndex 或带有 int64 dtype 的 Index 时是相等的。之前它指的是 RangeIndexInt64Index (GH 51098)

  • dtype 为“timedelta64[ns]”或“datetime64[ns]”的 Series.unique() 现在返回 TimedeltaArrayDatetimeArray,而不是 numpy.ndarray (GH 49176)

  • to_datetime()DatetimeIndex 现在允许包含 datetime 对象和数值项的序列,与 Series 的行为一致 (GH 49037, GH 50453)

  • pandas.api.types.is_string_dtype() 现在仅在 dtype 为 object 且元素被推断为字符串时,对于 array-like 对象返回 True (GH 15585)

  • 将包含 datetime 对象和 date 对象的序列传递给 Series 构造函数时,会返回 object dtype,而不是 datetime64[ns] dtype,与 Index 的行为一致 (GH 49341)

  • 将无法解析为 datetime 的字符串传递给 dtype 为 "datetime64[ns]"SeriesDataFrame 时,现在会引发错误,而不是静默忽略该关键字并返回 object dtype (GH 24435)

  • 将包含无法转换为 Timedelta 的类型的序列传递给 to_timedelta(),或传递给 dtype 为 "timedelta64[ns]"SeriesDataFrame 构造函数,或传递给 TimedeltaIndex 时,现在会引发 TypeError,而不是 ValueError (GH 49525)

  • 改变了 Index 构造函数的行为,当序列中至少包含一个 NaT 且其他所有元素都是 NoneNaN 时,会推断出 datetime64[ns] dtype,而不是 object dtype,与 Series 的行为一致 (GH 49340)

  • 参数 index_col 设置为 None(默认值)的 read_stata() 现在会将返回的 DataFrame 的索引设置为 RangeIndex,而不是 Int64Index (GH 49745)

  • 改变了 IndexSeriesDataFrame 在处理 object-dtypes 时的算术方法行为,结果不再对数组操作的结果进行类型推断,请使用 result.infer_objects(copy=False) 对结果进行类型推断以获得旧行为 (GH 49999, GH 49714)

  • 改变了 Index 构造函数的行为,当输入是包含全 bool 值或全复数值的 object-dtype numpy.ndarray 时,现在会保留 object dtype,与 Series 的行为一致 (GH 49594)

  • 改变了 Series.astype() 从包含 bytes 对象的 object-dtype 转换为字符串 dtypes 的行为;现在对 bytes 对象执行 val.decode(),而不是 str(val),与 Index.astype() 的行为一致 (GH 45326)

  • read_csv() 的默认 na_values 中添加了 "None" (GH 50286)

  • 改变了 SeriesDataFrame 构造函数的行为,当给定整数 dtype 和非整数浮点数据时,现在会引发 ValueError,而不是静默保留 float dtype;执行 Series(data)DataFrame(data) 以获得旧行为,执行 Series(data).astype(dtype)DataFrame(data).astype(dtype) 以获得指定的 dtype (GH 49599)

  • 改变了参数为 axis=1,整数 fill_value,且 dtype 为同构 datetime-like 的 DataFrame.shift() 的行为,现在会用整数 dtypes 填充新列,而不是转换为 datetimelike (GH 49842)

  • read_json() 中遇到异常时,现在会关闭文件 (GH 49921)

  • 改变了 read_csv()read_json()read_fwf() 的行为,在未指定索引时,索引现在将始终是 RangeIndex。之前,如果新的 DataFrame/Series 长度为 0,索引会是 dtype 为 objectIndex (GH 49572)

  • DataFrame.values()DataFrame.to_numpy()DataFrame.xs()DataFrame.reindex()DataFrame.fillna()DataFrame.replace() 不再静默地合并底层数组;执行 df = df.copy() 来确保合并 (GH 49356)

  • 使用 lociloc 在两个轴上进行完全切片(即 df.loc[:, :]df.iloc[:, :])创建新的 DataFrame 时,现在会返回一个新的 DataFrame(浅拷贝),而不是原始 DataFrame,与获取完全切片的其他方法(例如 df.loc[:]df[:])一致 (GH 49469)

  • 当分别传递 Series 和 DataFrame 并且使用默认值 copy=False(且没有其他关键字触发拷贝)时,SeriesDataFrame 构造函数现在会返回一个浅拷贝(即共享数据,但不共享属性)。之前,新的 Series 或 DataFrame 会共享 index 属性(例如,df.index = ... 也会更新父对象或子对象的 index) (GH 49523)

  • 禁止计算 Timedelta 对象的 cumprod;之前这会返回不正确的值 (GH 50246)

  • 从不带索引的 HDFStore 文件读取的 DataFrame 对象现在具有 RangeIndex 索引,而不是 int64 索引 (GH 51076)

  • 使用包含 NA 和/或 NaT 数据的 numeric numpy dtype 实例化 Index 时,现在会引发一个 ValueError。之前会引发一个 TypeError (GH 51050)

  • 使用 read_json(orient='split') 加载具有重复列的 JSON 文件时,会重命名列以避免重复,与 read_csv() 及其他读取函数的行为一致 (GH 50370)

  • Series.sparse.from_coo 返回的 Series 的索引级别现在总是具有 dtype int32。之前它们具有 dtype int64 (GH 50926)

  • 参数 unit 为“Y”或“M”的 to_datetime() 如果序列包含非整数的 float 值,现在会引发错误,与 Timestamp 的行为一致 (GH 50301)

  • 方法 Series.round()DataFrame.__invert__()Series.__invert__()DataFrame.swapaxes()DataFrame.first()DataFrame.last()Series.first()Series.last()DataFrame.align() 现在总是返回新对象 (GH 51032)

  • object-dtype 列的 DataFrameDataFrameGroupBy 聚合(例如“sum”)不再推断结果的非 object dtypes,请在结果上显式调用 result.infer_objects(copy=False) 以获得旧行为 (GH 51205, GH 49603)

  • ArrowDtype dtypes 的零除操作现在根据分子返回 -infnaninf,而不是引发错误 (GH 51541)

  • 添加了 pandas.api.types.is_any_real_numeric_dtype() 用于检查实数数值 dtype (GH 51152)

  • value_counts() 现在返回带有 ArrowDtype 类型 pyarrow.int64 的数据,而不是 "Int64" 类型的数据 (GH 51462)

  • 当传入非纳秒分辨率的 numpy timedelta64 或 datetime64 时,factorize()unique() 会保留原始 dtype (GH 48670)

注意

当前的一个 PDEP 提议弃用并移除 pandas API 中除一小部分方法以外的所有方法的 inplacecopy 关键字。当前的讨论位于 此处。在 Copy-on-Write 的背景下,这些关键字将不再需要。如果该提议被接受,这两个关键字将在 pandas 的下一个版本中被弃用,并在 pandas 3.0 中移除。

弃用#

移除之前版本的弃用/更改#

  • 已移除 Int64Index, UInt64IndexFloat64Index。更多信息请参见 此处 (GH 42717)

  • 已移除 Timestamp.freq, Timestamp.freqstr 以及 Timestamp 构造函数和 Timestamp.fromordinal() 中的弃用参数 freq (GH 14146)

  • 已移除弃用的 CategoricalBlock, Block.is_categorical(),要求在传递给 Block.make_block_same_class() 之前将 datetime64 和 timedelta64 值包装在 DatetimeArrayTimedeltaArray 中,要求 DatetimeTZBlock.values 在传递给 BlockManager 构造函数时具有正确的 ndim,并移除了 SingleBlockManager 构造函数中的 “fastpath” 关键字 (GH 40226, GH 40571)

  • 已移除弃用的全局选项 use_inf_as_null,请改用 use_inf_as_na (GH 17126)

  • 已移除弃用的模块 pandas.core.index (GH 30193)

  • 已移除弃用的别名 pandas.core.tools.datetimes.to_time,请直接从 pandas.core.tools.times 导入该函数 (GH 34145)

  • 已移除弃用的别名 pandas.io.json.json_normalize,请直接从 pandas.json_normalize 导入该函数 (GH 27615)

  • 已移除弃用的 Categorical.to_dense(),请改用 np.asarray(cat) (GH 32639)

  • 已移除弃用的 Categorical.take_nd() (GH 27745)

  • 已移除弃用的 Categorical.mode(),请改用 Series(cat).mode() (GH 45033)

  • 已移除弃用的 Categorical.is_dtype_equal()CategoricalIndex.is_dtype_equal() (GH 37545)

  • 已移除弃用的 CategoricalIndex.take_nd() (GH 30702)

  • 已移除弃用的 Index.is_type_compatible() (GH 42113)

  • 已移除弃用的 Index.is_mixed(),请直接检查 index.inferred_type (GH 32922)

  • 已移除弃用的 pandas.api.types.is_categorical();请改用 pandas.api.types.is_categorical_dtype() (GH 33385)

  • 已移除弃用的 Index.asi8() (GH 37877)

  • 已强制执行的弃用更改了以下行为:当将 datetime64[ns] dtype 数据和时区感知 dtype 传递给 Series 时,将值解释为墙上时间而不是 UTC 时间,与 DatetimeIndex 的行为一致 (GH 41662)

  • 已强制执行的弃用更改了以下行为:对多个未对齐(在索引或列上)的 DataFrame 应用 numpy ufunc 时,现在将首先对齐输入 (GH 39239)

  • 已移除弃用的 DataFrame._AXIS_NUMBERS(), DataFrame._AXIS_NAMES(), Series._AXIS_NUMBERS(), Series._AXIS_NAMES() (GH 33637)

  • 已移除弃用的 Index.to_native_types(),请改用 obj.astype(str) (GH 36418)

  • 已移除弃用的 Series.iteritems(), DataFrame.iteritems(),请改用 obj.items (GH 45321)

  • 已移除弃用的 DataFrame.lookup() (GH 35224)

  • 已移除弃用的 Series.append(), DataFrame.append(),请改用 concat() (GH 35407)

  • 已移除弃用的 Series.iteritems(), DataFrame.iteritems()HDFStore.iteritems(),请改用 obj.items (GH 45321)

  • 已移除弃用的 DatetimeIndex.union_many() (GH 45018)

  • 已移除弃用的 DatetimeArray, DatetimeIndexdt 访问器中的 weekofyearweek 属性,请改用 isocalendar().week (GH 33595)

  • 已移除弃用的 RangeIndex._start(), RangeIndex._stop(), RangeIndex._step(),请改用 start, stop, step (GH 30482)

  • 已移除弃用的 DatetimeIndex.to_perioddelta(),请改用 dtindex - dtindex.to_period(freq).to_timestamp() (GH 34853)

  • 已移除弃用的 Styler.hide_index()Styler.hide_columns() (GH 49397)

  • 已移除弃用的 Styler.set_na_rep()Styler.set_precision() (GH 49397)

  • 已移除弃用的 Styler.where() (GH 49397)

  • 已移除弃用的 Styler.render() (GH 49397)

  • 已移除 DataFrame.to_latex() 中的弃用参数 col_space (GH 47970)

  • 已移除 Styler.highlight_null() 中的弃用参数 null_color (GH 49397)

  • 已移除 testing.assert_frame_equal(), testing.assert_extension_array_equal(), testing.assert_series_equal(), testing.assert_index_equal() 中的弃用参数 check_less_precise (GH 30562)

  • 已移除 DataFrame.info() 中的弃用参数 null_counts。请改用 show_counts (GH 37999)

  • 已移除弃用的 Index.is_monotonic(), 和 Series.is_monotonic();请改用 obj.is_monotonic_increasing (GH 45422)

  • 已移除弃用的 Index.is_all_dates() (GH 36697)

  • 已强制执行的弃用禁止将时区感知 Timestampdtype="datetime64[ns]" 传递给 SeriesDataFrame 构造函数 (GH 41555)

  • 已强制执行的弃用禁止将时区感知值序列和 dtype="datetime64[ns]" 传递给 SeriesDataFrame 构造函数 (GH 41555)

  • 已强制执行的弃用禁止在 DataFrame 构造函数中使用 numpy.ma.mrecords.MaskedRecords;请改传 "{name: data[name] for name in data.dtype.names} (GH 40363)

  • 已强制执行的弃用禁止在 Series.astype()DataFrame.astype() 中使用不带单位的 “datetime64” dtype 进行转换 (GH 47844)

  • 已强制执行的弃用禁止使用 .astypedatetime64[ns] Series, DataFrame, 或 DatetimeIndex 转换为时区感知 dtype,请改用 obj.tz_localizeser.dt.tz_localize (GH 39258)

  • 已强制执行的弃用禁止使用 .astype 将时区感知 Series, DataFrame, 或 DatetimeIndex 转换为时区 naive 的 datetime64[ns] dtype,请改用 obj.tz_localize(None)obj.tz_convert("UTC").tz_localize(None) (GH 39258)

  • 已强制执行的弃用禁止在 concat() 中向 sort 参数传递非布尔值 (GH 44629)

  • 已移除日期解析函数 parse_date_time(), parse_date_fields(), parse_all_fields()generic_parser() (GH 24518)

  • 已移除 core.arrays.SparseArray 构造函数中的参数 index (GH 43523)

  • 已移除 DataFrame.groupby()Series.groupby() 中的参数 squeeze (GH 32380)

  • 已移除弃用的 DateOffset 属性 apply, apply_index, __call__, onOffset, 和 isAnchored (GH 34171)

  • 已移除 DatetimeIndex.to_series() 中的 keep_tz 参数 (GH 29731)

  • 已移除 Index.copy() 中的参数 namesdtype,并移除 MultiIndex.copy() 中的 levelscodes (GH 35853, GH 36685)

  • 已移除 MultiIndex.set_levels()MultiIndex.set_codes() 中的参数 inplace (GH 35626)

  • 已移除 DataFrame.to_excel()Series.to_excel() 中的参数 verboseencoding (GH 47912)

  • 参数 line_terminator 已从 DataFrame.to_csv()Series.to_csv() 中移除,请改用 lineterminator (GH 45302)

  • 参数 inplace 已从 DataFrame.set_axis()Series.set_axis() 中移除,请改用 obj = obj.set_axis(..., copy=False) (GH 48130)

  • 不允许将位置参数传递给 MultiIndex.set_levels()MultiIndex.set_codes() (GH 41485)

  • 不允许将包含单元 “Y”、“y” 或 “M” 的字符串解析为 Timedelta,因为这些单元不表示明确的持续时间 (GH 36838)

  • MultiIndex.is_lexsorted()MultiIndex.lexsort_depth() 已移除 (GH 38701)

  • 参数 how 已从 PeriodIndex.astype() 中移除,请改用 PeriodIndex.to_timestamp() (GH 37982)

  • 参数 try_cast 已从 DataFrame.mask()DataFrame.where()Series.mask()Series.where() 中移除 (GH 38836)

  • 参数 tz 已从 Period.to_timestamp() 中移除,请改用 obj.to_timestamp(...).tz_localize(tz) (GH 34522)

  • 参数 sort_columns 已在 DataFrame.plot()Series.plot() 中移除 (GH 47563)

  • 参数 is_copy 已从 DataFrame.take()Series.take() 中移除 (GH 30615)

  • 参数 kind 已从 Index.get_slice_bound()Index.slice_indexer()Index.slice_locs() 中移除 (GH 41378)

  • 参数 prefixsqueezeerror_bad_lineswarn_bad_lines 已从 read_csv() 中移除 (GH 40413, GH 43427)

  • 参数 squeeze 已从 read_excel() 中移除 (GH 43427)

  • 参数 datetime_is_numeric 已从 DataFrame.describe()Series.describe() 中移除,因为日期时间数据将始终汇总为数字数据 (GH 34798)

  • 不允许将列表 key 传递给 Series.xs()DataFrame.xs(),请改用元组 (GH 41789)

  • 不允许在 Index 构造函数中使用子类特定的关键字(例如“freq”、“tz”、“names”、“closed”) (GH 38597)

  • 参数 inplace 已从 Categorical.remove_unused_categories() 中移除 (GH 37918)

  • 不允许将非整数浮点数传递给 Timestamp,当 unit="M"unit="Y" 时 (GH 47266)

  • 关键字 convert_floatmangle_dupe_cols 已从 read_excel() 中移除 (GH 41176)

  • 关键字 mangle_dupe_cols 已从 read_csv()read_table() 中移除 (GH 48137)

  • 关键字 errors 已从 DataFrame.where()Series.where()DataFrame.mask()Series.mask() 中移除 (GH 47728)

  • 不允许将非关键字参数传递给 read_excel(),但 iosheet_name 除外 (GH 34418)

  • 不允许将非关键字参数传递给 DataFrame.drop()Series.drop(),但 labels 除外 (GH 41486)

  • 不允许将非关键字参数传递给 DataFrame.fillna()Series.fillna(),但 value 除外 (GH 41485)

  • 不允许将非关键字参数传递给 StringMethods.split()StringMethods.rsplit(),但 pat 除外 (GH 47448)

  • 不允许将非关键字参数传递给 DataFrame.set_index(),但 keys 除外 (GH 41495)

  • 不允许将非关键字参数传递给 Resampler.interpolate(),但 method 除外 (GH 41699)

  • 不允许将非关键字参数传递给 DataFrame.reset_index()Series.reset_index(),但 level 除外 (GH 41496)

  • 不允许将非关键字参数传递给 DataFrame.dropna()Series.dropna() (GH 41504)

  • 不允许将非关键字参数传递给 ExtensionArray.argsort() (GH 46134)

  • 不允许将非关键字参数传递给 Categorical.sort_values() (GH 47618)

  • 不允许将非关键字参数传递给 Index.drop_duplicates()Series.drop_duplicates() (GH 41485)

  • 不允许将非关键字参数传递给 DataFrame.drop_duplicates(),但 subset 除外 (GH 41485)

  • 不允许将非关键字参数传递给 DataFrame.sort_index()Series.sort_index() (GH 41506)

  • 不允许将非关键字参数传递给 DataFrame.interpolate()Series.interpolate(),但 method 除外 (GH 41510)

  • 不允许将非关键字参数传递给 DataFrame.any()Series.any() (GH 44896)

  • 不允许将非关键字参数传递给 Index.set_names(),但 names 除外 (GH 41551)

  • 不允许将非关键字参数传递给 Index.join(),但 other 除外 (GH 46518)

  • 不允许将非关键字参数传递给 concat(),但 objs 除外 (GH 41485)

  • 不允许将非关键字参数传递给 pivot(),但 data 除外 (GH 48301)

  • 不允许将非关键字参数传递给 DataFrame.pivot() (GH 48301)

  • 不允许将非关键字参数传递给 read_html(),但 io 除外 (GH 27573)

  • 不允许将非关键字参数传递给 read_json(),但 path_or_buf 除外 (GH 27573)

  • 不允许将非关键字参数传递给 read_sas(),但 filepath_or_buffer 除外 (GH 47154)

  • 不允许将非关键字参数传递给 read_stata(),但 filepath_or_buffer 除外 (GH 48128)

  • 不允许将非关键字参数传递给 read_csv(),但 filepath_or_buffer 除外 (GH 41485)

  • 不允许将非关键字参数传递给 read_table(),但 filepath_or_buffer 除外 (GH 41485)

  • 不允许将非关键字参数传递给 read_fwf(),但 filepath_or_buffer 除外 (GH 44710)

  • 不允许将非关键字参数传递给 read_xml(),但 path_or_buffer 除外 (GH 45133)

  • 不允许将非关键字参数传递给 Series.mask()DataFrame.mask(),但 condother 除外 (GH 41580)

  • 不允许将非关键字参数传递给 DataFrame.to_stata(),但 path 除外 (GH 48128)

  • 不允许将非关键字参数传递给 DataFrame.where()Series.where(),但 condother 除外 (GH 41523)

  • 不允许将非关键字参数传递给 Series.set_axis()DataFrame.set_axis(),但 labels 除外 (GH 41491)

  • 不允许将非关键字参数传递给 Series.rename_axis()DataFrame.rename_axis(),但 mapper 除外 (GH 47587)

  • 不允许将非关键字参数传递给 Series.clip()DataFrame.clip(),但 lowerupper 除外 (GH 41511)

  • 不允许将非关键字参数传递给 Series.bfill()Series.ffill()DataFrame.bfill()DataFrame.ffill() (GH 41508)

  • 不允许将非关键字参数传递给 DataFrame.replace()Series.replace(),但 to_replacevalue 除外 (GH 47587)

  • 不允许将非关键字参数传递给 DataFrame.sort_values(),但 by 除外 (GH 41505)

  • 不允许将非关键字参数传递给 Series.sort_values() (GH 41505)

  • 不允许将非关键字参数传递给 DataFrame.reindex(),但 labels 除外 (GH 17966)

  • 不允许使用非唯一 Index 对象调用 Index.reindex() (GH 42568)

  • 不允许使用标量 data 构造 Categorical (GH 38433)

  • 不允许在构造 CategoricalIndex 时不传递 data (GH 38944)

  • 移除了 Rolling.validate()Expanding.validate()ExponentialMovingWindow.validate() (GH 43665)

  • 移除了返回 "freq"Rolling.win_type (GH 38963)

  • 移除了 Rolling.is_datetimelike (GH 38963)

  • 移除了 DataFrameSeries 聚合中的 level 关键字;请改用 groupby (GH 39983)

  • 移除了已弃用的 Timedelta.delta()Timedelta.is_populated()Timedelta.freq (GH 46430, GH 46476)

  • 移除了已弃用的 NaT.freq (GH 45071)

  • 移除了已弃用的 Categorical.replace(),请改用 Series.replace() (GH 44929)

  • 移除了 Categorical.min()Categorical.max() 中的 numeric_only 关键字,改用 skipna (GH 48821)

  • 更改了 DataFrame.median()DataFrame.mean()numeric_only=None 时的行为,不再排除日期时间类型列(一旦强制执行 numeric_only=None 的弃用,此说明将不再相关)(GH 29941)

  • 移除了 is_extension_type(),改用 is_extension_array_dtype() (GH 29457)

  • 移除了 .ExponentialMovingWindow.vol (GH 39220)

  • 移除了 Index.get_value()Index.set_value() (GH 33907, GH 28621)

  • 移除了 Series.slice_shift()DataFrame.slice_shift() (GH 37601)

  • 移除了 DataFrameGroupBy.pad()DataFrameGroupBy.backfill() (GH 45076)

  • 移除了 read_json() 中的 numpy 参数 (GH 30636)

  • 不再允许在 DataFrame.to_dict() 中为 orient 传递缩写 (GH 32516)

  • 不再允许对非单调的 DatetimeIndex 进行部分切片时使用不在索引中的键。现在会引发 KeyError (GH 18531)

  • 移除了 get_offset,改用 to_offset() (GH 30340)

  • 移除了 infer_freq() 中的 warn 关键字 (GH 45947)

  • 移除了 DataFrame.between_time() 中的 include_startinclude_end 参数,改用 inclusive (GH 43248)

  • 移除了 date_range()bdate_range() 中的 closed 参数,改用 inclusive 参数 (GH 40245)

  • 移除了 DataFrame.expanding() 中的 center 关键字 (GH 20647)

  • 移除了 eval() 中的 truediv 关键字 (GH 29812)

  • 移除了 Index.get_loc() 中的 methodtolerance 参数。请改用 index.get_indexer([label], method=..., tolerance=...) (GH 42269)

  • 移除了 pandas.datetime 子模块 (GH 30489)

  • 移除了 pandas.np 子模块 (GH 30296)

  • 移除了 pandas.util.testing,改用 pandas.testing (GH 30745)

  • 移除了 Series.str.__iter__() (GH 28277)

  • 移除了 pandas.SparseArray,改用 arrays.SparseArray (GH 30642)

  • 移除了 pandas.SparseSeriespandas.SparseDataFrame,包括 pickle 支持 (GH 30642)

  • 强制禁止在 DataFrame.shift()Series.shift() 中对 datetime64, timedelta64 或 period 数据类型传递整数 fill_value (GH 32591)

  • 强制禁止在 DataFrame.ewm()times 参数中传递字符串列标签 (GH 43265)

  • 强制禁止在 Series.between()inclusive 参数中传递 TrueFalse,请改用 "both""neither" (GH 40628)

  • 强制禁止在 read_csv 中使用 engine="c" 时,usecols 参数使用越界索引 (GH 25623)

  • 强制禁止在 ExcelWriter 中使用 **kwargs;请改用关键字参数 engine_kwargs (GH 40430)

  • 强制禁止在 DataFrameGroupBy.__getitem__() 中传递列标签元组 (GH 30546)

  • 强制禁止使用标签序列对 MultiIndex 的某个级别进行索引时出现缺失标签。现在会引发 KeyError (GH 42351)

  • 强制禁止使用位置切片通过 .loc 设置值。请改用带标签的 .loc 或带位置的 .iloc (GH 31840)

  • 强制禁止使用 float 键进行位置索引,即使该键是整数,请手动将其转换为整数 (GH 34193)

  • 强制禁止使用 DataFrame 索引器与 .iloc 一起使用,请改用 .loc 进行自动对齐 (GH 39022)

  • 强制禁止在 __getitem____setitem__ 方法中使用 setdict 索引器 (GH 42825)

  • 强制禁止对 Index 或通过位置索引对 Series 进行索引以产生多维对象(例如 obj[:, None]),请改为在索引前转换为 numpy (GH 35141)

  • 强制禁止在 merge()suffixes 参数中使用 dictset 对象 (GH 34810)

  • 强制禁止 merge() 通过 suffixes 关键字和现有列产生重复列 (GH 22818)

  • 强制禁止在不同层级数上使用 merge()join() (GH 34862)

  • 强制禁止 DataFrame.melt() 中的 value_name 参数与 DataFrame 列中的元素名称相同 (GH 35003)

  • 强制禁止将 showindex 作为 **kwargs 传递给 DataFrame.to_markdown()Series.to_markdown(),请改用 index (GH 33091)

  • 移除了直接设置 Categorical._codes 的方式 (GH 41429)

  • 移除了直接设置 Categorical.categories 的方式 (GH 47834)

  • 移除了 Categorical.add_categories(), Categorical.remove_categories(), Categorical.set_categories(), Categorical.rename_categories(), Categorical.reorder_categories(), Categorical.set_ordered(), Categorical.as_ordered(), Categorical.as_unordered() 中的 inplace 参数 (GH 37981, GH 41118, GH 41133, GH 47834)

  • 强制使 Rolling.count()min_periods=None 时默认为窗口大小 (GH 31302)

  • DataFrame.to_parquet()DataFrame.to_stata()DataFrame.to_feather() 中的 fname 重命名为 path (GH 30338)

  • 强制禁止使用包含切片(例如 ser[[slice(0, 2)]])的单元素列表来索引 Series。请将列表转换为元组,或直接传递切片 (GH 31333)

  • 更改了在使用字符串索引器对带有 DatetimeIndex 索引的 DataFrame 进行索引时的行为,以前是按行进行切片,现在像其他任何列键一样操作;如需旧行为,请使用 frame.loc[key] (GH 36179)

  • 强制规定 display.max_colwidth 选项不接受负整数 (GH 31569)

  • 移除了 display.column_space 选项,改用 df.to_string(col_space=...) (GH 47280)

  • 移除了 pandas 类中已弃用的 mad 方法 (GH 11787)

  • 移除了 pandas 类中已弃用的 tshift 方法 (GH 11631)

  • 更改了空数据传递给 Series 时的行为;默认数据类型将是 object 而不是 float64 (GH 29405)

  • 更改了 DatetimeIndex.union()DatetimeIndex.intersection()DatetimeIndex.symmetric_difference() 处理时区不匹配的行为,现在会转换为 UTC 而不是转换为 object 数据类型 (GH 39328)

  • 更改了 to_datetime() 在参数为 “now” 且 utc=False 时的行为,使其与 Timestamp("now") 匹配 (GH 18705)

  • 更改了使用不感知时区的 datetime 对象对感知时区的 DatetimeIndex 进行索引,或反之亦然时的行为;现在它们的行为与其他任何不可比较的类型一样,会引发 KeyError (GH 36148)

  • 更改了 Index.reindex()Series.reindex()DataFrame.reindex() 在使用 `datetime64` 数据类型和 fill_valuedatetime.date 对象时的行为;它们不再被视为与 datetime.datetime 对象等效,因此重新索引会转换为 object 数据类型 (GH 39767)

  • 更改了 SparseArray.astype() 在给定数据类型并非显式 SparseDtype 时的行为,现在会转换为精确请求的数据类型,而不是静默地使用 SparseDtype (GH 34457)

  • 更改了 Index.ravel() 的行为,现在返回原始 Index 的视图,而不是 np.ndarray (GH 36900)

  • 更改了 Series.to_frame()Index.to_frame() 在显式指定 name=None 时的行为,现在列名使用 None,而不是索引名或默认的 0 (GH 45523)

  • 更改了 concat() 在连接一个 bool 数据类型数组和另一个整数数据类型数组时的行为,现在返回 object 数据类型而不是整数数据类型;如需旧行为,请在连接之前将 bool 对象显式转换为整数 (GH 45101)

  • 更改了 DataFrame 构造函数在给定浮点 data 和整数 dtype 时的行为,当数据无法无损转换时,保留浮点数据类型,这与 Series 的行为一致 (GH 41170)

  • 更改了 Index 构造函数在给定包含数值条目的 object 数据类型 np.ndarray 时的行为;现在保留 object 数据类型,而不是推断为数值数据类型,这与 Series 的行为一致 (GH 42870)

  • 更改了 Index.__and__()Index.__or__()Index.__xor__() 的行为,现在它们表现为逻辑运算(与 Series 行为一致),而不是集合操作的别名 (GH 37374)

  • 更改了 DataFrame 构造函数在传递第一个元素为 Categorical 的列表时的行为,现在将元素视为行并转换为 object 数据类型,这与其他类型的行为一致 (GH 38845)

  • 更改了 DataFrame 构造函数在传递数据无法转换为的 dtype(非 int 类型)时的行为;现在会引发错误,而不是静默忽略数据类型 (GH 41733)

  • 更改了 Series 构造函数的行为,它将不再从字符串条目推断出 datetime64 或 timedelta64 数据类型 (GH 41731)

  • 更改了 Timestamp 构造函数在给定 np.datetime64 对象并传递 tz 参数时的行为,现在将输入解释为本地时间(wall-time),而不是 UTC 时间 (GH 42288)

  • 更改了 Timestamp.utcfromtimestamp() 的行为,现在返回一个感知时区的对象,满足 Timestamp.utcfromtimestamp(val).timestamp() == val 的条件 (GH 45083)

  • 更改了 Index 构造函数在传递 SparseArraySparseDtype 时的行为,现在保留该数据类型,而不是转换为 numpy.ndarray (GH 43930)

  • 更改了对具有 DatetimeTZDtype 的对象执行 setitem-like 操作(__setitem__, fillna, where, mask, replace, insert,以及 shift 的 fill_value)时,当使用时区不匹配的值时,该值将被转换为对象的时区,而不是将两者都转换为 object 数据类型 (GH 44243)

  • 更改了 IndexSeriesDataFrame 构造函数在使用浮点数据类型和 DatetimeTZDtype 时的行为,现在将数据解释为 UTC 时间而不是本地时间(wall-times),这与整数数据类型的处理方式一致 (GH 45573)

  • 更改了 SeriesDataFrame 构造函数在整数 dtype 和包含 NaN 的浮点数据时的行为,现在会引发 IntCastingNaNError (GH 40110)

  • 更改了 SeriesDataFrame 构造函数在整数 dtype 和值过大无法无损转换为该 dtype 时的行为,现在会引发 ValueError (GH 41734)

  • 更改了 SeriesDataFrame 构造函数在整数 dtype 和值为 datetime64timedelta64 dtypes 时的行为,现在会引发 TypeError,请改用 values.view("int64") (GH 41770)

  • 移除了 pandas.DataFrame.resample()pandas.Series.resample()pandas.Grouper 中已废弃的 baseloffset 参数。请改用 offsetorigin (GH 31809)

  • 更改了 Series.fillna()DataFrame.fillna()timedelta64[ns] dtype 和不兼容的 fill_value 时的行为;现在会转换为 object dtype 而不是引发异常,与其他 dtypes 的行为一致 (GH 45746)

  • Series.str.replace()regex 的默认参数从 True 改为 False。此外,regex=True 时,单个字符的 pat 现在被视为正则表达式,而不是字符串字面量。(GH 36695, GH 24804)

  • 更改了 DataFrame.any()DataFrame.all()bool_only=True 时的行为;所有值均为布尔型的 object-dtype 列将不再包含在内,请先手动转换为 bool dtype (GH 46188)

  • 更改了 DataFrame.max(), DataFrame.min, DataFrame.mean, DataFrame.median, DataFrame.skew, DataFrame.kurtaxis=None 时的行为,现在返回一个标量,表示在两个轴上应用聚合 (GH 45072)

  • 更改了 Timestampdatetime.date 对象的比较行为;现在它们比较为不相等,并在不等比较时引发异常,与 datetime.datetime 的行为一致 (GH 36131)

  • 更改了 NaTdatetime.date 对象的比较行为;现在在不等比较时引发异常 (GH 39196)

  • 强制执行了对 Series.transformDataFrame.transform 在与列表或字典一起使用时,静默删除引发 TypeError 的列的废弃行为 (GH 43740)

  • 更改了 DataFrame.apply() 在使用类列表参数时的行为,现在任何部分失败都会引发错误 (GH 43740)

  • 更改了 DataFrame.to_latex() 的行为,现在通过 Styler.to_latex() 使用 Styler 实现 (GH 47970)

  • 更改了 Series.__setitem__() 在使用整数键和 Float64Index 且键不在索引中时的行为;之前我们将键视为位置(行为类似于 series.iloc[key] = val),现在我们将其视为标签(行为类似于 series.loc[key] = val),与 Series.__getitem__`() 的行为一致 (GH 33469)

  • 移除了 factorize()Index.factorize()ExtensionArray.factorize() 中的 na_sentinel 参数 (GH 47157)

  • 更改了 Series.diff()DataFrame.diff() 在 ExtensionDtype dtypes 且其数组未实现 diff 方法时的行为,现在会引发 TypeError 而不是转换为 numpy (GH 31025)

  • 强制执行了在 DataFrame 上调用 numpy “ufunc” 并使用 method="outer" 的废弃行为;现在会引发 NotImplementedError (GH 36955)

  • 强制执行了废弃行为,不允许在非数值 dtype 的 Series 聚合方法 (rank, any, all, …) 中传递 numeric_only=True (GH 47500)

  • 更改了 DataFrameGroupBy.apply()SeriesGroupBy.apply() 的行为,现在即使检测到是转换器,group_keys 参数也会被遵守 (GH 34998)

  • DataFrameSeries 在 DataFrame 列与 Series 索引不匹配时的比较行为改为引发 ValueError,而不是自动对齐。请在比较前执行 left, right = left.align(right, axis=1, copy=False) (GH 36795)

  • 强制执行了 DataFrame 聚合方法中 numeric_only=None (默认值) 的废弃行为,该行为会静默删除引发异常的列;numeric_only 现在默认为 False (GH 41480)

  • 将所有带有 numeric_only 参数的 DataFrame 方法中的该参数默认值更改为 False (GH 46096, GH 46906)

  • Series.rank()numeric_only 的默认值更改为 False (GH 47561)

  • 强制执行了在 groupby 和 resample 操作中当 numeric_only=False 时,静默删除无关列的废弃行为 (GH 41475)

  • 强制执行了在 RollingExpandingExponentialMovingWindow 操作中静默删除无关列的废弃行为。现在会引发 errors.DataError (GH 42834)

  • 更改了使用 df.loc[:, foo] = bardf.iloc[:, foo] = bar 设置值的行为,现在总是先尝试原地设置值,然后才退回到类型转换 (GH 45333)

  • 更改了各种 DataFrameGroupBy 方法中 numeric_only 的默认值;所有方法现在都默认为 numeric_only=False (GH 46072)

  • Resampler 方法中 numeric_only 的默认值更改为 False (GH 47177)

  • 使用 DataFrameGroupBy.transform() 方法且可调用对象返回 DataFrame 时,将与输入的索引对齐 (GH 47244)

  • 在向 DataFrame.groupby() 提供长度为一的列列表时,迭代生成的 DataFrameGroupBy 对象返回的键现在将是长度为一的元组 (GH 47761)

  • 移除了已废弃的方法 ExcelWriter.write_cells()ExcelWriter.save()ExcelWriter.cur_sheet()ExcelWriter.handles()ExcelWriter.path() (GH 45795)

  • ExcelWriter 的属性 book 不再可设置;但仍可访问和修改 (GH 48943)

  • 移除了 RollingExpandingExponentialMovingWindow 操作中未使用的 *args**kwargs (GH 47851)

  • 移除了 DataFrame.to_csv() 中已废弃的 line_terminator 参数 (GH 45302)

  • 移除了 lreshape() 中已废弃的 label 参数 (GH 30219)

  • DataFrame.eval()DataFrame.query()expr 参数之后的参数现在仅支持关键字参数 (GH 47587)

  • 移除了 Index._get_attributes_dict() (GH 50648)

  • 移除了 Series.__array_wrap__() (GH 50648)

  • 更改了 DataFrame.value_counts() 的行为,对于任何类列表参数(无论是否包含一个元素),返回一个带有 MultiIndexSeries,但对于单个标签,返回一个 Index (GH 50829)

性能改进#

Bug 修复#

Categorical (分类类型)#

日期/时间类型#

时间差#

  • to_timedelta() 中存在的 Bug:当输入具有可空数据类型 Float64 时引发错误 (GH 48796)

  • Timedelta 构造函数中存在的 Bug:在给定 np.timedelta64("nat") 时错误地引发异常,而非返回 NaT (GH 48898)

  • Timedelta 构造函数中存在的 Bug:在同时传入一个 Timedelta 对象和关键字参数(例如 days, seconds)时未能引发异常 (GH 48898)

  • Timedelta 比较中存在的 Bug:与非常大的 datetime.timedelta 对象进行比较时错误地引发 OutOfBoundsTimedelta 异常 (GH 49021)

时区#

  • Series.astype()DataFrame.astype() 中存在的 Bug:当 object 数据类型包含多个时区感知 datetime 对象(具有异构时区)并转换为 DatetimeTZDtype 时错误地引发异常 (GH 32581)

  • to_datetime() 中存在的 Bug:当 format 被指定为 %Z 时,未能解析带有有时区名称的日期字符串 (GH 49748)

  • 改进了在向 Timestamp.tz_localize() 方法的 ambiguous 参数传递无效值时的错误消息 (GH 49565)

  • 字符串解析中的 Bug:错误地允许创建带有无效时区的 Timestamp 对象,这在尝试打印时会引发异常 (GH 50668)

  • 修正了 objects_to_datetime64ns() 中的 TypeError 消息,以告知 DatetimeIndex 包含混合时区 (GH 50974)

数值#

  • DataFrame.add() 中存在的 Bug:当输入包含混合的 DataFrame 类型和 Series 类型时无法应用 ufunc (GH 39853)

  • 在对 Series 进行算术运算时存在的 Bug:当组合掩码数据类型和 numpy 数据类型时未传播掩码 (GH 45810, GH 42630)

  • DataFrame.sem()Series.sem() 中存在的 Bug:当使用由 ArrowDtype 支持的数据时总是会引发一个错误的 TypeError 异常 (GH 49759)

  • Series.__add__() 中存在的 Bug:在转换为 object 时,对于列表和掩码的 Series 会发生 (GH 22962)

  • mode() 中存在的 Bug:当存在 NA 值时,未遵守 dropna=False 参数 (GH 50982)

  • DataFrame.query() 中存在的 Bug:当 engine="numexpr" 且列名为 minmax 时会引发 TypeError 异常 (GH 50937)

  • DataFrame.min()DataFrame.max() 中存在的 Bug:当使用包含 pd.NaTaxis=1 的时区感知数据时,会返回不正确的结果 (GH 51242)

转换#

  • 构建 Series 对象时存在的 Bug:使用字符串列表和 int64 数据类型会引发异常而不是进行类型转换 (GH 44923)

  • 构建 Series 对象时存在的 Bug:使用掩码数据类型和包含 NA 的布尔值会引发异常 (GH 42137)

  • DataFrame.eval() 中存在的 Bug:当函数调用中存在负值时错误地引发一个 AttributeError 异常 (GH 46471)

  • Series.convert_dtypes() 中存在的 Bug:在将 Series 包含 NA 且数据类型为 object 时,未将数据类型转换为可空数据类型 (GH 48791)

  • 一个 Bug 导致任何 ExtensionDtype 子类,当其 kind="M" 时,会被解释为时区类型 (GH 34986)

  • arrays.ArrowExtensionArray 中存在的 Bug:当向其传递字符串或二进制序列时会引发 NotImplementedError 异常 (GH 49172)

  • Series.astype() 中存在的 Bug:当从非 pyarrow 字符串数据类型转换为 pyarrow 数字类型时引发 pyarrow.ArrowInvalid 异常 (GH 50430)

  • DataFrame.astype() 中存在的 Bug:在转换为 stringcopy=False 时,修改了输入数组的原地 (GH 51073)

  • Series.to_numpy() 中存在的 Bug:在应用 na_value 之前转换为 NumPy 数组 (GH 48951)

  • DataFrame.astype() 中存在的 Bug:在转换为 pyarrow 数据类型时未复制数据 (GH 50984)

  • to_datetime() 中存在的 Bug:当 format 参数是 ISO8601 格式时,未遵守 exact 参数 (GH 12649)

  • TimedeltaArray.astype() 中存在的 Bug:在转换为 pyarrow duration 类型时引发 TypeError 异常 (GH 49795)

  • DataFrame.eval()DataFrame.query() 中存在的 Bug:在使用扩展数组数据类型时引发异常 (GH 29618, GH 50261, GH 31913)

  • Series() 中存在的 Bug:从 Index 创建时,当 dtype 等于来自 Indexdtype 时未复制数据 (GH 52008)

字符串#

  • pandas.api.types.is_string_dtype() 中存在的 Bug:当用于 StringDtype 或带有 pyarrow.string()ArrowDtype 时不会返回 True (GH 15585)

  • 将字符串数据类型转换为 “datetime64[ns]” 或 “timedelta64[ns]” 时存在的 Bug:错误地引发 TypeError 异常 (GH 36153)

  • 设置字符串数据类型列的值时存在的 Bug:当输入数组包含缺失值时,会意外地修改该数组作为副作用 (GH 51299)

区间#

索引#

  • DataFrame.__setitem__() 中存在的 Bug:当索引器是一个数据类型为 booleanDataFrame 时引发异常 (GH 47125)

  • DataFrame.reindex() 中存在的 Bug:在对 columnsindex 使用 uint 数据类型进行索引时填充了错误的值 (GH 48184)

  • DataFrame.loc() 中存在的 Bug:在设置数据类型不同的 DataFrame 时,将值强制转换为单一数据类型 (GH 50467)

  • DataFrame.sort_values() 中存在的 Bug:当 by 参数为空列表且 inplace=True 时,未返回 None (GH 50643)

  • DataFrame.loc() 中存在的 Bug:在使用列表索引器设置值时强制转换数据类型 (GH 49159)

  • Series.loc() 中存在的 Bug:对切片索引器(slice indexer)使用越界结束位置时引发错误 (GH 50161)

  • DataFrame.loc() 中存在的 Bug:在使用全为 Falsebool 索引器和空对象时引发 ValueError 异常 (GH 51450)

  • DataFrame.loc() 中存在的 Bug:在使用 bool 索引器和 MultiIndex 时引发 ValueError 异常 (GH 47687)

  • DataFrame.loc() 中存在的 Bug:在对由 pyarrow 支持的列使用非标量索引器设置值时引发 IndexError 异常 (GH 50085)

  • DataFrame.__getitem__(), Series.__getitem__(), DataFrame.__setitem__()Series.__setitem__() 中存在的 Bug:在对使用扩展浮点数据类型(Float64 & Float64)或使用整数进行复杂数据类型索引的索引进行操作时 (GH 51053)

  • DataFrame.loc() 中存在的 Bug:在使用空索引器设置不兼容值时修改对象 (GH 45981)

  • DataFrame.__setitem__() 中存在的 Bug:当右侧是一个带有 MultiIndex 列的 DataFrame 时引发 ValueError 异常 (GH 49121)

  • DataFrame.reindex() 中存在的 Bug:在将 DataFrame 对象具有单个扩展数组列,并且在重新索引 columnsindex 时,将数据类型强制转换为 object (GH 48190)

  • DataFrame.iloc() 中存在的 Bug:当索引器是一个带有数值扩展数组数据类型的 Series 时引发 IndexError 异常 (GH 49521)

  • describe() 中存在的 Bug:在格式化结果索引中的百分位数时显示了超出所需的精度 (GH 46362)

  • DataFrame.compare() 中存在的 Bug:在比较 NA 与可空数据类型中的值时,无法识别差异 (GH 48939)

  • Series.rename() 中存在的 Bug:在使用 MultiIndex 时丢失扩展数组数据类型 (GH 21055)

  • DataFrame.isetitem() 中存在的 Bug:强制转换 DataFrame 中的扩展数组数据类型为 object (GH 49922)

  • Series.__getitem__() 中存在的 Bug:从由空的 pyarrow 支持的对象中进行选择时返回损坏的对象 (GH 51734)

  • BusinessHour 中存在的 Bug:当索引中未包含开放时间时,会导致 DatetimeIndex 的创建失败 (GH 49835)

缺失值#

  • Index.equals() 中存在的 Bug:当 Index 包含含有 NA 的元组时引发 TypeError 异常 (GH 48446)

  • Series.map() 中存在的 Bug:当数据包含 NaNs 且使用了 defaultdict 映射时导致结果不正确 (GH 48813)

  • NA 中存在的 Bug:当与一个 bytes 对象执行二元运算时,引发 TypeError 异常而非返回 NA (GH 49108)

  • DataFrame.update() 中存在的 Bug:当使用 overwrite=Falseself 包含含有 NaT 值的列,且该列在 other 中不存在时引发 TypeError 异常 (GH 16713)

  • 修复了 Series.replace() 在替换包含 NA 的 object-dtype Series 中的值时引发 RecursionError 的问题 (GH 47480)

  • 修复了 Series.replace() 在替换包含 NA 的 numeric Series 中的值时引发 RecursionError 的问题 (GH 50758)

MultiIndex#

I/O#

Period#

  • 修复了 Period.strftime()PeriodIndex.strftime() 在传递 locale 特定的指令时引发 UnicodeDecodeError 的问题 (GH 46319)

  • 修复了将 Period 对象添加到 DateOffset 对象数组时错误地引发 TypeError 的问题 (GH 50162)

  • 修复了 Period 在传入精度高于纳秒的字符串时会引发 KeyError 而非丢弃多余精度的问题 (GH 50417)

  • 修复了解析表示周期的字符串(例如 “2017-01-23/2017-01-29”)时,会解析为分钟频率而非周频率的问题 (GH 50803)

  • 修复了 DataFrameGroupBy.sum()DataFrameGroupByGroupBy.cumsum()DataFrameGroupByGroupBy.prod()DataFrameGroupByGroupBy.cumprod() 在使用 PeriodDtype 时未引发 TypeError 的问题 (GH 51040)

  • 修复了使用 Period 解析空字符串时,错误地引发 ValueError 而非返回 NaT 的问题 (GH 51349)

绘图#

  • 修复了 DataFrame.plot.hist() 未丢弃 weights 中对应于 NaN 值元素的问题 (GH 48884)

  • ax.set_xlim 有时会引发 UserWarning,由于 set_xlim 不接受解析参数,用户无法解决 - 转换器现在改为使用 Timestamp() (GH 49148)

分组/重采样/滚动窗口#

重塑#

稀疏#

扩展数组#

样式器#

元数据#

其他#

贡献者#

共有 260 人为本次版本贡献了补丁。名字旁带有 "+" 的是首次贡献者。

  • 5j9 +

  • ABCPAN-rank +

  • Aarni Koskela +

  • Aashish KC +

  • Abubeker Mohammed +

  • Adam Mróz +

  • Adam Ormondroyd +

  • Aditya Anulekh +

  • Ahmed Ibrahim

  • Akshay Babbar +

  • Aleksa Radojicic +

  • Alex +

  • Alex Buzenet +

  • Alex Kirko

  • Allison Kwan +

  • Amay Patel +

  • Ambuj Pawar +

  • Amotz +

  • Andreas Schwab +

  • Andrew Chen +

  • Anton Shevtsov

  • Antonio Ossa Guerra +

  • Antonio Ossa-Guerra +

  • Anushka Bishnoi +

  • Arda Kosar

  • Armin Berres

  • Asadullah Naeem +

  • Asish Mahapatra

  • Bailey Lissington +

  • BarkotBeyene

  • Ben Beasley

  • Bhavesh Rajendra Patil +

  • Bibek Jha +

  • Bill +

  • Bishwas +

  • CarlosGDCJ +

  • Carlotta Fabian +

  • Chris Roth +

  • Chuck Cadman +

  • Corralien +

  • DG +

  • Dan Hendry +

  • Daniel Isaac

  • David Kleindienst +

  • David Poznik +

  • David Rudel +

  • DavidKleindienst +

  • Dea María Léon +

  • Deepak Sirohiwal +

  • Dennis Chukwunta

  • Douglas Lohmann +

  • Dries Schaumont

  • Dustin K +

  • Edoardo Abati +

  • Eduardo Chaves +

  • Ege Özgüroğlu +

  • Ekaterina Borovikova +

  • Eli Schwartz +

  • Elvis Lim +

  • Emily Taylor +

  • Emma Carballal Haire +

  • Erik Welch +

  • Fangchen Li

  • Florian Hofstetter +

  • Flynn Owen +

  • Fredrik Erlandsson +

  • Gaurav Sheni

  • Georeth Chow +

  • George Munyoro +

  • Guilherme Beltramini

  • Gulnur Baimukhambetova +

  • H L +

  • Hans

  • Hatim Zahid +

  • HighYoda +

  • Hiki +

  • Himanshu Wagh +

  • Hugo van Kemenade +

  • Idil Ismiguzel +

  • Irv Lustig

  • Isaac Chung

  • Isaac Virshup

  • JHM Darbyshire

  • JHM Darbyshire (iMac)

  • JMBurley

  • Jaime Di Cristina

  • Jan Koch

  • JanVHII +

  • Janosh Riebesell

  • JasmandeepKaur +

  • Jeremy Tuloup

  • Jessica M +

  • Jonas Haag

  • Joris Van den Bossche

  • João Meirelles +

  • Julia Aoun +

  • Justus Magin +

  • Kang Su Min +

  • Kevin Sheppard

  • Khor Chean Wei

  • Kian Eliasi

  • Kostya Farber +

  • KotlinIsland +

  • Lakmal Pinnaduwage +

  • Lakshya A Agrawal +

  • Lawrence Mitchell +

  • Levi Ob +

  • Loic Diridollou

  • Lorenzo Vainigli +

  • Luca Pizzini +

  • Lucas Damo +

  • Luke Manley

  • Madhuri Patil +

  • Marc Garcia

  • Marco Edward Gorelli

  • Marco Gorelli

  • MarcoGorelli

  • Maren Westermann +

  • Maria Stazherova +

  • Marie K +

  • Marielle +

  • Mark Harfouche +

  • Marko Pacak +

  • Martin +

  • Matheus Cerqueira +

  • Matheus Pedroni +

  • Matteo Raso +

  • Matthew Roeschke

  • MeeseeksMachine +

  • Mehdi Mohammadi +

  • Michael Harris +

  • Michael Mior +

  • Natalia Mokeeva +

  • Neal Muppidi +

  • Nick Crews

  • Nishu Choudhary +

  • Noa Tamir

  • Noritada Kobayashi

  • Omkar Yadav +

  • P. Talley +

  • Pablo +

  • Pandas Development Team

  • Parfait Gasana

  • Patrick Hoefler

  • Pedro Nacht +

  • Philip +

  • Pietro Battiston

  • Pooja Subramaniam +

  • Pranav Saibhushan Ravuri +

  • Pranav. P. A +

  • Ralf Gommers +

  • RaphSku +

  • Richard Shadrach

  • Robsdedude +

  • Roger

  • Roger Thomas

  • RogerThomas +

  • SFuller4 +

  • Salahuddin +

  • Sam Rao

  • Sean Patrick Malloy +

  • Sebastian Roll +

  • Shantanu

  • Shashwat +

  • Shashwat Agrawal +

  • Shiko Wamwea +

  • Shoham Debnath

  • Shubhankar Lohani +

  • Siddhartha Gandhi +

  • Simon Hawkins

  • Soumik Dutta +

  • Sowrov Talukder +

  • Stefanie Molin

  • Stefanie Senger +

  • Stepfen Shawn +

  • Steven Rotondo

  • Stijn Van Hoey

  • Sudhansu +

  • Sven

  • Sylvain MARIE

  • Sylvain Marié

  • Tabea Kossen +

  • Taylor Packard

  • Terji Petersen

  • Thierry Moisan

  • Thomas H +

  • Thomas Li

  • Torsten Wörtwein

  • Tsvika S +

  • Tsvika Shapira +

  • Vamsi Verma +

  • Vinicius Akira +

  • William Andrea

  • William Ayd

  • William Blum +

  • Wilson Xing +

  • Xiao Yuan +

  • Xnot +

  • Yasin Tatar +

  • Yuanhao Geng

  • Yvan Cywan +

  • Zachary Moon +

  • Zhengbo Wang +

  • abonte +

  • adrienpacifico +

  • alm

  • amotzop +

  • andyjessen +

  • anonmouse1 +

  • bang128 +

  • bishwas jha +

  • calhockemeyer +

  • carla-alves-24 +

  • carlotta +

  • casadipietra +

  • catmar22 +

  • cfabian +

  • codamuse +

  • dataxerik

  • davidleon123 +

  • dependabot[bot] +

  • fdrocha +

  • github-actions[bot]

  • himanshu_wagh +

  • iofall +

  • jakirkham +

  • jbrockmendel

  • jnclt +

  • joelchen +

  • joelsonoda +

  • joshuabello2550

  • joycewamwea +

  • kathleenhang +

  • krasch +

  • ltoniazzi +

  • luke396 +

  • milosz-martynow +

  • minat-hub +

  • mliu08 +

  • monosans +

  • nealxm

  • nikitaved +

  • paradox-lab +

  • partev

  • raisadz +

  • ram vikram singh +

  • rebecca-palmer

  • sarvaSanjay +

  • seljaks +

  • silviaovo +

  • smij720 +

  • soumilbaldota +

  • stellalin7 +

  • strawberry beach sandals +

  • tmoschou +

  • uzzell +

  • yqyqyq-W +

  • yun +

  • Ádám Lippai

  • 김동현 (Daniel Donghyun Kim) +