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)。
以前,只能使用 int64
、uint64
和 float64
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")
Int64Index
、UInt64Index
和 Float64Index
在 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 位索引。
以下是可能不完全的变更列表
现在使用 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,这与以前相同。DatetimeIndex
的各种数字日期时间属性(day
、month
、year
等)以前是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')
来自
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
无法使用 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)。当使用
Series
或Index
构造DataFrame
并指定copy=False
时,DataFrame
构造函数现在将遵守写时复制规则。DataFrame
和Series
构造函数在从 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):
...
其他增强功能#
当将
ArrowDtype
与pyarrow.string
类型一起使用时,添加了对str
访问器方法的支持 (GH 50325)。当将
ArrowDtype
与pyarrow.timestamp
类型一起使用时,添加了对dt
访问器方法的支持 (GH 50954)。read_sas()
现在支持使用encoding='infer'
来正确读取和使用 sas 文件指定的编码 (GH 48048)。DataFrameGroupBy.quantile()
,SeriesGroupBy.quantile()
和DataFrameGroupBy.std()
现在保留可空 dtype,而不是转换为 numpy dtype (GH 37493)。DataFrameGroupBy.std()
,SeriesGroupBy.std()
现在支持 datetime64、timedelta64 和DatetimeTZDtype
dtype (GH 48481)。Series.add_suffix()
、DataFrame.add_suffix()
、Series.add_prefix()
和DataFrame.add_prefix()
支持axis
参数。如果设置了axis
,则可以覆盖默认考虑哪个轴的行为 (GH 47819)。testing.assert_frame_equal()
现在显示 DataFrames 不同步的第一个元素,类似于pytest
的输出 (GH 47910)。向
DataFrame.to_dict()
添加了index
参数 (GH 46398)。通过
_accumulate
为ExtensionArray
接口添加了cumsum
、cumprod
、cummin
和cummax
方法 (GH 28385)。CategoricalConversionWarning
、InvalidComparison
、InvalidVersion
、LossySetitemError
和NoBufferPresent
现在在pandas.errors
中暴露 (GH 27656)。通过添加缺失的测试包
pytest-asyncio
修复了test
optional_extra (GH 48361)。当类型转换不可行时,改进了
DataFrame.astype()
抛出的异常消息,使其包含列名 (GH 47571)。date_range()
现在支持unit
关键字(“s”、“ms”、“us” 或 “ns”),用于指定输出索引所需的精度 (GH 49106)。timedelta_range()
现在支持unit
关键字(“s”、“ms”、“us” 或 “ns”),用于指定输出索引所需的精度 (GH 49824)。DataFrame.to_json()
现在支持mode
关键字,支持的输入为 'w' 和 'a'。默认为 'w',当 lines=True 和 orient='records' 时可以使用 'a' 将记录导向的 json 行追加到现有的 json 文件中 (GH 35849)。为
IntervalIndex.from_breaks()
、IntervalIndex.from_arrays()
和IntervalIndex.from_tuples()
添加了name
参数 (GH 48911)改进了在
DataFrame
上使用testing.assert_frame_equal()
时的异常消息,使其包含被比较的列 (GH 50323)改进了
merge_asof()
在连接列重复时的错误消息 (GH 50102)为
get_dummies()
添加了对扩展数组 dtype 的支持 (GH 32430)添加了
Index.infer_objects()
,类似于Series.infer_objects()
(GH 50034)为
Series.infer_objects()
和DataFrame.infer_objects()
添加了copy
参数,传递False
将避免对已非对象类型或无法推断出更好 dtype 的 Series 或列进行复制 (GH 50096)DataFrame.plot.hist()
现在识别xlabel
和ylabel
参数 (GH 49793)Series.drop_duplicates()
增加了ignore_index
关键字来重置索引 (GH 48304)Series.dropna()
和DataFrame.dropna()
增加了ignore_index
关键字来重置索引 (GH 31725)改进了
to_datetime()
处理非 ISO8601 格式时的错误消息,向用户告知第一个错误的位置 (GH 50361)改进了尝试对齐
DataFrame
对象(例如,在DataFrame.compare()
中)时的错误消息,澄清“标签完全相同”是指索引和列都相同 (GH 50083)为 pyarrow 字符串 dtype 添加了对
Index.min()
和Index.max()
的支持 (GH 51397)添加了
DatetimeIndex.as_unit()
和TimedeltaIndex.as_unit()
用于转换为不同的分辨率;支持的分辨率包括 “s”, “ms”, “us”, 和 “ns” (GH 50616)添加了
Series.dt.unit()
和Series.dt.as_unit()
用于转换为不同的分辨率;支持的分辨率包括 “s”, “ms”, “us”, 和 “ns” (GH 51223)为
read_sql()
添加了新参数dtype
,使其与read_sql_query()
保持一致 (GH 50797)read_csv()
、read_table()
、read_fwf()
和read_excel()
现在接受date_format
参数 (GH 50601)to_datetime()
现在接受"ISO8601"
作为format
参数的值,这将匹配任何 ISO8601 字符串(但格式可能不完全相同)(GH 50411)to_datetime()
现在接受"mixed"
作为format
参数的值,这将单独推断每个元素的格式 (GH 50972)为
read_json()
添加了新参数engine
,通过指定engine="pyarrow"
来支持使用 pyarrow 解析 JSON (GH 48893)添加了对 SQLAlchemy 2.0 的支持 (GH 40686)
在
read_csv()
中当engine="pyarrow"
时,添加了对decimal
参数的支持 (GH 51302)Index
的集合运算Index.union()
、Index.intersection()
、Index.difference()
和Index.symmetric_difference()
现在支持sort=True
,这将始终返回排序结果,与默认的sort=None
不同(在某些情况下不排序)(GH 25151)添加了新的转义模式 “latex-math”,以避免在格式化器中转义 “$” (GH 50040)
重要 Bug 修复#
这些 bug 修复可能会带来显著的行为改变。
DataFrameGroupBy.cumsum()
和 DataFrameGroupBy.cumprod()
现在会溢出,而不是有损地转换为浮点数#
在之前的版本中,应用 cumsum
和 cumprod
时会转换为浮点数,这即使结果可以由 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 进行构造#
在过去的版本中,当构造一个 Series
或 DataFrame
并传入不支持分辨率(即除 “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#
在之前的版本中,将 Series
或 DataFrame
从 datetime64[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
#
之前,构造一个空的(其中 data
是 None
或空的类列表参数)Series
或 DataFrame
且不指定轴 (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.multicolumn
、display.latex.multicolumn_format
和display.latex.multirow
:替换为styler.sparse.rows
、styler.sparse.columns
、styler.latex.multirow_align
和styler.latex.multicol_align
,display.latex.repr
:替换为styler.render.repr
,display.max_rows
和display.max_columns
:替换为styler.render.max_rows
、styler.render.max_columns
和styler.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 |
更多信息请参见 Dependencies 和 Optional 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
构造函数中的freq
、tz
、nanosecond
和unit
关键字现在仅为关键字参数 (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()
对于datetime64
、timedelta64
或PeriodDtype
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 的数据传递给
TimedeltaIndex
、Series
或DataFrame
构造函数时,现在将保留该 dtype 而不是强制转换为 “timedelta64[ns]”;分辨率较低的 timedelta64 数据将被强制转换为最低支持的分辨率 “timedelta64[s]” (GH 49014)将
dtype
“timedelta64[s]”、“timedelta64[ms]”或“timedelta64[us]”传递给TimedeltaIndex
、Series
或DataFrame
构造函数时,现在会保留该 dtype,而不是将其转换为“timedelta64[ns]”;对于Series
或DataFrame
传递较低分辨率的 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]”)传递给
DataFrame
、Series
或Index
时,会将被视为 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
时是相等的。之前它指的是RangeIndex
或Int64Index
(GH 51098)dtype 为“timedelta64[ns]”或“datetime64[ns]”的
Series.unique()
现在返回TimedeltaArray
或DatetimeArray
,而不是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]"
的Series
或DataFrame
时,现在会引发错误,而不是静默忽略该关键字并返回object
dtype (GH 24435)将包含无法转换为
Timedelta
的类型的序列传递给to_timedelta()
,或传递给 dtype 为"timedelta64[ns]"
的Series
或DataFrame
构造函数,或传递给TimedeltaIndex
时,现在会引发TypeError
,而不是ValueError
(GH 49525)改变了
Index
构造函数的行为,当序列中至少包含一个NaT
且其他所有元素都是None
或NaN
时,会推断出datetime64[ns]
dtype,而不是object
dtype,与Series
的行为一致 (GH 49340)参数
index_col
设置为None
(默认值)的read_stata()
现在会将返回的DataFrame
的索引设置为RangeIndex
,而不是Int64Index
(GH 49745)改变了
Index
、Series
和DataFrame
在处理 object-dtypes 时的算术方法行为,结果不再对数组操作的结果进行类型推断,请使用result.infer_objects(copy=False)
对结果进行类型推断以获得旧行为 (GH 49999, GH 49714)改变了
Index
构造函数的行为,当输入是包含全bool
值或全复数值的 object-dtypenumpy.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)改变了
Series
和DataFrame
构造函数的行为,当给定整数 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 为object
的Index
(GH 49572)DataFrame.values()
、DataFrame.to_numpy()
、DataFrame.xs()
、DataFrame.reindex()
、DataFrame.fillna()
和DataFrame.replace()
不再静默地合并底层数组;执行df = df.copy()
来确保合并 (GH 49356)使用
loc
或iloc
在两个轴上进行完全切片(即df.loc[:, :]
或df.iloc[:, :]
)创建新的 DataFrame 时,现在会返回一个新的 DataFrame(浅拷贝),而不是原始 DataFrame,与获取完全切片的其他方法(例如df.loc[:]
或df[:]
)一致 (GH 49469)当分别传递 Series 和 DataFrame 并且使用默认值
copy=False
(且没有其他关键字触发拷贝)时,Series
和DataFrame
构造函数现在会返回一个浅拷贝(即共享数据,但不共享属性)。之前,新的 Series 或 DataFrame 会共享 index 属性(例如,df.index = ...
也会更新父对象或子对象的 index) (GH 49523)从不带索引的
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
的索引级别现在总是具有 dtypeint32
。之前它们具有 dtypeint64
(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 列的
DataFrame
和DataFrameGroupBy
聚合(例如“sum”)不再推断结果的非 object dtypes,请在结果上显式调用result.infer_objects(copy=False)
以获得旧行为 (GH 51205, GH 49603)ArrowDtype
dtypes 的零除操作现在根据分子返回-inf
、nan
或inf
,而不是引发错误 (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 中除一小部分方法以外的所有方法的 inplace
和 copy
关键字。当前的讨论位于 此处。在 Copy-on-Write 的背景下,这些关键字将不再需要。如果该提议被接受,这两个关键字将在 pandas 的下一个版本中被弃用,并在 pandas 3.0 中移除。
弃用#
弃用将带有系统本地时区的 datetime 字符串解析为
tzlocal
的行为,请传递tz
关键字或显式调用tz_localize
(GH 50791)弃用
to_datetime()
和read_csv()
中的参数infer_datetime_format
,因为它的严格版本现在是默认行为 (GH 48621)弃用
to_datetime()
在解析字符串时使用unit
的行为,在未来的版本中,这些字符串将被解析为 datetime(与不带 unit 参数的行为一致),而不是转换为 float。要保留旧行为,请在调用to_datetime()
之前将字符串转换为数值类型 (GH 50735)弃用
pandas.io.sql.execute()
(GH 50185)Index.is_boolean()
已被弃用。请改用pandas.api.types.is_bool_dtype()
(GH 50042)Index.is_integer()
已被弃用。请改用pandas.api.types.is_integer_dtype()
(GH 50042)Index.is_floating()
已被弃用。请改用pandas.api.types.is_float_dtype()
(GH 50042)Index.holds_integer()
已被弃用。请改用pandas.api.types.infer_dtype()
(GH 50243)Index.is_numeric()
已被弃用。请改用pandas.api.types.is_any_real_numeric_dtype()
(GH 50042,:issue:51152)Index.is_categorical()
已被弃用。请改用pandas.api.types.is_categorical_dtype()
(GH 50042)Index.is_object()
已被弃用。请改用pandas.api.types.is_object_dtype()
(GH 50042)Index.is_interval()
已被弃用。请改用pandas.api.types.is_interval_dtype()
(GH 50042)参数
date_parser
在read_csv()
,read_table()
,read_fwf()
, 和read_excel()
中已被弃用,请改用date_format
(GH 50601)将
all
和any
归约 (reductions) 用于datetime64
和DatetimeTZDtype
dtype 的方法已被弃用,请改用例如(obj != pd.Timestamp(0), tz=obj.tz).all()
(GH 34479)已弃用
Resampler
中未使用的参数*args
和**kwargs
(GH 50977)已弃用对单元素
Series
调用float
或int
来分别返回float
或int
的方法。请改为在调用float
或int
之前提取元素 (GH 51101)已弃用
Grouper.groups()
,请改用Groupby.groups()
(GH 51182)已弃用
Grouper.grouper()
,请改用Groupby.grouper()
(GH 51182)已弃用
Grouper.obj()
,请改用Groupby.obj()
(GH 51206)已弃用
Grouper.indexer()
,请改用Resampler.indexer()
(GH 51206)已弃用
Grouper.ax()
,请改用Resampler.ax()
(GH 51206)已弃用
read_parquet()
中的关键字use_nullable_dtypes
,请改用dtype_backend
(GH 51853)已弃用
Series.pad()
,请改用Series.ffill()
(GH 33396)已弃用
Series.backfill()
,请改用Series.bfill()
(GH 33396)已弃用
DataFrame.pad()
,请改用DataFrame.ffill()
(GH 33396)已弃用
DataFrame.backfill()
,请改用DataFrame.bfill()
(GH 33396)已弃用
close()
。请改用StataReader
作为上下文管理器 (context manager) (GH 49228)已弃用在迭代
DataFrameGroupBy
或通过长度为 1 的列表作为level
参数进行分组的SeriesGroupBy
时生成标量。现在将返回长度为 1 的元组 (GH 51583)
移除之前版本的弃用/更改#
已移除
Int64Index
,UInt64Index
和Float64Index
。更多信息请参见 此处 (GH 42717)已移除
Timestamp.freq
,Timestamp.freqstr
以及Timestamp
构造函数和Timestamp.fromordinal()
中的弃用参数freq
(GH 14146)已移除弃用的
CategoricalBlock
,Block.is_categorical()
,要求在传递给Block.make_block_same_class()
之前将 datetime64 和 timedelta64 值包装在DatetimeArray
或TimedeltaArray
中,要求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
,DatetimeIndex
和dt
访问器中的weekofyear
和week
属性,请改用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)已强制执行的弃用禁止将时区感知
Timestamp
和dtype="datetime64[ns]"
传递给Series
或DataFrame
构造函数 (GH 41555)已强制执行的弃用禁止将时区感知值序列和
dtype="datetime64[ns]"
传递给Series
或DataFrame
构造函数 (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)已强制执行的弃用禁止使用
.astype
将datetime64[ns]
Series
,DataFrame
, 或DatetimeIndex
转换为时区感知 dtype,请改用obj.tz_localize
或ser.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)已移除日期解析函数
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()
中的参数names
和dtype
,并移除MultiIndex.copy()
中的levels
和codes
(GH 35853, GH 36685)已移除
MultiIndex.set_levels()
和MultiIndex.set_codes()
中的参数inplace
(GH 35626)已移除
DataFrame.to_excel()
和Series.to_excel()
中的参数verbose
和encoding
(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)参数
prefix
、squeeze
、error_bad_lines
和warn_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)关键字
convert_float
和mangle_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()
,但io
和sheet_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)不允许将非关键字参数传递给
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()
,但cond
和other
除外 (GH 41580)不允许将非关键字参数传递给
DataFrame.to_stata()
,但path
除外 (GH 48128)不允许将非关键字参数传递给
DataFrame.where()
和Series.where()
,但cond
和other
除外 (GH 41523)不允许将非关键字参数传递给
Series.set_axis()
和DataFrame.set_axis()
,但labels
除外 (GH 41491)不允许将非关键字参数传递给
Series.rename_axis()
和DataFrame.rename_axis()
,但mapper
除外 (GH 47587)不允许将非关键字参数传递给
Series.clip()
和DataFrame.clip()
,但lower
和upper
除外 (GH 41511)不允许将非关键字参数传递给
Series.bfill()
、Series.ffill()
、DataFrame.bfill()
和DataFrame.ffill()
(GH 41508)不允许将非关键字参数传递给
DataFrame.replace()
和Series.replace()
,但to_replace
和value
除外 (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)移除了
DataFrame
和Series
聚合中的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_start
和include_end
参数,改用inclusive
(GH 43248)移除了
date_range()
和bdate_range()
中的closed
参数,改用inclusive
参数 (GH 40245)移除了
DataFrame.expanding()
中的center
关键字 (GH 20647)移除了
Index.get_loc()
中的method
和tolerance
参数。请改用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.SparseSeries
和pandas.SparseDataFrame
,包括 pickle 支持 (GH 30642)强制禁止在
DataFrame.shift()
和Series.shift()
中对 datetime64, timedelta64 或 period 数据类型传递整数fill_value
(GH 32591)强制禁止在
DataFrame.ewm()
的times
参数中传递字符串列标签 (GH 43265)强制禁止在
Series.between()
的inclusive
参数中传递True
和False
,请改用"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)强制禁止在
__getitem__
和__setitem__
方法中使用set
或dict
索引器 (GH 42825)强制禁止对
Index
或通过位置索引对Series
进行索引以产生多维对象(例如obj[:, None]
),请改为在索引前转换为 numpy (GH 35141)强制禁止
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_value
为datetime.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
构造函数在传递SparseArray
或SparseDtype
时的行为,现在保留该数据类型,而不是转换为numpy.ndarray
(GH 43930)更改了对具有
DatetimeTZDtype
的对象执行 setitem-like 操作(__setitem__
,fillna
,where
,mask
,replace
,insert
,以及shift
的 fill_value)时,当使用时区不匹配的值时,该值将被转换为对象的时区,而不是将两者都转换为 object 数据类型 (GH 44243)更改了
Index
、Series
、DataFrame
构造函数在使用浮点数据类型和DatetimeTZDtype
时的行为,现在将数据解释为 UTC 时间而不是本地时间(wall-times),这与整数数据类型的处理方式一致 (GH 45573)更改了
Series
和DataFrame
构造函数在整数 dtype 和包含NaN
的浮点数据时的行为,现在会引发IntCastingNaNError
(GH 40110)更改了
Series
和DataFrame
构造函数在整数dtype
和值过大无法无损转换为该 dtype 时的行为,现在会引发ValueError
(GH 41734)更改了
Series
和DataFrame
构造函数在整数dtype
和值为datetime64
或timedelta64
dtypes 时的行为,现在会引发TypeError
,请改用values.view("int64")
(GH 41770)移除了
pandas.DataFrame.resample()
、pandas.Series.resample()
和pandas.Grouper
中已废弃的base
和loffset
参数。请改用offset
或origin
(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.kurt
在axis=None
时的行为,现在返回一个标量,表示在两个轴上应用聚合 (GH 45072)更改了
Timestamp
与datetime.date
对象的比较行为;现在它们比较为不相等,并在不等比较时引发异常,与datetime.datetime
的行为一致 (GH 36131)更改了
NaT
与datetime.date
对象的比较行为;现在在不等比较时引发异常 (GH 39196)强制执行了对
Series.transform
和DataFrame.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)DataFrame
和Series
在 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)强制执行了在
Rolling
、Expanding
和ExponentialMovingWindow
操作中静默删除无关列的废弃行为。现在会引发errors.DataError
(GH 42834)更改了使用
df.loc[:, foo] = bar
或df.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)移除了
Rolling
、Expanding
和ExponentialMovingWindow
操作中未使用的*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()
的行为,对于任何类列表参数(无论是否包含一个元素),返回一个带有MultiIndex
的Series
,但对于单个标签,返回一个Index
(GH 50829)
性能改进#
改进了
DataFrameGroupBy.median()
和SeriesGroupBy.median()
以及DataFrameGroupBy.cumprod()
对于可空 dtypes 的性能 (GH 37493)改进了
DataFrameGroupBy.all()
、DataFrameGroupBy.any()
、SeriesGroupBy.all()
和SeriesGroupBy.any()
对于 object dtype 的性能 (GH 50623)改进了
MultiIndex.argsort()
和MultiIndex.sort_values()
的性能 (GH 48406)改进了
MultiIndex.size()
的性能 (GH 48723)改进了
MultiIndex.union()
在没有缺失值和没有重复值时的性能 (GH 48505, GH 48752)改进了
MultiIndex.difference()
的性能 (GH 48606)改进了
MultiIndex
集合操作在 sort=None 时的性能 (GH 49010)改进了
DataFrameGroupBy.mean()
、SeriesGroupBy.mean()
、DataFrameGroupBy.var()
和SeriesGroupBy.var()
对于扩展数组 dtypes 的性能 (GH 37493)改进了
MultiIndex.isin()
在level=None
时的性能 (GH 48622, GH 49577)改进了
MultiIndex.putmask()
的性能 (GH 49830)改进了
Index.union()
和MultiIndex.union()
在索引包含重复值时的性能 (GH 48900)改进了
Series.rank()
对于 pyarrow-backed dtypes 的性能 (GH 50264)改进了
Series.searchsorted()
对于 pyarrow-backed dtypes 的性能 (GH 50447)改进了
Series.fillna()
对于扩展数组 dtypes 的性能 (GH 49722, GH 50078)改进了
Index.join()
、Index.intersection()
和Index.union()
对于 masked 和 arrow dtypes 且Index
为单调时的性能 (GH 50310, GH 51365)改进了带有可空 dtype 的
Series.value_counts()
的性能 (GH 48338)构造函数传入列表时的性能提升 (GH 48609)
在基于已排序的 `MultiIndex` 进行
merge()
和DataFrame.join()
操作时的性能提升 (GH 48504)在解析带有时区偏移的字符串时,
to_datetime()
的性能提升 (GH 50107)对
MultiIndex
使用元组索引进行DataFrame.loc()
和Series.loc()
操作时的性能提升 (GH 48384)对 categorical dtype 的
Series.replace()
操作的性能提升 (GH 49404)MultiIndex.unique()
的性能提升 (GH 48335)api.types.infer_dtype()
的性能提升 (GH 51054)使用 BZ2 或 LZMA 时,减少
DataFrame.to_pickle()
/Series.to_pickle()
的内存使用 (GH 49068)StringArray
构造函数传入类型为np.str_
的 numpy 数组时的性能提升 (GH 49109)from_tuples()
的性能提升 (GH 50620)factorize()
的性能提升 (GH 49177)当数组包含 NA 时,
ArrowExtensionArray
比较方法的性能提升 (GH 50524)将字符串解析为
BooleanDtype
时的性能提升 (GH 50613)在基于
MultiIndex
的子集进行DataFrame.join()
操作时的性能提升 (GH 48611)MultiIndex.intersection()
的性能提升 (GH 48604)DataFrame.__setitem__()
的性能提升 (GH 46267)对 nullable dtypes 的
var
和std
操作的性能提升 (GH 48379)。read_sas()
的性能提升 (GH 47403, GH 47405, GH 47656, GH 48502)RangeIndex.sort_values()
的内存改进 (GH 48801)通过避免两次复制,在
copy=True
时Series.to_numpy()
的性能提升 (GH 24345)对带有
MultiIndex
的Series.rename()
操作的性能提升 (GH 21055)当
by
为 categorical 类型且sort=False
时,DataFrameGroupBy
和SeriesGroupBy
的性能提升 (GH 48976)当
by
为 categorical 类型且observed=False
时,DataFrameGroupBy
和SeriesGroupBy
的性能提升 (GH 49596)read_stata()
中参数index_col
设置为None
(默认值) 时的性能提升。现在索引将是RangeIndex
而不是Int64Index
(GH 49745)当不基于索引进行
merge()
操作时的性能提升 - 新的索引将是RangeIndex
而不是Int64Index
(GH 49478)使用任何非 object dtypes 时,
DataFrame.to_dict()
和Series.to_dict()
的性能提升 (GH 46470)存在多个表格时,
read_html()
的性能提升 (GH 49929)使用
'%Y%m%d'
格式时,to_datetime()
的性能提升 (GH 17410)指定格式或可以推断格式时,
to_datetime()
的性能提升 (GH 50465)对 nullable dtypes 的
Series.median()
操作的性能提升 (GH 50838)当将
to_datetime()
lambda 函数传递给date_parser
且输入具有混合时区偏移时,read_csv()
的性能提升 (GH 35296)对 categorical dtype 的
SeriesGroupBy.value_counts()
操作的性能提升 (GH 46202)修复了
read_hdf()
中的引用泄漏 (GH 37441)修复了序列化 datetime 和 timedelta 时
DataFrame.to_json()
和Series.to_json()
中的内存泄漏 (GH 40443)降低了许多
DataFrameGroupBy
方法的内存使用 (GH 51090)DataFrame.round()
中整数decimal
参数的性能提升 (GH 17254)当
to_replace
使用大型字典时,DataFrame.replace()
和Series.replace()
的性能提升 (GH 6697)读取可寻址文件时,
StataReader
的内存改进 (GH 48922)
Bug 修复#
Categorical (分类类型)#
Categorical.set_categories()
中丢失 dtype 信息的 bug (GH 48812)对 categorical dtype 的
Series.replace()
操作中,当to_replace
的值与新值重叠时的 bug (GH 49404)对 categorical dtype 的
Series.replace()
操作中,丢失底层类别的 nullable dtypes 的 bug (GH 49404)DataFrame.groupby()
和Series.groupby()
中,当 categorical 用作 grouper 时会重新排序类别的 bug (GH 48749)从
Categorical
对象构造且dtype="category"
时,Categorical
构造函数中丢失有序性的 bug (GH 49309)使用无序
CategoricalDtype
且没有分组时,SeriesGroupBy.min()
、SeriesGroupBy.max()
、DataFrameGroupBy.min()
和DataFrameGroupBy.max()
未能引发TypeError
的 bug (GH 51034)
日期/时间类型#
pandas.infer_freq()
中,在RangeIndex
上推断时引发TypeError
的 bug (GH 47084)to_datetime()
中,使用对应于大整数的字符串参数时错误地引发OverflowError
的 bug (GH 50533)to_datetime()
中,在errors='coerce'
和infer_datetime_format=True
时对无效偏移量引发错误的 bug (GH 48633)DatetimeIndex
构造函数中,当显式指定tz=None
且结合时区感知dtype
或数据时未能引发错误的 bug (GH 48659)从
DatetimeIndex
中减去datetime
标量时,未能保留原始freq
属性的 bug (GH 48818)pandas.tseries.holiday.Holiday
中,半开日期区间导致USFederalHolidayCalendar.holidays()
返回类型不一致的 bug (GH 49075)使用
dateutil
或zoneinfo
时区且接近夏令时转换时,渲染具有时区感知 dtypes 的DatetimeIndex
、Series
和DataFrame
的 bug (GH 49684)to_datetime()
中,当传入非 ISO8601format
时,解析Timestamp
、datetime.datetime
、datetime.date
或np.datetime64
对象时引发ValueError
的 bug (GH 49298, GH 50036)to_datetime()
中,当解析空字符串且传入非 ISO8601 格式时引发ValueError
的 bug。现在,空字符串将被解析为NaT
,以与 ISO8601 格式的处理方式兼容 (GH 50251)Timestamp
中,解析非 ISO8601 分隔的日期字符串时显示用户无法处理的UserWarning
的 bug (GH 50232)to_datetime()
中,解析包含 ISO 周指令和 ISO 周日指令格式的日期时显示误导性ValueError
的 bug (GH 50308)Timestamp.round()
中,当freq
参数具有零持续时间 (例如 “0ns”) 时返回错误结果而不是引发错误的 bug (GH 49737)to_datetime()
中,当传入无效格式且errors
为 `'ignore'` 或 `'coerce'` 时未引发ValueError
的 bug (GH 50266)DateOffset
中,使用毫秒和其他超日参数构造时抛出TypeError
的 bug (GH 49897)to_datetime()
中,使用格式 `'%Y%m%d'` 解析带有小数日期的字符串时未引发ValueError
的 bug (GH 50051)to_datetime()
中,使用 ISO8601 格式解析混合偏移日期字符串时未将None
转换为NaT
的 bug (GH 50071)to_datetime()
中,使用errors='ignore'
和format='%Y%m%d'
解析超出范围的日期字符串时未返回输入的 bug (GH 14487)to_datetime()
中,使用时区感知字符串、ISO8601 格式和utc=False
解析时,将时区朴素的datetime.datetime
转换为时区感知的 bug (GH 50254)to_datetime()
中,解析 ISO8601 格式日期时,某些值未填充零时抛出ValueError
的 bug (GH 21422)to_datetime()
中,使用format='%Y%m%d'
和errors='ignore'
时给出错误结果的 bug (GH 26493)to_datetime()
中,如果format
不是 ISO8601 格式,则无法解析日期字符串 `'today'` 和 `'now'` 的 bug (GH 50359)Timestamp.utctimetuple()
引发TypeError
的 bug (GH 32174)to_datetime()
中,使用errors='ignore'
解析混合偏移Timestamp
时引发ValueError
的 bug (GH 50585)to_datetime()
中,错误处理溢出边界附近 1unit
内的浮点输入的 bug (GH 50183)to_datetime()
中,单位为 “Y” 或 “M” 时给出错误结果,与逐点Timestamp
结果不匹配的 bug (GH 50870)Series.interpolate()
和DataFrame.interpolate()
中,datetime 或 timedelta dtypes 错误地引发ValueError
的 bug (GH 11312)to_datetime()
中,当输入超出范围时,使用errors='ignore'
未返回输入的 bug (GH 50587)DataFrame.from_records()
中,给定包含时区感知 datetime64 列的DataFrame
输入时,错误地丢失时区感知性的 bug (GH 51162)to_datetime()
中,使用errors='coerce'
解析日期字符串时引发decimal.InvalidOperation
的 bug (GH 51084)to_datetime()
中,同时指定unit
和origin
时返回错误结果的 bug (GH 42624)Series.astype()
和DataFrame.astype()
中,将包含时区感知 datetime 或字符串的 object-dtype 对象转换为datetime64[ns]
时,错误地本地化为 UTC 而不是引发TypeError
的 bug (GH 50140)在
DataFrameGroupBy.quantile()
和SeriesGroupBy.quantile()
中存在的 Bug:当使用 datetime 或 timedelta 数据类型处理包含NaT
的组时,会给出不正确的结果 (GH 51373)在
DataFrameGroupBy.quantile()
和SeriesGroupBy.quantile()
中存在的 Bug:当使用PeriodDtype
或DatetimeTZDtype
时错误地引发异常 (GH 51373)
时间差#
在
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"
且列名为min
或max
时会引发TypeError
异常 (GH 50937)在
DataFrame.min()
和DataFrame.max()
中存在的 Bug:当使用包含pd.NaT
且axis=1
的时区感知数据时,会返回不正确的结果 (GH 51242)
转换#
构建
Series
对象时存在的 Bug:使用字符串列表和int64
数据类型会引发异常而不是进行类型转换 (GH 44923)在
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:在转换为string
且copy=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
等于来自Index
的dtype
时未复制数据 (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)
区间#
在
IntervalIndex.is_overlapping()
中存在的 Bug:当区间包含重复的左边界时输出不正确 (GH 49581)在
Series.infer_objects()
中存在的 Bug:对于一个包含Interval
对象的 object 序列,未能推断出IntervalDtype
(GH 50090)在
Series.shift()
中存在的 Bug:在使用IntervalDtype
且无效的 nullfill_value
时,未能引发TypeError
异常 (GH 51258)
索引#
在
DataFrame.__setitem__()
中存在的 Bug:当索引器是一个数据类型为boolean
的DataFrame
时引发异常 (GH 47125)在
DataFrame.reindex()
中存在的 Bug:在对columns
和index
使用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:在使用全为False
的bool
索引器和空对象时引发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
对象具有单个扩展数组列,并且在重新索引columns
和index
时,将数据类型强制转换为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=False
且self
包含含有NaT
值的列,且该列在other
中不存在时引发TypeError
异常 (GH 16713)修复了
Series.replace()
在替换包含NA
的 object-dtypeSeries
中的值时引发RecursionError
的问题 (GH 47480)修复了
Series.replace()
在替换包含NA
的 numericSeries
中的值时引发RecursionError
的问题 (GH 50758)
MultiIndex#
修复了
MultiIndex.get_indexer()
不匹配NaN
值的问题 (GH 29252, GH 37222, GH 38623, GH 42883, GH 43222, GH 46173, GH 48905)修复了
MultiIndex.argsort()
当索引包含NA
时引发TypeError
的问题 (GH 48495)修复了
MultiIndex.difference()
丢失扩展数组 dtype 的问题 (GH 48606)修复了
MultiIndex.set_levels
在设置空层级时引发IndexError
的问题 (GH 48636)修复了
MultiIndex.unique()
丢失扩展数组 dtype 的问题 (GH 48335)修复了
MultiIndex.intersection()
丢失扩展数组的问题 (GH 48604)修复了
MultiIndex.union()
丢失扩展数组的问题 (GH 48498, GH 48505, GH 48900)修复了
MultiIndex.union()
在 sort=None 且索引包含缺失值时不排序的问题 (GH 49010)修复了
MultiIndex.append()
不检查名称是否相等的问题 (GH 48288)修复了
MultiIndex.symmetric_difference()
丢失扩展数组的问题 (GH 48607)修复了
MultiIndex.join()
当MultiIndex
包含重复项时丢失 dtypes 的问题 (GH 49830)修复了
MultiIndex.putmask()
丢失扩展数组的问题 (GH 49830)修复了
MultiIndex.value_counts()
返回一个由扁平元组索引而非MultiIndex
索引的Series
的问题 (GH 49558)
I/O#
修复了
read_sas()
导致DataFrame
碎片化并引发errors.PerformanceWarning
的问题 (GH 48595)改进了
read_excel()
中的错误消息,在读取文件时引发异常时,通过包含导致错误的 sheet 名称 (GH 48706)修复了腌制 PyArrow 支持的数据子集时的一个问题,该问题会导致序列化整个数据而非子集 (GH 42600)
修复了
read_sql_query()
在指定chunksize
且结果为空时忽略dtype
参数的问题 (GH 50245)修复了
read_csv()
对于列数少于names
参数的单行 csv,使用engine="c"
时引发errors.ParserError
的问题 (GH 47566)修复了
read_json()
在使用orient="table"
和NA
值时引发错误的问题 (GH 40255)修复了显示
string
dtypes 时不显示存储选项的问题 (GH 50099)修复了
DataFrame.to_string()
使用header=False
参数时,将索引名称打印在数据第一行的同一行的问题 (GH 49230)修复了
DataFrame.to_string()
忽略扩展数组的浮点格式化器的问题 (GH 39336)修复了源于内部 JSON 模块初始化导致的内存泄漏问题 (GH 49222)
修复了
json_normalize()
会错误地移除列名前缀中与sep
参数匹配的字符的问题 (GH 49861)修复了
read_csv()
在包含NA
时,不必要地导致扩展数组 dtype 溢出的问题 (GH 32134)修复了
DataFrame.to_dict()
不将NA
转换为None
的问题 (GH 50795)修复了
DataFrame.to_json()
在编码字符串失败时会导致段错误 (segfault) 的问题 (GH 50307)修复了
DataFrame.to_html()
在DataFrame
包含非标量数据并设置了na_rep
参数时的问题 (GH 47103)修复了
read_xml()
在使用 iterparse 时,文件类对象失败的问题 (GH 50641)修复了
read_csv()
使用engine="pyarrow"
时,encoding
参数未正确处理的问题 (GH 51302)修复了
read_xml()
在使用 iterparse 时忽略重复元素的问题 (GH 51183)修复了
ExcelWriter
在实例化过程中发生异常时,文件句柄未关闭的问题 (GH 51443)修复了
DataFrame.to_parquet()
使用engine="pyarrow"
时,非字符串索引或列会引发ValueError
的问题 (GH 52036)
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)
分组/重采样/滚动窗口#
修复了
ExponentialMovingWindow
使用online
参数时,对于不支持的操作未引发NotImplementedError
的问题 (GH 48834)修复了
DataFrameGroupBy.sample()
在对象为空时引发ValueError
的问题 (GH 48459)修复了
Series.groupby()
当索引中的一个条目等于索引名称时引发ValueError
的问题 (GH 48567)修复了
DataFrameGroupBy.resample()
在传入空 DataFrame 时产生不一致结果的问题 (GH 47705)修复了
DataFrameGroupBy
和SeriesGroupBy
在使用分类索引分组时,结果中未包含未观察到的类别的问题 (GH 49354)修复了
DataFrameGroupBy
和SeriesGroupBy
在使用分类数据分组时,结果顺序会取决于输入索引的问题 (GH 49223)修复了
DataFrameGroupBy
和SeriesGroupBy
在使用分类数据分组时,即使使用sort=False
参数,仍会对结果值进行排序的问题 (GH 42482)修复了
DataFrameGroupBy.apply()
和SeriesGroupBy.apply
使用as_index=False
参数时,当使用分组键计算失败并引发TypeError
时,不会尝试不使用分组键进行计算的问题 (GH 49256)修复了
DataFrameGroupBy.describe()
会描述分组键的问题 (GH 49256)修复了
SeriesGroupBy.describe()
使用as_index=False
参数时形状不正确的问题 (GH 49256)修复了
DataFrameGroupBy
和SeriesGroupBy
使用dropna=False
参数时,当分组器是分类类型时会丢弃 NA 值的问题 (GH 36327)修复了
SeriesGroupBy.nunique()
当分组器为空分类且observed=True
时会错误地引发异常的问题 (GH 21334)修复了
SeriesGroupBy.nth()
从DataFrameGroupBy
子集化后,当分组器包含 NA 值时会引发异常的问题 (GH 26454)修复了
DataFrame.groupby()
使用as_index=False
参数时,结果中不包含由key
指定的Grouper
的问题 (GH 50413)修复了
DataFrameGroupBy.value_counts()
与TimeGrouper
一起使用时会引发异常的问题 (GH 50486)修复了
Resampler.size()
导致返回宽DataFrame
而非带有MultiIndex
的Series
的问题 (GH 46826)修复了
DataFrameGroupBy.transform()
和SeriesGroupBy.transform()
当分组器的axis=1
且参数为"idxmin"
和"idxmax"
时会错误地引发异常的问题 (GH 45986)修复了
DataFrameGroupBy
与空 DataFrame、分类分组器和dropna=False
一起使用时会引发异常的问题 (GH 50634)修复了
SeriesGroupBy.value_counts()
未遵循sort=False
参数的问题 (GH 50482)修复了
DataFrameGroupBy.resample()
在时间索引上重采样时,从键列表获取结果时引发KeyError
的问题 (GH 50840)修复了
DataFrameGroupBy.transform()
和SeriesGroupBy.transform()
当分组器的axis=1
且参数为"ngroup"
时会错误地引发异常的问题 (GH 45986)修复了
DataFrameGroupBy.describe()
当数据包含重复列时产生不正确结果的问题 (GH 50806)修复了
DataFrameGroupBy.agg()
使用engine="numba"
时未遵循as_index=False
参数的问题 (GH 51228)修复
DataFrameGroupBy.agg()
、SeriesGroupBy.agg()
和Resampler.agg()
在传入函数列表时会忽略参数的 Bug (GH 50863)修复
DataFrameGroupBy.ohlc()
忽略参数as_index=False
的 Bug (GH 51413)修复
DataFrameGroupBy.agg()
在子集列后 (例如.groupby(...)[["a", "b"]]
) 结果不包含分组信息的 Bug (GH 51186)
重塑#
修复
DataFrame.pivot_table()
对于可空数据类型和margins=True
参数会引发TypeError
的 Bug (GH 48681)修复
DataFrame.unstack()
和Series.unstack()
当MultiIndex
包含混合名称时,会错误地解栈MultiIndex
层级的 Bug (GH 48763)修复
DataFrame.melt()
丢失扩展数组数据类型的 Bug (GH 41570)修复
DataFrame.pivot()
不尊重None
作为列名的 Bug (GH 48293)修复
DataFrame.join()
当left_on
或right_on
是或包含CategoricalIndex
时错误地引发AttributeError
的 Bug (GH 48464)修复
DataFrame.pivot_table()
在结果为空DataFrame
时,使用参数margins=True
会引发ValueError
的 Bug (GH 49240)修复
DataFrame.explode()
对包含NaN
值或空列表的多个列引发ValueError
的 Bug (GH 46084)修复
DataFrame.transpose()
对包含timedelta64[ns]
端点的IntervalDtype
列的 Bug (GH 44917)修复
DataFrame.agg()
和Series.agg()
在传入函数列表时会忽略参数的 Bug (GH 50863)
稀疏#
修复
Series.astype()
在将具有datetime64[ns]
子类型的SparseDtype
转换为int64
数据类型时引发异常的 Bug,这与非稀疏行为不一致 (GH 49631,:issue:50087)修复
Series.astype()
在从datetime64[ns]
转换为Sparse[datetime64[ns]]
时错误地引发异常的 Bug (GH 50082)修复
Series.sparse.to_coo()
在MultiIndex
包含ExtensionArray
时引发SystemError
的 Bug (GH 50996)
扩展数组#
修复
Series.mean()
对可空整数不必要溢出的 Bug (GH 48378)修复
Series.tolist()
对可空数据类型返回 numpy 标量而非 python 标量的 Bug (GH 49890)修复
Series.round()
对基于 pyarrow 的数据类型引发AttributeError
的 Bug (GH 50437)修复当将一个带有 ExtensionDtype 的空 DataFrame 与另一个带有相同 ExtensionDtype 的 DataFrame 连接时,结果数据类型变为 object 的 Bug (GH 48510)
修复
array.PandasArray.to_numpy()
在指定na_value
时对NA
值引发异常的 Bug (GH 40638)修复
api.types.is_numeric_dtype()
中,自定义ExtensionDtype
在_is_numeric
返回True
时不会返回True
的 Bug (GH 50563)修复
api.types.is_integer_dtype()
、api.types.is_unsigned_integer_dtype()
、api.types.is_signed_integer_dtype()
、api.types.is_float_dtype()
中,自定义ExtensionDtype
在kind
返回相应 NumPy 类型时不会返回True
的 Bug (GH 50667)修复将非字符串值设置到
StringArray
中引发ValueError
而非TypeError
的 Bug (GH 49632)修复
DataFrame.reindex()
在处理带有 ExtensionDtype 的列时未遵守默认的copy=True
关键字参数的 Bug (以及因此导致的通过 getitem ([]
) 选择多列时未正确创建副本的问题) (GH 51197)修复
ArrowExtensionArray
逻辑操作&
和|
引发KeyError
的 Bug (GH 51688)
样式器#
修复
background_gradient()
对包含NA
值的可空数据类型Series
的 Bug (GH 50712)
元数据#
修复
DataFrame.corr()
和DataFrame.cov()
中的元数据传播问题 (GH 28283)
其他#
贡献者#
共有 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) +