Pandas-2-2-中文文档-四十二-
Pandas 2.2 中文文档(四十二)
2.0.3 版中的新内容(2023 年 6 月 28 日)
这些是 pandas 2.0.3 中的更改。详见发布说明,了解包括其他版本在内的完整更改日志。
修复的回归问题
-
在
'0000-02-29'
之前,[`Timestamp.weekday`()` 中存在 bug,返回的结果不正确 (GH 53738) -
修复了在合并日期时间类列时的性能回归(GH 53231)
-
修复了当
DataFrame.to_string()
创建额外空间以用于字符串数据类型时的回归问题 (GH 52690) ## Bug fixes -
当尝试转换带有
dtype_backend="nullable_numpy"
的ArrowDtype
时,DataFrame.convert_dtype()
和Series.convert_dtype()
中存在 bug (GH 53648) -
当使用
sort=True
和另一个RangeIndex
时,RangeIndex.union()
中存在 bug (GH 53490) -
在扩展非纳秒日期时间或时间间隔
Series
时,Series.reindex()
中存在 bug,NaT
填充不正确 (GH 53497) -
在使用
bool[pyarrow]
定义dtype
为"c"
和"python"
引擎时,read_csv()
中存在 bug (GH 53390) -
在使用
expand=True
为带有pyarrow.string
的ArrowDtype
进行Series.str.split()
和Series.str.rsplit()
时存在 bug (GH 53532) -
在索引方法(例如
DataFrame.__getitem__()
)中存在 bug,当启用写时复制并且数组长度超过 32 位整数可以容纳的最大大小时,取整个DataFrame
/Series
会引发OverflowError
(GH 53616) -
构建
DataFrame
时出现的错误,其中列具有ArrowDtype
,具有重新索引数据的pyarrow.dictionary
类型(GH 53617) -
使用具有时间戳
ArrowDtype
的DataFrame
或Series
进行索引时,会引发AttributeError
(GH 53644) ## 其他 ## 贡献者
总共有 13 人为此版本贡献了补丁。名字后带有“+”的人第一次贡献了补丁。
-
Conrad Mcgee Stocks +
-
Dominik Berger +
-
Joris Van den Bossche
-
Luke Manley
-
Lumberbot(又名杰克)
-
Marc Garcia
-
Marco Edward Gorelli
-
Matthew Roeschke
-
Pandas 开发团队
-
Thomas A Caswell
-
Thomas Li
-
Xiao Yuan
-
dependabot[bot] ## 修复回归
-
Timestamp.weekday
()中的错误,在
'0000-02-29'`之前返回了不正确的结果(GH 53738) -
在日期时间列上合并时的性能回归修复(GH 53231)
-
修复了
DataFrame.to_string()
在字符串 dtype 上创建额外空间的回归(GH 52690)
修复错误
-
在尝试转换具有
dtype_backend="nullable_numpy"
的ArrowDtype
时,DataFrame.convert_dtype()
和Series.convert_dtype()
中的错误(GH 53648) -
使用
sort=True
与另一个RangeIndex
时,RangeIndex.union()
中的错误(GH 53490) -
Series.reindex()
中的错误,当扩展非纳秒日期时间或时间间隔的Series
时,将无法正确填充为NaT
(GH 53497) -
在使用
bool[pyarrow]
定义dtype
时,read_csv()
中的错误,用于"c"
和"python"
引擎(GH 53390) -
在使用
pyarrow.string
的ArrowDtype
进行expand=True
的Series.str.split()
和Series.str.rsplit()
时存在 bug(GH 53532) -
在索引方法(例如
DataFrame.__getitem__()
)中存在的 bug,当启用写时复制并且数组长度超过 32 位整数的最大大小时,获取整个DataFrame
/Series
会引发OverflowError
错误(GH 53616) -
在构建具有重新索引数据的
pyarrow.dictionary
类型的ArrowDtype
列的DataFrame
时存在 bug(GH 53617) -
当使用时间戳
ArrowDtype
的Index
对DataFrame
或Series
进行索引时,会引发AttributeError
错误(GH 53644)
其他
贡献者
总共有 13 人为此版本贡献了补丁。名字后面带有“+”的人是第一次贡献补丁的。
-
Conrad Mcgee Stocks +
-
Dominik Berger +
-
Joris Van den Bossche
-
Luke Manley
-
Lumberbot(又名 Jack)
-
Marc Garcia
-
Marco Edward Gorelli
-
Matthew Roeschke
-
Pandas 开发团队
-
Thomas A Caswell
-
Thomas Li
-
Xiao Yuan
-
dependabot[bot]
2.0.2 版本的新特性(2023 年 5 月 29 日)
这些是 pandas 2.0.2 的变更。有关 pandas 其他版本的完整更改日志,请参阅发布说明。
修复的回归
-
修复了
GroupBy.apply()
中的性能回归(GH 53195) -
修复了在 Windows 上,
merge()
中 dtype 为np.intc
时的回归(GH 52451) -
修复了
read_sql()
中的回归,删除具有重复列名的列(GH 53117) -
修复了
DataFrame.loc()
中的回归,在扩大对象时丢失MultiIndex
名称(GH 53053) -
修复了
DataFrame.to_string()
中的回归,当 DataFrame 不符合行宽时,在第一行数据的末尾打印反斜杠,而不是标题(GH 53054) -
修复了
MultiIndex.join()
中的回归,返回级别顺序错误(GH 53093) ## Bug fixes -
在
.type
中,arrays.ArrowExtensionArray
中的 Bug 不正确地分配了dict
而不是list
,并在pyarrow.struct
上引发了NotImplementedError
(GH 53328) -
在空分类数据上,
api.interchange.from_dataframe()
中的 Bug 引发了IndexError
(GH 53077) -
在对切片调用时,
api.interchange.from_dataframe()
中的 Bug 返回了不正确大小的DataFrame
(GH 52824) -
在
api.interchange.from_dataframe()
中的 Bug 不必要地在位掩码上引发了异常(GH 49888) -
当在不同分辨率的日期时间列上进行合并时,
merge()
中的 Bug (GH 53200) -
在
engine="pyarrow"
且parse_dates
设置时,read_csv()
报告OverflowError
的 Bug (GH 53295) -
to_datetime()
中的 Bug 在推断日期格式包含"%H"
而不是"%I"
,如果日期包含“AM” / “PM” 标记 (GH 53147) -
在
to_timedelta()
中,如果使用pandas.NA
,会报ValueError
的 Bug (GH 52909) -
在
DataFrame.__getitem__()
中,对MultiIndex
的部分键不保留数据类型的 Bug (GH 51895) -
DataFrame.convert_dtypes()
中的 Bug 在设置为 False 且dtype_backend="pyarrow"
时忽略了convert_*
关键字 (GH 52872) -
当时区感知数据类型且
dtype_backend="pyarrow"
时,DataFrame.convert_dtypes()
丢失时区的 Bug (GH 53382) -
在 PyArrow
dictionary
数据类型时,DataFrame.sort_values()
报错的 Bug (GH 53232) -
在
Series.describe()
中,将 pyarrow 支持的时间戳和时间间隔视为分类数据的 Bug (GH 53001) -
当传递标量给
Series.rename()
时,如果启用了写时复制,不会进行惰性复制的 Bug (GH 52450) -
在
pd.array()
中,对于NumPy
数组和pa.large_string
或pa.large_binary
报错的 Bug (GH 52590) ## 其他 -
在使用
pyarrow.date32
或pyarrow.date64
类型的ArrowDtype
调用Series.dt.to_pydatetime()
时,提高了更好的错误消息(GH 52812) ## 贡献者
总共有 18 人为此版本贡献了补丁。名字后面带有“+”的人是第一次贡献补丁的。
-
Gianluca Ficarelli +
-
Guillaume Lemaitre
-
Joris Van den Bossche
-
Julian Badillo +
-
Luke Manley
-
Lumberbot(又名 Jack)+
-
Marc Garcia
-
Marco Edward Gorelli
-
MarcoGorelli
-
Matt Richards
-
Matthew Roeschke
-
MeeseeksMachine
-
Pandas 开发团队
-
Patrick Hoefler
-
Simon Høxbro Hansen +
-
Thomas Li
-
Yao Xiao +
-
dependabot[bot] ## 修复的回归问题
-
修复了
GroupBy.apply()
中的性能回归问题(GH 53195) -
修复了在 Windows 上使用
np.intc
类型时merge()
中的回归问题(GH 52451) -
修复了
read_sql()
中的回归问题,导致重复列名的列被删除(GH 53117) -
修复了
DataFrame.loc()
中的回归问题,在扩大对象时丢失MultiIndex
名称(GH 53053) -
修复了
DataFrame.to_string()
中的回归问题,当 DataFrame 不适合行宽时,在第一行数据的末尾打印反斜杠,而不是标题(GH 53054) -
修复了
MultiIndex.join()
中的回归问题,返回顺序错误的级别(GH 53093)
Bug fixes
-
arrays.ArrowExtensionArray
中的错误,错误地将pyarrow.map_
的.type
分配为dict
而不是list
,并且在pyarrow.struct
上引发NotImplementedError
(GH 53328) -
api.interchange.from_dataframe()
中的错误,当空分类数据时引发IndexError
(GH 53077) -
api.interchange.from_dataframe()
中的 Bug 在调用片段时返回了DataFrame
的不正确大小 (GH 52824) -
api.interchange.from_dataframe()
中的 Bug 无必要地对 bitmasks 进行了提升 (GH 49888) -
在不同分辨率的 datetime 列上合并时,
merge()
中的 Bug (GH 53200) -
read_csv()
中的 Bug 在engine="pyarrow"
和parse_dates
设置时引发OverflowError
(GH 53295) -
在推断格式以包含
"%H"
而不是"%I"
的情况下,to_datetime()
中的 Bug 包含了“AM”/“PM” tokens (GH 53147) -
to_timedelta()
中的 Bug 在使用pandas.NA
时引发ValueError
(GH 52909) -
在
DataFrame.__getitem__()
中,不保留MultiIndex
部分键的 dtypes 的 Bug (GH 51895) -
DataFrame.convert_dtypes()
中的 Bug 在设置为 False 时忽略了convert_*
关键字,dtype_backend="pyarrow"
(GH 52872) -
DataFrame.convert_dtypes()
中的 Bug 在 tz-aware dtypes 和dtype_backend="pyarrow"
时丢失了时区 (GH 53382) -
在 PyArrow
dictionary
dtype 上,DataFrame.sort_values()
中的 Bug 引发了错误 (GH 53232) -
在处理 pyarrow-backed timestamps 和 timedeltas 时,
Series.describe()
将其视为分类数据 (GH 53001) -
在调用
Series.rename()
传递标量参数时未在启用写时复制时进行懒惰复制的 bug (GH 52450) -
在使用
pd.array()
时引发NumPy
数组和pa.large_string
或pa.large_binary
时的 bug (GH 52590)
其他
- 在使用
Series.dt.to_pydatetime()
时,当使用pyarrow.date32
或pyarrow.date64
类型的ArrowDtype
时,提高了错误消息的质量 (GH 52812)
贡献者
总共有 18 人为此版本提供了补丁。名字后带有 “+” 符号的人是第一次为此贡献补丁的。
-
Gianluca Ficarelli +
-
Guillaume Lemaitre
-
Joris Van den Bossche
-
Julian Badillo +
-
Luke Manley
-
木头机器人(又名杰克) +
-
Marc Garcia
-
Marco Edward Gorelli
-
MarcoGorelli
-
Matt Richards
-
Matthew Roeschke
-
MeeseeksMachine
-
Pandas 开发团队
-
Patrick Hoefler
-
Simon Høxbro Hansen +
-
Thomas Li
-
Yao Xiao +
-
dependabot[bot]
2.0.1 版本新功能(2023 年 4 月 24 日)
这些是 pandas 2.0.1 中的变更。查看 发布说明 以获取包括其他版本的完整更改日志。
修复的回归问题
-
修复了从字典构造子类 Series 时的回归问题(GH 52445)
-
修复了在使用分类数据、多个分组、
as_index=False
和聚合列表进行分组时,调用SeriesGroupBy.agg()
失败的回归问题(GH 52760) -
修复了调用
DataFrame.pivot()
时更改输入对象的Index
名称的回归问题(GH 52629) -
修复了在没有列的 DataFrame 上调用
DataFrame.resample()
时引发的回归问题(GH 52484) -
修复了在已经排序并且
ignore_index=True
时,调用DataFrame.sort_values()
不重置索引的回归问题(GH 52553) -
修复了对
Generator
引发TypeError
的MultiIndex.isin()
的回归问题(GH 52568) -
修复了在调用
Series.describe()
时,对具有单个元素的扩展 dtypeSeries
引发RuntimeWarning
的回归问题(GH 52515) -
修复了向
DataFrame
添加新列时,当DataFrame.columns
是RangeIndex
而新键是可哈希但不是标量时的回归问题(GH 52652) ## Bug 修复 -
Series.dt.days
中的 bug,可能会导致int32
天数溢出的回归问题(GH 52391) -
Bug in
arrays.DatetimeArray
构造函��在传递非纳秒 numpy 日期时间数组时返回不正确的单位的 bug(GH 52555) -
Bug in
ArrowExtensionArray
,当从包含 numpyNaT
的数据构建时,持续时间 dtype 会溢出(GH 52843) -
Bug in
Series.dt.round()
当传递与Series
相比相等或更高分辨率的freq
时,会引发ZeroDivisionError
(GH 52761) -
Bug in
Series.median()
与ArrowDtype
一起返回近似中位数的 bug(GH 52679) -
Bug in
api.interchange.from_dataframe()
在分类 dtype 上不必要地引发异常(GH 49889) -
Bug in
api.interchange.from_dataframe()
在大字符串 dtype 上不必要地引发异常(GH 52795) -
Bug in
pandas.testing.assert_series_equal()
中check_dtype=False
的 bug,仍会因日期时间或时间间隔类型的分辨率不同而引发错误(GH 52449) -
Bug in
read_csv()
在dtype_backend="pyarrow"
和设置parse_dates
时,将 PyArrow 日期时间转换为 NumPy 导致性能瓶颈的 bug(GH 52546) -
Bug in
to_datetime()
和to_timedelta()
尝试使用ArrowDtype
转换数值数据时的 bug(GH 52425) -
Bug in
to_numeric()
在使用errors='coerce'
和dtype_backend='pyarrow'
以及ArrowDtype
数据时出现问题(GH 52588) -
Bug in
ArrowDtype.__from_arrow__()
在未尊重显式给定 dtype 的情况下出现错误(GH 52533) -
Bug in
DataFrame.describe()
在include
和exclude
中未尊重ArrowDtype
(GH 52570) -
Bug in
DataFrame.max()
和相关的将不同的Timestamp
分辨率始终转换为纳秒的问题(GH 52524) -
Bug in
Series.describe()
在数值数据中使用pyarrow.float64
类型时未返回ArrowDtype
(GH 52427) -
Bug in
Series.dt.tz_localize()
在使用ArrowDtype
时错误地本地化时间戳(GH 52677) -
Bug in
np.datetime64
和np.timedelta64
NaT
标量之间的算术运算始终返回纳秒分辨率(GH 52295) -
Bug in
ArrowDtype
与 numpy 掩码类型(例如"boolean"
)之间的逻辑和比较操作中出现问题(GH 52625) -
修复了在与
ArrowDtype
一侧和另一侧为 NumPy dtype 进行合并时merge()
中的错误(GH 52406) -
修复了在使用
null[pyarrow]
dtype 时Series.to_numpy()
中的段错误(GH 52443) ## 其他 -
从空字典创建的
DataFrame
的columns
的数据类型为object
。现在是一个RangeIndex
(GH 52404) -
从空字典创建的
Series
的index
的数据类型为object
。现在是一个RangeIndex
(GH 52404) -
用
pyarrow.string
为ArrowDtype
实现了Series.str.split()
和Series.str.rsplit()
(GH 52401) -
用
pyarrow.string
为ArrowDtype
实现了大多数str
访问器方法(GH 52401) -
为
api.types.is_scalar()
提供一个非整数可散列键,如果在RangeIndex.get_loc()
中测试为False
,现在会引发KeyError
,就像在Index.get_loc()
中一样。之前会引发InvalidIndexError
(GH 52652). ## 贡献者
总共有 20 人对此版本做出了贡献。名字后带“+”的人是第一次贡献补丁的人。
-
Alex Malins +
-
Chris Carini +
-
Dea María Léon
-
Joris Van den Bossche
-
Luke Manley
-
Marc Garcia
-
Marco Edward Gorelli
-
MarcoGorelli
-
Matthew Roeschke
-
MeeseeksMachine
-
Natalia Mokeeva
-
Nirav +
-
Pandas 开发团队
-
Patrick Hoefler
-
Richard Shadrach
-
Stefanie Molin
-
Terji Petersen
-
Thomas +
-
Thomas Li
-
yonashub ## 修复的回归问题
-
修复了从字典构造时子类化 Series 的回归问题(GH 52445)
-
修复了在使用分类数据、多个分组、
as_index=False
和聚合列表时,SeriesGroupBy.agg()
在分组时失败的问题(GH 52760) -
修复了
DataFrame.pivot()
中的回归,改变了输入对象的Index
名称(GH 52629) -
修复了
DataFrame.resample()
中的回归,对没有列的 DataFrame 进行处理时引发错误(GH 52484) -
修复了
DataFrame.sort_values()
中的回归,当DataFrame
已经排序且ignore_index=True
时不重置索引(GH 52553) -
修复了
MultiIndex.isin()
中的回归,对Generator
引发TypeError
的问题(GH 52568) -
修复了
Series.describe()
中的回归,对只有一个元素的扩展 dtypeSeries
显示RuntimeWarning
的问题(GH 52515) -
修复了向
DataFrame
添加新列时的回归,当DataFrame.columns
是RangeIndex
且新键是可哈希但不是标量时的问题(GH 52652)
Bug 修复
-
修复了
Series.dt.days
中的错误,可能会导致int32
天数溢出(GH 52391) -
修复了在传递非纳秒 numpy 日期时间数组时,
arrays.DatetimeArray
构造函数返回不正确单位的错误(GH 52555) -
在构建包含 numpy
NaT
数据的情况下,修复了ArrowExtensionArray
中的持续时间 dtype 溢出的错误(GH 52843) -
在
Series.dt.round()
中存在一个 bug,当传递与Series
相比分辨率相等或更高的freq
时会引发ZeroDivisionError
(GH 52761) -
在
Series.median()
中存在一个 bug,返回一个近似的中位数 (GH 52679) -
在
api.interchange.from_dataframe()
中存在一个 bug,不必要地对分类 dtype 引发异常 (GH 49889) -
在
api.interchange.from_dataframe()
中存在一个 bug,不必要地对大型字符串 dtype 引发异常 (GH 52795) -
在
pandas.testing.assert_series_equal()
中存在一个 bug,即使check_dtype=False
,对于具有不同分辨率的日期时间或时间间隔类型仍会引发错误 (GH 52449) -
在
read_csv()
中存在一个 bug,当dtype_backend="pyarrow"
且parse_dates
被设置时,将 PyArrow 日期时间转换为 NumPy 导致性能瓶颈的过程 (GH 52546) -
在
to_datetime()
和to_timedelta()
中存在一个 bug,当尝试将数值数据转换为ArrowDtype
时 (GH 52425) -
在
to_numeric()
中存在一个 bug,当errors='coerce'
且dtype_backend='pyarrow'
与ArrowDtype
数据一起使用时 (GH 52588) -
在
ArrowDtype.__from_arrow__()
中存在一个 bug,不遵循 dtype 是否明确给定的情况 (GH 52533) -
修复了在
DataFrame.describe()
中不尊重ArrowDtype
在include
和exclude
中的错误(GH 52570) -
修复了在
DataFrame.max()
和相关的类型转换中,总是将不同的Timestamp
分辨率转换为纳秒的错误(GH 52524) -
修复了在带有数值数据的
pyarrow.float64
类型的ArrowDtype
的Series.describe()
中未返回ArrowDtype
的错误(GH 52427) -
修复了在使用
ArrowDtype
时Series.dt.tz_localize()
错误地本地化时间戳的错误(GH 52677) -
修复了在
np.datetime64
和np.timedelta64
NaT
标量单位下的算术运算总是返回纳秒分辨率的错误(GH 52295) -
修复了在
ArrowDtype
和 numpy 掩码类型(例如"boolean"
)之间的逻辑与比较操作中的错误(GH 52625) -
修复了在使用
ArrowDtype
的一侧合并时和另一侧使用 NumPy 数据类型时的merge()
中的错误(GH 52406) -
修复了使用
null[pyarrow]
数据类型导致的Series.to_numpy()
发生的段错误(segfault)(GH 52443)
其他
-
由空字典创建的
DataFrame
的columns
数据类型为object
。现在是RangeIndex
(GH 52404) -
由空字典创建的
Series
的index
数据类型为object
。现在是RangeIndex
(GH 52404) -
为
ArrowDtype
实现了Series.str.split()
和Series.str.rsplit()
,使用了pyarrow.string
(GH 52401)。 -
为
ArrowDtype
实现了大多数str
访问器方法,使用了pyarrow.string
(GH 52401)。 -
对于提供了在
api.types.is_scalar()
中测试为False
的非整数可散列键,现在会像Index.get_loc()
一样,为RangeIndex.get_loc()
抛出KeyError
。之前会抛出InvalidIndexError
(GH 52652)。
贡献者
本次发布共有 20 人贡献了补丁。在其名字旁边带有“+”符号的人第一次贡献了补丁。
-
Alex Malins +
-
Chris Carini +
-
Dea María Léon
-
Joris Van den Bossche
-
Luke Manley
-
Marc Garcia
-
Marco Edward Gorelli
-
MarcoGorelli
-
Matthew Roeschke
-
MeeseeksMachine
-
Natalia Mokeeva
-
Nirav +
-
Pandas 开发团队
-
Patrick Hoefler
-
Richard Shadrach
-
Stefanie Molin
-
Terji Petersen
-
Thomas +
-
Thomas Li
-
yonashub
2.0.0 中的新功能 (2023 年 4 月 3 日)
这些是 pandas 2.0.0 中的更改。有关完整的更改日志,请参阅 发布说明,其中包括 pandas 的其他版本。
增强功能
使用 pip extras 安装可选依赖项
使用 pip 安装 pandas 时,还可以通过指定 extras 来安装一组可选依赖项。
pip install "pandas[performance, aws]>=2.0.0"
可用的额外功能,在 安装指南 中找到,是 [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 数字 dtypes
现在可以在 Index
中使用任何 numpy 数字 dtype (GH 42717).
之前只能使用 int64
、uint64
和 float64
dtypes:
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 数字 dtypes,即 int8
/ int16
/int32
/int64
/uint8
/uint16
/uint32
/uint64
/float32
/float64
dtypes:
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 数字 dtypes 的能力意味着 Pandas 功能上的一些更改。特别是,先前强制创建 64 位索引的操作现在可以创建具有较低位大小的索引,例如 32 位索引。
以下是可能不完整的更改列表:
-
使用 numpy 数字数组进行实例化现在遵循 numpy 数组的 dtype。之前,从 numpy 数字数组创建的所有索引都被强制为 64 位。现在,例如,
Index(np.array([1, 2, 3]))
在 32 位系统上将是int32
,之前即使在 32 位系统上也将是int64
。使用数字列表进行Index
实例化仍将返回 64 位 dtypes,例如Index([1, 2, 3])
将具有int64
dtype,与之前相同。 -
DatetimeIndex
的各种数字日期时间属性(day
、month
、year
等)以前的数据类型为int64
,而在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()
返回的索引的级别数据类型现在为int32
,与 scipy 稀疏矩阵上的rows
/cols
的数据类型相同。以前它们的数据类型为int64
。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
-
Index
不能使用float16
数据类型进行实例化。以前使用float16
数据类型实例化Index
会得到一个Float64Index
,其数据类型为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_backend
的关键字参数(GH 36712):
-
read_csv()
-
read_clipboard()
-
read_fwf()
-
read_excel()
-
read_html()
-
read_xml()
-
read_json()
-
read_sql()
-
read_sql_query()
-
read_sql_table()
-
read_parquet()
-
read_orc()
-
read_feather()
-
read_spss()
-
to_numeric()
-
DataFrame.convert_dtypes()
-
Series.convert_dtypes()
当此选项设置为"numpy_nullable"
时,它将返回由可空数据类型支持的DataFrame
。
当此关键字设置为"pyarrow"
时,这些函数将返回由 pyarrow 支持的可空ArrowDtype
数据帧(GH 48957, GH 49997):
-
read_csv()
-
read_clipboard()
-
read_fwf()
-
read_excel()
-
read_html()
-
read_xml()
-
read_json()
-
read_sql()
-
read_sql_query()
-
read_sql_table()
-
read_parquet()
-
read_orc()
-
read_feather()
-
read_spss()
-
to_numeric()
-
DataFrame.convert_dtypes()
-
Series.convert_dtypes()
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 时,DataFrame
构造器现在将创建一个延迟复制(在数据发生修改时推迟复制)(GH 51239)。 -
当从 Series 对象的字典构造 DataFrame 并指定
copy=False
时,DataFrame
构造器现在将为 DataFrame 的列使用这些 Series 对象的延迟复制(GH 50777)。 -
当从
Series
或Index
构造 DataFrame 并指定copy=False
时,DataFrame
构造器现在将尊重写时复制。 -
当从 NumPy 数组构造时,
DataFrame
和Series
构造函数现在默认会复制数组,以避免在修改数组后修改DataFrame
/Series
。指定copy=False
以获取旧行为。当设置copy=False
时,pandas 不保证在创建DataFrame
/Series
后修改 NumPy 数组时正确的写时复制行为。 -
当使用
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
具有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()
现在保留可空数据类型,而不是转换为 numpy 数据类型。 (GH 37493) -
DataFrameGroupBy.std()
、SeriesGroupBy.std()
现在支持 datetime64、timedelta64 和DatetimeTZDtype
数据类型。 (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) -
merge()
中添加了对扩展数组数据类型的支持 (GH 44240) -
在
DataFrame
上的二进制运算符上添加了元数据传播 (GH 28283) -
通过
_accumulate
将cumsum
,cumprod
,cummin
和cummax
添加到ExtensionArray
接口中 (GH 28385) -
现在在
pandas.errors
中公开了CategoricalConversionWarning
,InvalidComparison
,InvalidVersion
,LossySetitemError
, 和NoBufferPresent
(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) -
在使用
testing.assert_frame_equal()
对DataFrame
进行比较时,改进了异常消息,包括被比较的列名(GH 50323) -
在
merge_asof()
中,当连接列重复时,改进了错误消息(GH 50102) -
为
get_dummies()
添加了对扩展数组数据类型的支持(GH 32430) -
添加了类似于
Series.infer_objects()
的Index.infer_objects()
(GH 50034) -
在
Series.infer_objects()
和DataFrame.infer_objects()
中添加了copy
参数,传递False
将避免为已经是非对象类型或无法推断出更好数据类型的系列或列制作副本(GH 50096) -
DataFrame.plot.hist()
现在识别xlabel
和ylabel
参数(GH 49793) -
Series.drop_duplicates()
现在具有ignore_index
关键字以重置索引(GH 48304) -
Series.dropna()
和DataFrame.dropna()
现在具有ignore_index
关键字以重置索引(GH 31725) -
对于非 ISO8601 格式,改进了
to_datetime()
中的错误消息,向用户提供第一个错误的位置信息(GH 50361) -
当尝试对齐
DataFrame
对象(例如,在DataFrame.compare()
中)时,改进了错误消息,以澄清“标签相同”指的是索引和列都相同的情况(GH 50083) -
为 pyarrow 字符串类型增加了对
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"
解析 JSON(GH 48893) -
添加了对 SQLAlchemy 2.0 的支持(GH 40686)
-
在
engine="pyarrow"
时,read_csv()
中添加了decimal
参数支持(GH 51302) -
Index
集合操作Index.union()
、Index.intersection()
、Index.difference()
和Index.symmetric_difference()
现在支持sort=True
,这将始终返回一个排序结果,与默认的sort=None
不同,在某些情况下不会排序(GH 25151) -
添加了新的转义模式“latex-math”,以避免在格式化程序中转义“$”(GH 50040)## 显著的错误修复
这些是可能具有显著行为变化的错误修复。
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
我们在第 6 个值返回不正确的结果。
新行为
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
我们在第 7 个值上溢出,但第 6 个值仍然正确。 ### 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`并传递一个具有不支持分辨率的“datetime64”或“timedelta64” dtype 时(即除了“ns”之外的任何分辨率),pandas 会默默地用其纳秒模拟替换给定的 dtype:
*以前的行为*:
```py
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:1219, in maybe_cast_to_datetime(value, dtype)
1215 raise TypeError("value must be listlike")
1217 # TODO: _from_sequence would raise ValueError in cases where
1218 # _ensure_nanosecond_dtype raises TypeError
-> 1219 _ensure_nanosecond_dtype(dtype)
1221 if lib.is_np_dtype(dtype, "m"):
1222 res = TimedeltaArray._from_sequence(value, dtype=dtype)
File ~/work/pandas/pandas/pandas/core/dtypes/cast.py:1276, in _ensure_nanosecond_dtype(dtype)
1273 raise ValueError(msg)
1274 # TODO: ValueError or TypeError? existing test
1275 # test_constructor_generic_timestamp_bad_frequency expects TypeError
-> 1276 raise TypeError(
1277 f"dtype={dtype} is not supported. Supported resolutions are 's', "
1278 "'ms', 'us', and 'ns'"
1279 )
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](https://github.com/pandas-dev/pandas/issues/49497))。
*以前的行为*:
```py
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 添加了支持,因此转换为这些 dtypes 会得到确切的请求 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]
转换的 dtype,旧的行为会转换为浮点格式。
以前的行为:
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](https://github.com/pandas-dev/pandas/issues/34916))
*先前的行为*:
```py
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
)会将轴返回为空的对象 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 转换 JupyterNotebook 时才会生成 LaTeX,而不是在用户运行笔记本时。现在 `styler.render.repr` 选项允许在操作中(不仅仅是在 nbconvert 中)控制 JupyterNotebooks 中的特定输出。参见[GH 39911](https://github.com/pandas-dev/pandas/issues/39911)。 ### 增加了依赖项的最低版本
一些依赖项的最低支持版本已更新。如果已安装,我们现在需要:
| 包 | 最低版本 | 必需 | 已更改 |
| --- | --- | --- | --- |
| mypy (dev) | 1.0 | | X |
| pytest (dev) | 7.0.0 | | X |
| pytest-xdist (dev) | 2.2.0 | | X |
| hypothesis (dev) | 6.34.2 | | X |
| python-dateutil | 2.8.2 | X | X |
| tzdata | 2022.1 | X | X |
对于[可选库](https://pandas.pydata.org/docs/getting_started/install.html),通常建议使用最新版本。以下表格列出了 pandas 开发过程中当前正在测试的每个库的最低版本。低于最低测试版本的可选库可能仍然有效,但不被视为受支持。
| 包 | 最低版本 | 更改 |
| --- | --- | --- |
| pyarrow | 7.0.0 | X |
| matplotlib | 3.6.1 | X |
| fastparquet | 0.6.3 | X |
| xarray | 0.21.0 | X |
查看依赖项和可选依赖项了解更多信息。
### 现在日期时间以一致的格式解析
在过去,`to_datetime()` 会独立地猜测每个元素的格式。这在一些元素具有混合日期格式的情况下是合适的——然而,当用户期望一致的格式但函数会在元素之间切换格式时,这通常会导致问题。从版本 2.0.0 开始,解析将使用一致的格式,由第一个非 NA 值确定(除非用户指定格式,在这种情况下将使用该格式)。
*旧行为*:
```py
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) -
将“timedelta64[s]”、“timedelta64[ms]”或“timedelta64[us]”的
dtype
传递给TimedeltaIndex
、Series
或DataFrame
的构造函数现在会保留该dtype
,而不是转换为“timedelta64[ns]”;将低分辨率的dtype
传递给Series
或DataFrame
的构造函数将被转换为最低支持的分辨率“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
) -
当创建一个具有日期时间对象的对象类型
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
的数组类返回True
,当元素被推断为字符串时(GH 15585) -
将包含
datetime
对象和date
对象的序列传递给Series
构造函数将返回object
dtype,而不是datetime64[ns]
dtype,与Index
的行为一致(GH 49341) -
将无法解析为日期时间的字符串传递给带有
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,与Series
的行为一致(GH 49340) -
将参数
index_col
设置为None
(默认)的read_stata()
现在将返回的DataFrame
的索引设置为RangeIndex
而不是Int64Index
(GH 49745) -
更改了在处理对象类型时
Index
、Series
和DataFrame
算术方法的行为,结果不再对数组操作的结果进行类型推断,使用result.infer_objects(copy=False)
来对结果进行类型推断(GH 49999, GH 49714) -
更改了带有对象类型
numpy.ndarray
的Index
构造函数的行为,其中包含全部为bool
值或全部为复数值,现在将保留对象数据类型,与Series
的行为一致(GH 49594) -
将
Series.astype()
从包含bytes
对象的对象数据类型更改为字符串数据类型;现在对字节对象执行val.decode()
而不是str(val)
,与Index.astype()
的行为相匹配(GH 45326) -
在
read_csv()
中将"None"
添加到默认的na_values
中(GH 50286) -
当给定整数数据类型和不是整数的浮点数据时,更改了
Series
和DataFrame
构造函数的行为,现在会引发ValueError
而不是悄悄地保留浮点数据类型;使用Series(data)
或DataFrame(data)
以获取旧的行为,使用Series(data).astype(dtype)
或DataFrame(data).astype(dtype)
以获取指定的数据类型(GH 49599) -
改变了带有
axis=1
、整数fill_value
和同质日期时间样式的DataFrame.shift()
的行为,现在新列将填充整数 dtype,而不是转换为日期时间样式(GH 49842) -
在
read_json()
遇到异常时,文件现在会被关闭(GH 49921) -
改变了
read_csv()
、read_json()
和read_fwf()
的行为,当未指定索引时,索引现在将始终是RangeIndex
。之前,如果新的 DataFrame/Series 的长度为 0,则索引将是具有 dtypeobject
的Index
(GH 49572) -
DataFrame.values()
、DataFrame.to_numpy()
、DataFrame.xs()
、DataFrame.reindex()
、DataFrame.fillna()
和DataFrame.replace()
不再悄悄地合并底层数组;执行df = df.copy()
以确保合并(GH 49356) -
使用
loc
或iloc
在两个轴上使用全片段创建新 DataFrame(因此,df.loc[:, :]
或df.iloc[:, :]
)现在返回一个新的 DataFrame(浅拷贝),而不是原始 DataFrame,与其他获取全片段的方法一致(例如df.loc[:]
或df[:]
)(GH 49469) -
当传递 Series 和 DataFrame 到构造函数时,默认为
copy=False
(如果没有其他关键字触发复制),现在构造函数会返回浅拷贝(即共享数据,但不共享属性)。以前,新的 Series 或 DataFrame 会共享索引属性(例如df.index = ...
也会更新父级或子级的索引)(GH 49523) -
禁止对
Timedelta
对象计算cumprod
;以前会返回不正确的值(GH 50246) -
从
HDFStore
文件读取的DataFrame
对象如果没有索引,则现在具有RangeIndex
而不是int64
索引(GH 51076) -
使用包含
NA
和/或NaT
的数据实例化具有数字 numpy 数据类型的Index
现在会引发ValueError
。以前会引发TypeError
(GH 51050) -
使用
read_json(orient='split')
加载具有重复列的 JSON 文件时,会重新命名列以避免重复,就像read_csv()
和其他读取器一样(GH 50370) -
从
Series.sparse.from_coo
返回的Series
索引级别现在始终具有int32
数据类型。以前它们的数据类型为int64
(GH 50926) -
当
to_datetime()
的unit
为 “Y” 或 “M” 时,如果序列包含非圆整的float
值,现在会引发异常,与Timestamp
的行为相匹配(GH 50301) -
方法
Series.round()
、DataFrame.__invert__()
、Series.__invert__()
、DataFrame.swapaxes()
、DataFrame.first()
、DataFrame.last()
、Series.first()
、Series.last()
和DataFrame.align()
现在将始终返回新对象 (GH 51032) -
DataFrame
和DataFrameGroupBy
聚合(例如“sum”)的对象 dtype 列不再推断其结果的非对象 dtype,请在结果上显式调用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()
现在返回带有pyarrow.int64
类型而不是"Int64"
类型的数据,使用ArrowDtype
(GH 51462) -
当传递具有非纳秒分辨率的 numpy timedelta64 或 datetime64 时,
factorize()
和unique()
会保留原始 dtype (GH 48670)
注意
当前的 PDEP 提议对 pandas API 中除了一小部分方法之外的所有方法的 inplace
和 copy
关键字进行弃用和删除。当前的讨论发生在 这里。在写时复制的上下文中,这些关键字将不再必要。如果该提议被接受,这两个关键字将在 pandas 的下一个版本中被弃用,并在 pandas 3.0 中被移除。## 弃用
-
弃用了使用系统本地时区解析日期时间字符串到
tzlocal
的行为,请传递一个tz
关键字或显式调用tz_localize
来替代 (GH 50791) -
在
to_datetime()
和read_csv()
中,infer_datetime_format
参数已被弃用,现在其严格版本已成为默认值 (GH 48621) -
当解析字符串时,使用
unit
参数的to_datetime()
的行为已经被弃用,在未来版本中,这些将被解析为日期时间(与无单位的行为匹配)而不是转换为浮点数。要保留旧行为,请在调用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) -
废弃了
read_csv()
、read_table()
、read_fwf()
和read_excel()
中的date_parser
参数,改用date_format
(GH 50601) -
废弃了
datetime64
和DatetimeTZDtype
dtypes 中的all
和any
reductions,改用例如(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
作为上下文管理器(GH 49228) -
弃用在迭代
DataFrameGroupBy
或SeriesGroupBy
时产生标量的行为,该行为已被弃用,当level
参数是长度为 1 的列表时,将返回长度为 1 的元组代替(GH 51583) ## 移除之前版本的弃用/更改 -
移除了
Int64Index
、UInt64Index
和Float64Index
。更多信息请参见此处(GH 42717) -
移除了不推荐使用的
Timestamp.freq
、Timestamp.freqstr
以及Timestamp
构造函数和Timestamp.fromordinal()
方法中的freq
参数(GH 14146) -
移除了不推荐使用的
CategoricalBlock
、Block.is_categorical()
,要求将 datetime64 和 timedelta64 值封装在DatetimeArray
或TimedeltaArray
中后再传递给Block.make_block_same_class()
,要求在传递给BlockManager
构造函数时,DatetimeTZBlock.values
具有正确的 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]
数据类型和时区感知数据类型传递给Series
时的行为更改,将值解释为壁钟时间而不是 UTC 时间,与DatetimeIndex
的行为相匹配(GH 41662) -
强制废弃了在对多个未对齐(在索引或列上)的 numpy ufunc 应用于
DataFrame
时的行为更改,现在将首先对输入进行对齐(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) -
移除了废弃的
weekofyear
和week
属性的DatetimeArray
,DatetimeIndex
和dt
访问器,改用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
转换为时区无关的datetime64[ns]
dtype,改用obj.tz_localize(None)
或obj.tz_convert("UTC").tz_localize(None)
代替(GH 39258) -
在
concat()
中强制废弃排序时传递非布尔参数(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()
中删除参数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) -
从
DataFrame.to_csv()
和Series.to_csv()
中删除了参数line_terminator
,改用lineterminator
代替(GH 45302) -
从
DataFrame.set_axis()
和Series.set_axis()
中删除了参数inplace
,改用obj = obj.set_axis(..., copy=False)
代替(GH 48130) -
禁止向
MultiIndex.set_levels()
和MultiIndex.set_codes()
传递位置参数(GH 41485) -
禁止解析带有单位“Y”、“y”或“M”的时间增量字符串,因为这些不代表明确的持续时间(GH 36838)
-
删除了
MultiIndex.is_lexsorted()
和MultiIndex.lexsort_depth()
(GH 38701) -
从
PeriodIndex.astype()
中删除了参数how
,改用PeriodIndex.to_timestamp()
代替(GH 37982) -
从
DataFrame.mask()
、DataFrame.where()
、Series.mask()
和Series.where()
中删除了参数try_cast
(GH 38836) -
从
Period.to_timestamp()
中删除了参数tz
,请改用obj.to_timestamp(...).tz_localize(tz)
(GH 34522) -
从
DataFrame.plot()
和Series.plot()
中删除了参数sort_columns
(GH 47563) -
从
DataFrame.take()
和Series.take()
中删除了参数is_copy
(GH 30615) -
从
Index.get_slice_bound()
、Index.slice_indexer()
和Index.slice_locs()
中删除了参数kind
(GH 41378) -
从
read_csv()
中删除了参数prefix
、squeeze
、error_bad_lines
和warn_bad_lines
(GH 40413、GH 43427) -
从
read_excel()
中删除了参数squeeze
(GH 43427) -
从
DataFrame.describe()
和Series.describe()
中删除了参数datetime_is_numeric
,因为日期时间数据将始终被总结为数值数据(GH 34798) -
禁止将列表
key
传递给Series.xs()
和DataFrame.xs()
,改为传递元组(GH 41789) -
在
Index
构造函数中禁止子类特定关键字(例如“freq”、“tz”、“names”、“closed”)(GH 38597) -
从
Categorical.remove_unused_categories()
中删除参数inplace
(GH 37918) -
禁止将非四舍五入浮点数传递给
Timestamp
,使用unit="M"
或unit="Y"
(GH 47266) -
从
read_excel()
中删除关键字convert_float
和mangle_dupe_cols
(GH 41176) -
从
read_csv()
和read_table()
中删除关键字mangle_dupe_cols
(GH 48137) -
从
DataFrame.where()
、Series.where()
、DataFrame.mask()
和Series.mask()
中删除errors
关键字(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) -
禁止向
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()
传递非关键字参数,除非是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) -
禁止在不传递
data
的情况下构造CategoricalIndex
(GH 38944) -
移除了
Rolling.validate()
、Expanding.validate()
和ExponentialMovingWindow.validate()
(GH 43665) -
移除了
Rolling.win_type
返回的"freq"
(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) -
更改了带有
numeric_only=None
的DataFrame.median()
和DataFrame.mean()
的行为,不再排除类似日期时间的列。一旦弃用numeric_only=None
,此说明将不再相关(GH 29941) -
放弃了
is_extension_type()
,改用is_extension_array_dtype()
(GH 29457) -
移除了
.ExponentialMovingWindow.vol
(GH 39220) -
移除了
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)。 -
在
eval()
中移除了truediv
关键字(GH 29812)。 -
在
Index.get_loc()
中移除了method
和tolerance
参数。使用index.get_indexer([label], method=..., tolerance=...)
代替(GH 42269)。 -
移除了
pandas.datetime
子模块(GH 30489)。 -
移除了
pandas.np
子模块(GH 30296)。 -
使用
pandas.testing
替代了pandas.util.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
()中,禁止传递整数
fill_value`给 datetime64、timedelta64 或 period 类型的 dtype(GH 32591)。 -
在
DataFrame.ewm()
中,禁止将字符串列标签传入times
(GH 43265)。 -
强制禁止在
Series.between()
中将True
和False
传递给inclusive
,改用分别用"both"
和"neither"
代替(GH 40628)。 -
强制禁止在
engine="c"
的情况下使用read_csv
中超出边界索引的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)。 -
强制禁止在
.iloc
上使用DataFrame
索引器,请改用.loc
自动对齐(GH 39022)。 -
在
__getitem__
和__setitem__
方法中强制禁止使用set
或dict
索引器(GH 42825)。 -
强制禁止在
Index
或Series
上进行索引,产生多维对象,例如obj[:, None]
,请在索引之前转换为 numpy (GH 35141)。 -
在
merge()
中强制禁止使用dict
或set
对象作为suffixes
(GH 34810)。 -
强制禁止通过
suffixes
关键字和已存在的列在merge()
中产生重复的列(GH 22818)。 -
强制禁止在不同层级上使用
merge()
或join()
(GH 34862)。 -
强制禁止在
DataFrame.melt()
中将value_name
参数匹配为DataFrame
列中的元素(GH 35003) -
强制禁止在
DataFrame.to_markdown()
和Series.to_markdown()
中将showindex
传递给**kwargs
,而更喜欢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
中的空数据的行为;默认 dtype 将是object
而不是float64
(GH 29405) -
更改了
DatetimeIndex.union()
、DatetimeIndex.intersection()
和DatetimeIndex.symmetric_difference()
的行为,当时区不匹配时转换为 UTC,而不是强制转换为对象 dtype(GH 39328) -
更改了带有参数“now”和
utc=False
的to_datetime()
的行为,以匹配Timestamp("now")
(GH 18705) -
更改了在时区感知的
DatetimeIndex
上进行索引的行为,当给定时区无关的datetime
对象或反之时;现在像任何其他不可比较的类型一样通过引发KeyError
来处理(GH 36148) -
更改了带有
datetime64
dtype 和datetime.date
对象作为fill_value
的Index.reindex()
、Series.reindex()
和DataFrame.reindex()
的行为;这些不再被视为等同于datetime.datetime
对象,因此重新索引会转换为对象 dtype(GH 39767) -
更改了给定非显式
SparseDtype
的 dtype 时SparseArray.astype()
的行为,而不是静默地使用SparseDtype
而是强制转换为精确请求的 dtype(GH 34457) -
更改了
Index.ravel()
的行为,返回原始Index
的视图,而不是np.ndarray
(GH 36900) -
更改了具有显式
name=None
的Series.to_frame()
和Index.to_frame()
的行为,将None
用于列名而不是索引名或默认的0
(GH 45523) -
更改了具有一个
bool
dtype 数组和另一个整数 dtype 数组的concat()
的行为,现在返回object
dtype 而不是整数 dtype;在连接之前,明确将布尔对象转换为整数以获得旧的行为(GH 45101) -
更改了当给定浮点
data
和整数dtype
时DataFrame
构造函数的行为,当数据无法无损转换时,保留浮点 dtype,与Series
的行为相匹配(GH 41170) -
更改了当给定一个包含数值条目的 object-dtype 的
np.ndarray
时Index
构造函数的行为,现在保留 object dtype 而不是推断数值 dtype,与Series
的行为一致(GH 42870) -
更改了
Index.__and__()
,Index.__or__()
和Index.__xor__()
的行为,使其作为逻辑操作(与Series
的行为相匹配),而不是集合操作的别名(GH 37374) -
更改了当传递一个列表且其第一个元素是
Categorical
时,DataFrame
构造函数的行为,现在将这些元素视为行,并转换为object
dtype,与其他类型的行为一致(GH 38845) -
更改了当传递一个
dtype
(除 int 之外)且数据无法转换时DataFrame
构造函数的行为,现在引发异常而不是默默地忽略 dtype(GH 41733) -
更改了
Series
构造函数的行为,它将不再从字符串条目中推断出 datetime64 或 timedelta64 dtype(GH 41731) -
改变了使用
np.datetime64
对象和传递tz
来解释输入为壁钟时间而不是 UTC 时间的Timestamp
构造函数的行为(GH 42288) -
改变了
Timestamp.utcfromtimestamp()
的行为,返回一个满足Timestamp.utcfromtimestamp(val).timestamp() == val
的带时区的对象(GH 45083) -
改变了当传递
SparseArray
或SparseDtype
以保留该数据类型而不是转换为numpy.ndarray
时的Index
构造函数的行为(GH 43930) -
改变了在具有
DatetimeTZDtype
的对象上使用类似于 setitem 的操作(__setitem__
、fillna
、where
、mask
、replace
、insert
、shift
的fill_value
)的行为,当使用具有非匹配时区的值时,该值将被转换为对象的时区而不是同时转换为对象数据类型(GH 44243) -
改变了使用浮点数据类型和
DatetimeTZDtype
的Index
、Series
、DataFrame
构造函数的行为,现在数据被解释为 UTC 时间而不是壁钟时间,与整数数据类型的处理方式一致(GH 45573) -
改变了具有整数数据类型和包含
NaN
的浮点数据的Series
和DataFrame
构造函数的行为,现在会引发IntCastingNaNError
(GH 40110) -
改变了当具有整数
dtype
和值太大无法无损转换为该数据类型时,Series
和DataFrame
构造函数的行为,现在会引发ValueError
(GH 41734) -
更改了带有整数
dtype
和值为datetime64
或timedelta64
dtype 的Series
和DataFrame
构造函数的行为,现在会引发TypeError
,请改用values.view("int64")
。(GH 41770) -
从
pandas.DataFrame.resample()
、pandas.Series.resample()
和pandas.Grouper
中移除了已弃用的base
和loffset
参数。请改用offset
或origin
。(GH 31809) -
更改了对
timedelta64[ns]
dtype 和不兼容的fill_value
的Series.fillna()
和DataFrame.fillna()
的行为;现在将其转换为object
dtype 而不是引发错误,与其他 dtype 的行为一致。(GH 45746) -
将
Series.str.replace()
的默认参数regex
从True
改为False
。另外,现在对于带有regex=True
的单个字符pat
,将其视为正则表达式而不是字符串文字。(GH 36695, GH 24804) -
更改了带有
bool_only=True
的DataFrame.any()
和DataFrame.all()
的行为;所有值为 bool 的 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()
实现样式化输出(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) -
更改了具有不实现
diff
的ExtensionDtype
dtypes 数组的行为,Series.diff()
和DataFrame.diff()
现在引发TypeError
,而不是强制转换为 numpy(GH 31025) -
强制执行了在
DataFrame
上使用method="outer"
调用 numpy“ufunc”时的弃用;现在会引发NotImplementedError
(GH 36955) -
强制执行了不允许将
numeric_only=True
传递给带有非数值 dtype 的Series
reductions(rank
,any
,all
等)的弃用(GH 47500) -
更改了
DataFrameGroupBy.apply()
和SeriesGroupBy.apply()
的行为,因此即使检测到变换器,也会尊重group_keys
(GH 34998) -
当
DataFrame
与Series
进行比较时,如果框架的列与系列的索引不匹配,则会引发ValueError
,而不是自动对齐,因此在比较之前执行left, right = left.align(right, axis=1, copy=False)
(GH 36795) -
强制执行了对在 DataFrame reductions 中默默丢弃引发的列的
numeric_only=None
(默认值)的弃用;numeric_only
现在默认为False
(GH 41480) -
在所有带有该参数的 DataFrame 方法中,将
numeric_only
的默认值更改为False
(GH 46096,GH 46906) -
在
Series.rank()
中将numeric_only
的默认值更改为False
(GH 47561) -
在
numeric_only=False
时,强制废弃在 groupby 和 resample 操作中默默丢弃无用列的行为(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) -
使用带有返回 DataFrame 的可调用对象的方法
DataFrameGroupBy.transform()
将与输入的索引对齐(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()
中的性能提升,适用于可空数据类型(GH 37493) -
在对象数据类型中的
DataFrameGroupBy.all()
、DataFrameGroupBy.any()
、SeriesGroupBy.all()
和SeriesGroupBy.any()
中的性能提升(GH 50623) -
在
MultiIndex.argsort()
和MultiIndex.sort_values()
中的性能提升(GH 48406) -
在
MultiIndex.size()
的性能改进 (GH 48723) -
MultiIndex.difference()
的性能改进 (GH 48606) -
在不进行排序时
MultiIndex
集合操作的性能改进 (GH 49010) -
在
DataFrameGroupBy.mean()
、SeriesGroupBy.mean()
、DataFrameGroupBy.var()
和SeriesGroupBy.var()
扩展数组数据类型的性能改进 (GH 37493) -
MultiIndex.putmask()
的性能改进 (GH 49830) -
在索引包含重复值时
Index.union()
和MultiIndex.union()
的性能改进 (GH 48900) -
在
Series.rank()
针对 pyarrow 支持的数据类型的性能改进 (GH 50264) -
在 pyarrow 支持的数据类型上
Series.searchsorted()
的性能改进 (GH 50447) -
当
Index
是单调的时,对具有掩码和 arrow dtypes 的Index.join()
、Index.intersection()
和Index.union()
的性能有所提升(GH 50310, GH 51365) -
具有可空 dtype 的
Series.value_counts()
的性能有所提升(GH 48338) -
通过传递具有可空 dtype 的整数 numpy 数组构造
Series
的性能有所提升(GH 48338) -
通过传递列表构造
DatetimeIndex
的性能有所提升(GH 48609) -
在对排序的
MultiIndex
进行连接时,merge()
和DataFrame.join()
的性能有所提升(GH 48504) -
在解析带有时区偏移的字符串时,
to_datetime()
的性能有所提升(GH 50107) -
在对基于元组的
MultiIndex
进行索引的DataFrame.loc()
和Series.loc()
的性能有所提升(GH 48384) -
具有分类 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) -
使用类型为
np.str_
的 numpy 数组构造StringArray
时的性能改进(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) -
对可空数据类型的
var
和std
进行了性能改进(GH 48379). -
RangeIndex.sort_values()
在内存方面有所改善(GH 48801) -
如果
copy=True
,则在Series.to_numpy()
中通过避免两次复制来提高性能(GH 24345) -
在使用
MultiIndex
时,Series.rename()
的性能得到了提升(GH 21055) -
当
by
是分类类型且sort=False
时,DataFrameGroupBy
和SeriesGroupBy
的性能得到了提升(GH 48976) -
当
by
是分类类型且observed=False
时,DataFrameGroupBy
和SeriesGroupBy
的性能得到了提升(GH 49596) -
当参数
index_col
设置为None
(默认值)时,read_stata()
的性能得到了提升。现在索引将是RangeIndex
而不是Int64Index
(GH 49745) -
在不在索引上合并时,
merge()
的性能得到了提升 - 新索引现在将是RangeIndex
而不是Int64Index
(GH 49478) -
在使用任何非对象数据类型时,
DataFrame.to_dict()
和Series.to_dict()
的性能得到了提升(GH 46470) -
在存在多个表格时,改进了
read_html()
的性能(GH 49929) -
在从字符串或整数构造时,改进了
Period
构造函数的性能(GH 38312) -
在使用
'%Y%m%d'
格式时,改进了to_datetime()
的性能(GH 17410) -
在给定格式或可以推断时,改进了
to_datetime()
的性能(GH 50465) -
对可空数据类型,改进了
Series.median()
的性能(GH 50838) -
在将
to_datetime()
lambda 函数传递给date_parser
并且输入具有混合时区偏移时,改进了read_csv()
的性能(GH 35296) -
在
isna()
和isnull()
中改进了性能(GH 50658) -
在分类数据类型时,改进了
SeriesGroupBy.value_counts()
的性能(GH 46202) -
修复了在
read_hdf()
中的引用泄漏(GH 37441) -
修复了在序列化日期时间和时间间隔时,
DataFrame.to_json()
和Series.to_json()
中的内存泄漏(GH 40443) -
在许多
DataFrameGroupBy
方法中减少了内存使用量(GH 51090) -
在整数
decimal
参数中改进了DataFrame.round()
的性能(GH 17254) -
在使用大字典作为
to_replace
时DataFrame.replace()
和Series.replace()
中的性能改进(GH 6697) -
在读取可寻址文件时
StataReader
中的内存改进(GH 48922) ## Bug 修复
分类(Categorical)
-
Categorical.set_categories()
中的 Bug 丢失 dtype 信息(GH 48812) -
当
Series.replace()
中的 categorical dtype 的to_replace
值与新值重叠时的 Bug(GH 49404) -
当 categorical dtype 丢失底层类别的可空 dtype 时
Series.replace()
中的 Bug(GH 49404) -
在用作分组键时
DataFrame.groupby()
和Series.groupby()
会重新排序类别的 Bug(GH 48749) -
从
Categorical
对象构造时,构造函数中的 Bug 丢失了 ordered-ness,且dtype="category"
(GH 49309) -
无序
CategoricalDtype
且没有组时,SeriesGroupBy.min()
、SeriesGroupBy.max()
、DataFrameGroupBy.min()
和DataFrameGroupBy.max()
中的 Bug 未能引发TypeError
(GH 51034)
日期时间类(Datetimelike)
-
当在
RangeIndex
上推断时,pandas.infer_freq()
会抛出TypeError
(GH 47084) -
当字符串参数对应于大整数时,
to_datetime()
中的错误不正确地抛出OverflowError
(GH 50533) -
to_datetime()
中的错误,在使用errors='coerce'
和infer_datetime_format=True
时会抛出无效偏移的问题(GH 48633) -
当明确指定
tz=None
与时区感知的dtype
或数据一起使用时,DatetimeIndex
构造函数未能引发错误(GH 48659) -
从
DatetimeIndex
中减去一个datetime
标量会导致原始的freq
属性丢失的错误(GH 48818) -
在
pandas.tseries.holiday.Holiday
中,半开放日期区间导致从USFederalHolidayCalendar.holidays()
返回类型不一致的错误(GH 49075) -
在接近夏令时转换的时候,使用
dateutil
或zoneinfo
时区感知的 dtype 渲染DatetimeIndex
、Series
和DataFrame
时出现错误(GH 49684) -
当解析
Timestamp
、datetime.datetime
、datetime.date
或np.datetime64
对象时传递非 ISO8601format
时,to_datetime()
中的错误会抛出ValueError
(GH 49298, GH 50036) -
当解析空字符串和非 ISO8601 格式时,
to_datetime()
中的错误会抛出ValueError
。现在,空字符串将被解析为NaT
,以兼容对 ISO8601 格式的处理方式(GH 50251) -
当解析非 ISO8601 分隔日期字符串时,
Timestamp
函数显示UserWarning
,用户无法采取行动(GH 50232) -
当解析带有 ISO 周指令和 ISO 工作日指令的格式的日期时,
to_datetime()
函数显示误导性的ValueError
(GH 50308) -
当
freq
参数为零持续时间(例如“0ns”)时,Timestamp.round()
函数返回不正确的结果而不是引发错误(GH 49737) -
当传递无效格式并且
errors
参数为'ignore'
或'coerce'
时,to_datetime()
函数未引发ValueError
(GH 50266) -
当以毫秒构造
DateOffset
且另一个超过日频率的参数时,存在 bug 引发TypeError
(GH 49897) -
当解析带有
'%Y%m%d'
格式的小数日期字符串时,to_datetime()
函数未引发ValueError
(GH 50051) -
to_datetime()
函数中的 bug 在解析混合偏移日期字符串时未将None
转换为NaT
,使用的是 ISO8601 格式(GH 50071) -
当解析超出边界日期字符串时,使用
errors='ignore'
和format='%Y%m%d'
时,to_datetime()
函数未返回输入(GH 14487) -
当解析时区感知字符串、ISO8601 格式和
utc=False
时,to_datetime()
函数将时区无关的datetime.datetime
转换为时区感知的,但存在 bug(GH 50254) -
当解析带有 ISO8601 格式的日期,其中某些值未进行零填充时,
to_datetime()
函数引发ValueError
(GH 21422) -
当使用
format='%Y%m%d'
和errors='ignore'
时,to_datetime()
函数会给出错误的结果(GH 26493) -
to_datetime()
中的错误在未使用 ISO8601 格式时未能解析日期字符串'today'
和'now'
(GH 50359) -
Timestamp.utctimetuple()
中的错误引发了TypeError
(GH 32174) -
当使用
errors='ignore'
解析混合偏移的Timestamp
时,to_datetime()
中的错误会引发ValueError
(GH 50585) -
在溢出边界范围内 1 个
unit
的浮点数输入时,to_datetime()
中的错误会不正确地处理浮点数输入(GH 50183) -
使用“Y”或“M”单位时,
to_datetime()
中的错误会导致不正确的结果,不匹配点对点的Timestamp
结果(GH 50870) -
当 datetime 或 timedelta 数据类型不正确时,
Series.interpolate()
和DataFrame.interpolate()
中的错误会不正确地引发ValueError
(GH 11312) -
当输入超出范围时,
to_datetime()
中的错误未返回errors='ignore'
的输入(GH 50587) -
当给定具有时区感知的 datetime64 列的
DataFrame
输入时,DataFrame.from_records()
中的错误错误地删除了时区感知(GH 51162) -
当使用
errors='coerce'
解析日期字符串时,to_datetime()
中的错误会引发decimal.InvalidOperation
(GH 51084) -
当同时指定
unit
和origin
时,to_datetime()
中的错误返回不正确的结果(GH 42624) -
在将包含时区感知日期时间或字符串的对象类型对象转换为
datetime64[ns]
时,Series.astype()
和DataFrame.astype()
中的错误,不正确地将其本地化为 UTC 而不是引发TypeError
(GH 50140) -
在包含
NaT
的组中,使用日期时间或时间增量类型进行DataFrameGroupBy.quantile()
和SeriesGroupBy.quantile()
时,给出了不正确的结果(GH 51373) -
在具有
PeriodDtype
或DatetimeTZDtype
的情况下,DataFrameGroupBy.quantile()
和SeriesGroupBy.quantile()
不正确地引发错误(GH 51373)
时间增量
-
在输入具有可空类型
Float64
时,to_timedelta()
引发错误(GH 48796) -
Timedelta
构造函数中的错误,当传入np.timedelta64("nat")
时,不正确地引发而不是返回NaT
(GH 48898) -
Timedelta
构造函数中的错误,在传递了Timedelta
对象和关键字(例如天数、秒)时未能引发(GH 48898) -
与非常大的
datetime.timedelta
对象进行比较时,Timedelta
引发错误,错误地引发OutOfBoundsTimedelta
(GH 49021)
时区
-
在包含多个具有异构时区的时区感知
datetime
对象的对象数据类型中,Series.astype()
和DataFrame.astype()
中的错误将不正确地转换为DatetimeTZDtype
(GH 32581) -
在指定
format
为%Z
时,to_datetime()
无法解析带有时区名称的日期字符串的错误(GH 49748) -
在
Timestamp.tz_localize()
中传递无效值给ambiguous
参数时提供更好的错误消息(GH 49565) -
字符串解析中的错误允许使用无效时区构造
Timestamp
,在尝试打印时会引发错误(GH 50668) -
在
objects_to_datetime64ns()
中修正了TypeError
消息,以通知DatetimeIndex
具有混合时区(GH 50974)
数值
-
在
DataFrame.add()
中,当输入包含混合的 DataFrame 类型和 Series 类型时无法应用 ufunc(GH 39853) -
在
Series
上的算术操作中,当组合掩码数据类型和 numpy 数据类型时,未传播掩码的错误(GH 45810,GH 42630) -
在
DataFrame.sem()
和Series.sem()
中,当使用由ArrowDtype
支持的数据时,总是会引发错误的TypeError
([GH 49759](https://github.com/pandas-dev/pandas/issues/49759) -
在
Series.__add__()
中,将列表和掩码Series
转换为对象时会引发错误(GH 22962) -
在
mode()
中,当存在NA
值时未遵守dropna=False
(GH 50982) -
DataFrame.query()
在使用engine="numexpr"
且列名为min
或max
时会引发TypeError
的 bug(GH 50937) -
DataFrame.min()
和DataFrame.max()
在包含pd.NaT
和axis=1
的时区感知数据中存在 bug,会返回不正确的结果(GH 51242)
转换
-
在使用字符串列表构造
int64
dtype 的Series
时,会引发而不是转换的 bug(GH 44923) -
在使用掩码 dtype 和包含
NA
的布尔值构造Series
时会引发 bug(GH 42137) -
DataFrame.eval()
中存在 bug,在函数调用中存在负值时会错误地引发AttributeError
(GH 46471) -
Series.convert_dtypes()
中存在 bug,当Series
包含NA
且 dtype 为object
时,不会将 dtype 转换为可空 dtype(GH 48791) -
任何具有
kind="M"
的ExtensionDtype
子类都会被解释为时区类型的 bug(GH 34986) -
arrays.ArrowExtensionArray
中存在 bug,当传递字符串或二进制序列时,会引发NotImplementedError
(GH 49172) -
Series.astype()
中存在 bug,在从非 pyarrow 字符串 dtype 转换为 pyarrow 数字类型时,会引发pyarrow.ArrowInvalid
(GH 50430) -
DataFrame.astype()
中存在 bug,在转换为string
且copy=False
时,会修改输入数组 inplace(GH 51073) -
在应用
na_value
之前将Series.to_numpy()
转换为 NumPy 数组中的 Bug(GH 48951)。 -
在转换为 pyarrow dtype 时,
DataFrame.astype()
中的 Bug 未复制数据 (GH 50984)。 -
当
format
为 ISO8601 格式时,to_datetime()
中的 Bug 未尊重exact
参数(GH 12649)。 -
TimedeltaArray.astype()
中的 Bug 导致转换为 pyarrow duration 类型时引发TypeError
。 -
DataFrame.eval()
和DataFrame.query()
中出现 Bug,因为扩展数组 dtypes (GH 29618, GH 50261, GH 31913)。 -
从
Index
创建时,Series()
未复制数据,并且dtype
等于从Index
中的dtype
时出现 Bug (GH 52008)。
字符串
-
pandas.api.types.is_string_dtype()
中的 Bug 将不会对StringDtype
或ArrowDtype
以pyarrow.string()
开头的对象返回True
(GH 15585)。 -
将字符串类型转换为“datetime64[ns]”或“timedelta64[ns]”时出现 Bug,错误地引发
TypeError
(GH 36153)。 -
在具有数组的字符串-dtype 列中设置值时出现 Bug,在包含缺失值时会作为副作用改变数组(GH 51299)。
区间
-
当间隔具有重复的左边界时,
IntervalIndex.is_overlapping()
中的 Bug 输出不正确 (GH 49581)。 -
Series.infer_objects()
未能推断出一个对象系列的Interval
对象的IntervalDtype
(GH 50090) -
Series.shift()
在使用IntervalDtype
和无效的空值fill_value
时未能引发TypeError
错误(GH 51258)
索引操作
-
当索引器是具有
boolean
数据类型的DataFrame
时,DataFrame.__setitem__()
引发错误(GH 47125) -
DataFrame.reindex()
在索引列和索引为uint
数据类型时填充错误的值(GH 48184) -
DataFrame.loc()
在设置具有不同数据类型的DataFrame
时将值强制转换为单一数据类型(GH 50467) -
DataFrame.sort_values()
在by
为空列表且inplace=True
时未返回None
(GH 50643) -
DataFrame.loc()
在使用列表索引器设置值时强制转换数据类型的错误(GH 49159) -
Series.loc()
对于超出范围的切片索引器末尾引发错误(GH 50161) -
DataFrame.loc()
在所有False
bool
索引器和空对象时引发ValueError
错误(GH 51450) -
DataFrame.loc()
在使用bool
索引器和MultiIndex
时引发ValueError
错误(GH 47687) -
Bug in
DataFrame.loc()
在为具有非标量索引器的 pyarrow-backed 列设置值时引发IndexError
(GH 50085) -
Bug in
DataFrame.__getitem__()
,Series.__getitem__()
,DataFrame.__setitem__()
和Series.__setitem__()
在使用整数索引具有扩展浮点 dtypes(Float64
和Float64
)或复杂 dtypes 的索引时(GH 51053) -
Bug in
DataFrame.loc()
在使用不兼容值设置空索引器时修改对象(GH 45981) -
Bug in
DataFrame.__setitem__()
当右侧是具有MultiIndex
列的DataFrame
时引发ValueError
(GH 49121) -
Bug in
DataFrame.reindex()
当重新索引columns
和index
时,将 dtype 转换为object
,当DataFrame
具有单个扩展数组列时(GH 48190) -
Bug in
DataFrame.iloc()
当索引器是具有数值扩展数组 dtype 的Series
时引发IndexError
(GH 49521) -
Bug in
describe()
在格式化结果索引中的百分位数时显示比所需更多的小数位数(GH 46362) -
Bug in
DataFrame.compare()
在比较可空 dtypes 中的NA
与值时无法识别差异(GH 48939) -
Bug in
Series.rename()
在使用MultiIndex
时丢失扩展数组 dtypes(GH 21055) -
Bug in
DataFrame.isetitem()
将DataFrame
中的扩展数组 dtypes 强制转换为 object(GH 49922) -
从空的 pyarrow 支持的对象中选择时,
Series.__getitem__()
返回损坏对象的错误已修复 (GH 51734) -
当索引中未包含开放时间时,
BusinessHour
的错误导致创建DatetimeIndex
失败已修复 (GH 49835)
缺失
-
当
Index
包含包含NA
的元组时,Index.equals()
引发TypeError
的错误已修复 (GH 48446) -
当数据中包含 NaN 并且使用 defaultdict 映射时,
Series.map()
引发错误结果的错误已修复 (GH 48813) -
NA
在与bytes
对象进行二进制操作时引发TypeError
而不是返回NA
的错误已修复 (GH 49108) -
当
self
具有带有NaT
值的列且other
中不存在该列时,使用overwrite=False
的DataFrame.update()
引发TypeError
的错误已修复 (GH 16713) -
在对象类型的
Series
中替换包含NA
的值时,Series.replace()
引发RecursionError
已修复 (GH 47480) -
当替换具有
NA
的数值Series
时,Series.replace()
引发RecursionError
的错误已修复 (GH 50758)
多重索引
-
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()
中的错误,丢失扩展数组的数据类型(GH 48606) -
MultiIndex.set_levels
中的错误,在设置空级别时引发IndexError
(GH 48636) -
MultiIndex.unique()
中的错误,丢失扩展数组的数据类型(GH 48335) -
MultiIndex.intersection()
中的错误,丢失扩展数组(GH 48604) -
MultiIndex.union()
中的错误,在 sort=None 且索引包含缺失值时未排序(GH 49010) -
MultiIndex.append()
中的错误,未检查名称是否相等(GH 48288) -
MultiIndex.symmetric_difference()
中的错误,丢失扩展数组(GH 48607) -
MultiIndex.join()
中的错误,当MultiIndex
存在重复时,丢失数据类型(GH 49830) -
MultiIndex.putmask()
中的错误,丢失扩展数组(GH 49830) -
MultiIndex.value_counts()
中的错误,返回一个由元组的平面索引索引的Series
而不是一个MultiIndex
(GH 49558)
I/O
-
read_sas()
中的错误,导致DataFrame
的碎片化,并引发errors.PerformanceWarning
(GH 48595) -
在
read_excel()
中改进错误消息,当读取文件时引发异常时,包含有问题的工作表名称(GH 48706) -
当序列化整个数据而不是子集时,PyArrow 支持的数据的子集会序列化整个数据的 Bug (GH 42600)
-
Bug 在
read_sql_query()
中,当指定chunksize
并且结果为空时,忽略dtype
参数 (GH 50245) -
单行 csv 中
read_csv()
出现的 Bug,列数少于names
时引发errors.ParserError
,使用engine="c"
时 (GH 47566) -
Bug 在
read_json()
中,使用orient="table"
和NA
值时引发异常 (GH 40255) -
显示
string
数据类型的 Bug,未显示存储选项 (GH 50099) -
Bug 在
DataFrame.to_string()
中,使用header=False
时将索引名称打印在与数据的第一行相同的行上 (GH 49230) -
Bug 在
DataFrame.to_string()
中,忽略了扩展数组的浮点格式化程序 (GH 39336) -
修复了内部 JSON 模块初始化引起的内存泄漏 (GH 49222)
-
修复了
json_normalize()
错误地从与sep
参数匹配的列名中错误地删除前导字符的问题 (GH 49861) -
Bug 在
read_csv()
中,包含NA
时无必要溢出扩展数组 dtype (GH 32134) -
Bug 在
DataFrame.to_dict()
中,未将NA
转换为None
(GH 50795) -
Bug 在
DataFrame.to_json()
处,当无法对字符串进行编码时会导致段错误 (GH 50307) -
当
na_rep
被设置时DataFrame
包含非标量数据时,DataFrame.to_html()
中存在一个 Bug (GH 47103) -
当使用 iterparse 时,
read_xml()
中文件样式的对象失败了 (GH 50641) -
当
engine="pyarrow"
时read_csv()
存在一个 Bug,其中encoding
参数未被正确处理 (GH 51302) -
当使用 iterparse 时,
read_xml()
忽略了重复的元素 (GH 51183) -
当实例化期间发生异常时,
ExcelWriter
在例外情况下保留文件句柄的 Bug (GH 51443) -
当
engine="pyarrow"
时,非字符串索引或列引发了ValueError
的 Bug 在DataFrame.to_parquet()
中 (GH 52036)
时间段
-
当传递区域设置特定指令时,在
Period.strftime()
和PeriodIndex.strftime()
中引发了UnicodeDecodeError
的 Bug (GH 46319) -
将
Period
对象添加到DateOffset
对象数组中时,错误地引发了TypeError
的 Bug (GH 50162) -
当传递比纳秒更细的分辨率字符串时,
Period
中会导致KeyError
而不是删除额外精度的 Bug (GH 50417) -
解析字符串表示的周期问题,例如“2017-01-23/2017-01-29”会被解析为分钟频率而不是周频率 (GH 50803)
-
与
PeriodDtype
一起使用的DataFrameGroupBy.sum()
、DataFrameGroupByGroupBy.cumsum()
、DataFrameGroupByGroupBy.prod()
、DataFrameGroupByGroupBy.cumprod()
中的错误未能引发TypeError
(GH 51040) -
解析空字符串时的错误,用
Period
不正确地引发ValueError
,而不是返回NaT
(GH 51349)
绘图
-
在
DataFrame.plot.hist()
中的错误,在data
中NaN
值对应的weights
不会被丢弃 (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) -
当传递空 DataFrame 时,
DataFrameGroupBy.resample()
中的错误会产生不一致的结果 (GH 47705) -
在按分类索引分组时,
DataFrameGroupBy
和SeriesGroupBy
中的错误不会将未观察到的类别包含在结果中 (GH 49354) -
在按分类分组时,
DataFrameGroupBy
和SeriesGroupBy
中的错误会根据输入索引改变结果顺序 (GH 49223) -
当在分类数据上进行分组时,
DataFrameGroupBy
和SeriesGroupBy
中的 Bug 即使与sort=False
一起使用时也会对结果值进行排序 (GH 42482) -
使用
as_index=False
的DataFrameGroupBy.apply()
和SeriesGroupBy.apply
中的 Bug 在使用分组键失败时不会尝试计算而是会引发TypeError
错误 (GH 49256) -
DataFrameGroupBy.describe()
中的 Bug 将描述分组键(GH 49256) -
在
as_index=False
的情况下,SeriesGroupBy.describe()
中的 Bug 会导致形状不正确 (GH 49256) -
当 grouper 为分类数据时,使用
dropna=False
的DataFrameGroupBy
和SeriesGroupBy
中的 Bug 会在分组器是分类时丢弃 NA 值 (GH 36327) -
当 grouper 是空分类且
observed=True
时,SeriesGroupBy.nunique()
中的 Bug 会错误地引发异常 (GH 21334) -
SeriesGroupBy.nth()
中的 Bug 在从DataFrameGroupBy
子集中含有 NA 值的分组器时会引发错误(GH 26454) -
在
as_index=False
的情况下,DataFrame.groupby()
中的 Bug 在结果中不会包含由key
指定的Grouper
(GH 50413) -
DataFrameGroupBy.value_counts()
中的 Bug 在与TimeGrouper
一起使用时会引发错误(GH 50486) -
Resampler.size()
中的 Bug 导致返回宽DataFrame
而不是带有MultiIndex
的Series
(GH 46826) -
DataFrameGroupBy.transform()
和SeriesGroupBy.transform()
中的 Bug 在 grouper 具有axis=1
的情况下,对"idxmin"
和"idxmax"
参数会错误地引发异常(GH 45986) -
DataFrameGroupBy
中的 Bug 在使用空 DataFrame、分类分组器和dropna=False
时会引发错误(GH 50634) -
SeriesGroupBy.value_counts()
中的 Bug 不遵守sort=False
(GH 50482) -
DataFrameGroupBy.resample()
中的 Bug 在对时间索引进行重新采样时,从键列表获取结果时会引发KeyError
(GH 50840) -
DataFrameGroupBy.transform()
和SeriesGroupBy.transform()
中的 Bug 在 grouper 具有axis=1
的情况下,对"ngroup"
参数会错误地引发异常(GH 45986) -
DataFrameGroupBy.describe()
中的 Bug 在数据具有重复列时会产生不正确的结果(GH 50806) -
当
engine="numba"
时,DataFrameGroupBy.agg()
中存在的错误未能尊重as_index=False
(GH 51228) -
当传递函数列表时,
DataFrameGroupBy.agg()
,SeriesGroupBy.agg()
和Resampler.agg()
中存在的错误将忽略参数(GH 50863) -
在忽略
as_index=False
时,DataFrameGroupBy.ohlc()
中存在错误(GH 51413) -
在子集列之后,
DataFrameGroupBy.agg()
中存在的错误(例如.groupby(...)[["a", "b"]]
)将不会在结果中包含分组(GH 51186)
重塑
-
当可空 dtype 和
margins=True
时,DataFrame.pivot_table()
中存在错误引发TypeError
(GH 48681) -
当
MultiIndex
具有混合名称时,DataFrame.unstack()
和Series.unstack()
中存在错误将错误级别解压缩为错误的级别(GH 48763) -
在失去扩展数组 dtype 时,
DataFrame.melt()
存在错误(GH 41570) -
在不尊重
None
作为列名时,DataFrame.pivot()
中存在错误(GH 48293) -
当
left_on
或right_on
为或包含CategoricalIndex
时,DataFrame.join()
中存在错误将不正确地引发AttributeError
(GH 48464) -
在参数
margins=True
时,DataFrame.pivot_table()
存在 bug,当结果是空的DataFrame
时提升ValueError
(GH 49240) -
在传递无效的
validate
选项时,merge()
中澄清的错误消息(GH 49417) -
在具有
NaN
值或空列表的多列上,DataFrame.explode()
存在 bug,提升ValueError
(GH 46084) -
在具有
timedelta64[ns]
端点的IntervalDtype
列中,DataFrame.transpose()
存在 bug(GH 44917) -
在传递函数列表时,
DataFrame.agg()
和Series.agg()
中存在 bug,会忽略参数(GH 50863)
Sparse
-
在将
SparseDtype
的datetime64[ns]
子类型转换为int64
dtype 时,Series.astype()
存在 bug,与非稀疏行为不一致,导致错误提升(GH 49631,:issue:50087) -
在从
datetime64[ns]
转换为Sparse[datetime64[ns]]
时,Series.astype()
存在 bug,错误提升(GH 50082) -
在包含
ExtensionArray
时,Series.sparse.to_coo()
存在 bug��提升SystemError
(GH 50996)
ExtensionArray
-
在可空整数中,
Series.mean()
存在 bug,不必要地溢出(GH 48378) -
在可空数据类型的
Series.tolist()
中存在 bug,返回 numpy 标量而不是 python 标量([GH 49890](https://github.com/pandas-dev/pandas/issues/49890) -
Bug in
Series.round()
对于 pyarrow-backed dtypes 引发AttributeError
(GH 50437) -
当将一个空的 DataFrame 与具有相同 ExtensionDtype 的另一个 DataFrame 连接时,结果的 dtype 变为 object(GH 48510)
-
在
array.PandasArray.to_numpy()
中的一个问题,当指定na_value
时引发NA
值(GH 40638) -
Bug in
api.types.is_numeric_dtype()
中的一个问题,当自定义的ExtensionDtype
返回_is_numeric
为True
时不会返回True
(GH 50563) -
Bug in
api.types.is_integer_dtype()
,api.types.is_unsigned_integer_dtype()
,api.types.is_signed_integer_dtype()
,api.types.is_float_dtype()
中的一个问题,当自定义的ExtensionDtype
返回相应的 NumPy 类型时不会返回True
(GH 50667) -
将非字符串值设置到
StringArray
中引发ValueError
而不是TypeError
(GH 49632) -
Bug in
DataFrame.reindex()
在列具有 ExtensionDtype 的情况下不遵守默认的copy=True
关键字(因此在使用 getitem ([]
) 选择多列时也没有正确地复制)(GH 51197) -
Bug in
ArrowExtensionArray
逻辑操作&
和|
引发KeyError
(GH 51688)
Styler
- 修复了对带有
NA
值的可空 dtypeSeries
的background_gradient()
(GH 50712)
Metadata
- 修复了
DataFrame.corr()
和DataFrame.cov()
中元数据传播的问题(GH 28283)
其他
-
修复了错误地多次接受包含“[pyarrow]”的 dtype 字符串的问题(GH 51548)
-
修复了
Series.searchsorted()
在接受DataFrame
作为参数value
时行为不一致的问题(GH 49620) -
修复了
array()
中的错误,在接受DataFrame
输入时未能引发错误(GH 51167) ## 贡献者
总共有 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) + ## 增强功能
使用 pip extras 安装可选依赖项
安装 pandas 时,可以通过指定额外的参数来安装一组可选的依赖项。
pip install "pandas[performance, aws]>=2.0.0"
可用的额外功能,在安装指南中找到,包括[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 数值数据类型
现在可以在Index
中使用任何 numpy 数值数据类型(GH 42717)。
以前只能使用int64
、uint64
和float64
数据类型:
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 数值数据类型,即int8
/ int16
/int32
/int64
/uint8
/uint16
/uint32
/uint64
/float32
/float64
数据类型:
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 数值数据类型的能力意味着 Pandas 功能上发生了一些变化。特别是,以前被强制创建 64 位索引的操作现在可以创建较低位大小的索引,例如 32 位索引。
以下是可能不完全的更改列表:
-
使用 numpy 数值数组进行实例化现在遵循 numpy 数组的数据类型。以前,从 numpy 数值数组创建的所有索引都被强制为 64 位。现在,例如,在 32 位系统上,
Index(np.array([1, 2, 3]))
将是int32
,而以前即使在 32 位系统上也将是int64
。使用数字列表实例化Index
仍将返回 64 位数据类型,例如Index([1, 2, 3])
将具有int64
数据类型,与以前相同。 -
DatetimeIndex
的各种数值日期时间属性(day
、month
、year
等)以前的数据类型是int64
,而在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()
中的索引级别 dtype 现在是int32
,与 scipy 稀疏矩阵上的rows
/cols
相同。之前它们的 dtype 是int64
。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
。以前使用 dtypefloat16
实例化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-backed 或 numpy-backed 可空 dtype
以下函数增加了一个新关键字 dtype_backend
(GH 36712)
-
read_csv()
-
read_clipboard()
-
read_fwf()
-
read_excel()
-
read_html()
-
read_xml()
-
read_json()
-
read_sql()
-
read_sql_query()
-
read_sql_table()
-
read_parquet()
-
read_orc()
-
read_feather()
-
read_spss()
-
to_numeric()
-
DataFrame.convert_dtypes()
-
Series.convert_dtypes()
当此选项设置为 "numpy_nullable"
时,将返回一个由可空 dtype 支持的 DataFrame
。
当此关键字设置为"pyarrow"
时,这些函数将返回由 pyarrow 支持的可空ArrowDtype
数据帧(GH 48957, GH 49997):
-
read_csv()
-
read_clipboard()
-
read_fwf()
-
read_excel()
-
read_html()
-
read_xml()
-
read_json()
-
read_sql()
-
read_sql_query()
-
read_sql_table()
-
read_parquet()
-
read_orc()
-
read_feather()
-
read_spss()
-
to_numeric()
-
DataFrame.convert_dtypes()
-
Series.convert_dtypes()
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 的单个列(例如
df["col"]
)访问为 Series 现在每次构建时都会返回一个新对象(不会多次返回相同的缓存的 Series 对象)。这确保了这些 Series 对象正确遵循写时复制规则(GH 49450) -
Series
构造函数现在将在从现有 Series 构造 Series 时创建延迟复制(直到数据发生修改时才复制)的默认行为为copy=False
(GH 50471) -
DataFrame
构造函数现在将在从现有DataFrame
构造时创建延迟复制(直到数据发生修改时才复制)的默认行为为copy=False
(GH 51239) -
DataFrame
构造函数,在从字典的 Series 对象构造 DataFrame 且指定copy=False
时,现在将使用这些 Series 对象的延迟复制作为 DataFrame 的列 (GH 50777) -
DataFrame
构造函数,在从Series
或Index
构造 DataFrame 且指定copy=False
时,现在将尊重写时复制。 -
DataFrame
和Series
构造函数,在从 NumPy 数组构造时,默认情况下现在会复制数组,以避免在修改数组时改变DataFrame
/Series
。指定copy=False
可以获得旧的行为。当设置copy=False
时,pandas 在创建DataFrame
/Series
后修改 NumPy 数组时不保证正确的写时复制行为。 -
DataFrame.from_records()
现在在与DataFrame
一起调用时将尊重写时复制。 -
当启用写时复制时,尝试使用链式赋值设置值(例如,
df["a"][1:3] = 0
)将始终在启用写时复制时引发警告。在此模式下,链式赋值永远无法工作,因为我们总是设置到一个索引操作(getitem)的临时对象中,而在写时复制下,这总是表现为复制。因此,会向用户发出信息性警告,以避免悄悄地什么都不做 (GH 49467) -
DataFrame.replace()
现在在inplace=True
时会尊重写时复制机制。 -
DataFrame.transpose()
现在会尊重写时复制机制。 -
可以原地进行的算术操作,例如
ser *= 2
现在会尊重写时复制机制。 -
DataFrame.__getitem__()
现在在具有MultiIndex
列的DataFrame
时会尊重写时复制机制。 -
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):
...
其他增强
-
当使用
pyarrow.string
类型时,通过ArrowDtype
支持str
访问器方法 (GH 50325) -
当使用
pyarrow.timestamp
类型时,通过ArrowDtype
支持dt
访问器方法 (GH 50954) -
read_sas()
现在支持使用encoding='infer'
来正确读取和使用 sas 文件指定的编码。(GH 48048) -
DataFrameGroupBy.quantile()
,SeriesGroupBy.quantile()
和DataFrameGroupBy.std()
现在保留可空 dtypes 而不是转换为 numpy dtypes (GH 37493) -
DataFrameGroupBy.std()
,SeriesGroupBy.std()
现在支持 datetime64、timedelta64 和DatetimeTZDtype
dtypes (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) -
在
merge()
中添加了对扩展数组 dtypes 的支持(GH 44240) -
为
DataFrame
上的二元运算符添加了元数据传播(GH 28283) -
通过
_accumulate
将cumsum
、cumprod
、cummin
和cummax
添加到ExtensionArray
接口中 (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”, or “ns”) 以指定输出索引的所需分辨率 (GH 49106) -
timedelta_range()
现在支持unit
关键字 (“s”, “ms”, “us”, or “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) -
当使用
testing.assert_frame_equal()
对DataFrame
进行比较时,改进了异常消息以包括被比较的列(GH 50323) -
在 join-columns 重复时,改进了
merge_asof()
的错误消息(GH 50102) -
为
get_dummies()
添加了对扩展数组数据类型的支持(GH 32430) -
添加了类似于
Series.infer_objects()
的Index.infer_objects()
(GH 50034) -
在
Series.infer_objects()
和DataFrame.infer_objects()
中添加了copy
参数,传递False
将避免对已经是非对象或无法推断出更好数据类型的系列或列进行复制(GH 50096) -
DataFrame.plot.hist()
现在能够识别xlabel
和ylabel
参数(GH 49793) -
Series.drop_duplicates()
添加了ignore_index
关键字以重置索引(GH 48304) -
Series.dropna()
和DataFrame.dropna()
添加了ignore_index
关键字以重置索引(GH 31725) -
在非 ISO8601 格式的
to_datetime()
中改进了错误消息,通知用户第一个错误的位置(GH 50361) -
当尝试对齐
DataFrame
对象时(例如在DataFrame.compare()
中),改进了错误消息以阐明“标签相同”是指索引和列都相同 (GH 50083) -
为 pyarrow 字符串类型添加了对
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"
来解析 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) ### 使用 pip 额外功能安装可选依赖项
使用 pip 安装 pandas 时,还可以通过指定额外功能来安装一组可选依赖项。
pip install "pandas[performance, aws]>=2.0.0"
可用的额外功能在安装指南中找到,包括[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 数值数据类型
现在可以在Index
中使用任何 numpy 数值数据类型(GH 42717)
以前只能使用int64
、uint64
和float64
数据类型:
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 数值数据类型,即int8
/ int16
/int32
/int64
/uint8
/uint16
/uint32
/uint64
/float32
/float64
数据类型:
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 数值数组实例化现在遵循 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
等)以前的 dtype 是int64
,而它们在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()
创建的索引的级别 dtype 现在是int32
,与 scipy 稀疏矩阵的rows
/cols
上的 dtype 相同。以前它们的 dtype 是int64
。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
。以前使用 dtypefloat16
实例化Index
会导致具有float64
dtype 的Float64Index
。现在会引发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)
-
read_csv()
-
read_clipboard()
-
read_fwf()
-
read_excel()
-
read_html()
-
read_xml()
-
read_json()
-
read_sql()
-
read_sql_query()
-
read_sql_table()
-
read_parquet()
-
read_orc()
-
read_feather()
-
read_spss()
-
to_numeric()
-
DataFrame.convert_dtypes()
-
Series.convert_dtypes()
当此选项设置为"numpy_nullable"
时,将返回由可空数据类型支持的DataFrame
。
当设置此关键词为"pyarrow"
时,这些函数将返回以 pyarrow 支持的可空ArrowDtype
数据帧(GH 48957,GH 49997):
-
read_csv()
-
read_clipboard()
-
read_fwf()
-
read_excel()
-
read_html()
-
read_xml()
-
read_json()
-
read_sql()
-
read_sql_query()
-
read_sql_table()
-
read_parquet()
-
read_orc()
-
read_feather()
-
read_spss()
-
to_numeric()
-
DataFrame.convert_dtypes()
-
Series.convert_dtypes()
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
构造函数现在会对 DataFrame 的列使用这些 Series 对象的延迟复制 (GH 50777) -
当从 Series 或 Index 构造 DataFrame 并指定
copy=False
时,DataFrame
构造函数现在会尊重写时复制。 -
当从 NumPy 数组构造时,
DataFrame
和Series
构造函数现在默认会复制数组,以避免在修改数组时改变DataFrame
/Series
。指定copy=False
以获得旧的行为。当设置copy=False
时,pandas 不保证在创建DataFrame
/Series
后修改 NumPy 数组时正确的写时复制行为。 -
当使用
DataFrame.from_records()
与DataFrame
调用时,现在将遵循写时复制。 -
当启用写时复制时,尝试使用链式赋值设置值(例如,
df["a"][1:3] = 0
)将始终引发警告。在此模式下,链式赋值永远无法工作,因为我们始终设置到一个临时对象中,该对象是索引操作的结果(getitem),在写时复制下始终行为为复制。因此,向链式赋值中赋值永远不会更新原始的 Series 或 DataFrame。因此,将向用户发出信息性警告,以避免悄悄地什么也不做 (GH 49467)。 -
DataFrame.replace()
中inplace=True
时将遵循写时复制机制。 -
DataFrame.transpose()
现在将遵循写时复制机制。 -
可以进行就地操作的算术运算,例如
ser *= 2
现在将遵循写时复制机制。 -
DataFrame.__getitem__()
现在在具有MultiIndex
列的DataFrame
上将遵循写时复制机制。 -
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()
现在会保留可空数据类型,而不是强制转换为 numpy 数据类型。 (GH 37493) -
DataFrameGroupBy.std()
、SeriesGroupBy.std()
现在支持 datetime64、timedelta64 和DatetimeTZDtype
数据类型。 (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) -
在
merge()
中增加了对扩展数组数据类型的支持 (GH 44240) -
在
DataFrame
上的二元运算符增加了元数据传播 (GH 28283) -
通过
_accumulate
在ExtensionArray
接口中增加了cumsum
,cumprod
,cummin
和cummax
(GH 28385) -
CategoricalConversionWarning
,InvalidComparison
,InvalidVersion
,LossySetitemError
, 和NoBufferPresent
现在在pandas.errors
中公开 (GH 27656) -
通过添加缺少的测试包
pytest-asyncio
修复了test
可选的额外内容 (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()
现在支持带有支持的输入 'w' 和 'a' 的mode
关键字。默认为 'w',当lines=True
和orient='records'
时,可以使用 'a' 将面向记录的 JSON 行追加到现有的 JSON 文件中(GH 35849) -
在
IntervalIndex.from_breaks()
、IntervalIndex.from_arrays()
和IntervalIndex.from_tuples()
中添加了name
参数(GH 48911) -
改进了在使用
testing.assert_frame_equal()
对DataFrame
进行比较时的异常消息,包括进行比较的列名(GH 50323) -
当连接列重复时,改进了
merge_asof()
的错误消息(GH 50102) -
为
get_dummies()
添加了对扩展数组 dtype 的支持(GH 32430) -
添加了类似于
Series.infer_objects()
的Index.infer_objects()
(GH 50034) -
在
Series.infer_objects()
和DataFrame.infer_objects()
中添加了copy
参数,传递False
将避免为已经是非对象或无法推断更好的 dtype 的系列或列制作副本(GH 50096) -
DataFrame.plot.hist()
现在识别xlabel
和ylabel
参数 (GH 49793) -
Series.drop_duplicates()
已添加ignore_index
关键字以重置索引(GH 48304) -
Series.dropna()
和DataFrame.dropna()
已添加ignore_index
关键字以重置索引(GH 31725) -
在非 ISO8601 格式的
to_datetime()
中改进了错误消息,告知用户第一个错误的位置(GH 50361) -
当尝试对齐
DataFrame
对象(例如,在DataFrame.compare()
中)时,改进了错误消息以澄清“标签相同”指的是索引和列都相同(GH 50083) -
为 pyarrow 字符串数据类型添加了对
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"
解析 JSON(GH 48893) -
增加了对 SQLAlchemy 2.0 的支持(GH 40686)
-
在
engine="pyarrow"
中的read_csv()
中添加了对decimal
参数的支持(GH 51302) -
Index
集合操作Index.union()
,Index.intersection()
,Index.difference()
, 和Index.symmetric_difference()
现在支持sort=True
,这将始终返回一个排序结果,不像默认的sort=None
在某些情况下不会排序(GH 25151) -
添加了新的转义模式“latex-math”以避免在格式化器中转义“$”(GH 50040)
显著的错误修复
这些是可能具有显著行为变化的错误修复。
DataFrameGroupBy.cumsum()
和 DataFrameGroupBy.cumprod()
溢出而不是强制转换为浮点数
在先前的版本中,当应用cumsum
和cumprod
时,我们会强制转换为浮点数,这会导致即使结果可以由int64
类型保持也会得到不正确的结果。此外,当达到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
我们返回了第 6 个值的不正确结果。
新行为
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
我们在第 7 个值处溢出,但第 6 个值仍然是正确的。 ### 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: []
``` ### `DataFrameGroupBy.cumsum()` 和 `DataFrameGroupBy.cumprod()` 在溢出时不再进行损失性地转换为浮点数。
在早期版本中,我们在应用 `cumsum` 和 `cumprod` 时转换为浮点数,这导致即使结果可以由 `int64` dtype 保持,也会得到不正确的结果。此外,当达到 `int64` 限制时,聚合溢出与 numpy 和常规的 `DataFrame.cumprod()` 和 `DataFrame.cumsum()` 方法一致([GH 37493](https://github.com/pandas-dev/pandas/issues/37493))。
*旧行为*
```py
In [1]: df = pd.DataFrame({"key": ["b"] * 7, "value": 625})
In [2]: df.groupby("key")["value"].cumprod()[5]
Out[2]: 5.960464477539062e+16
我们返回第 6 个值的不正确结果。
新行为
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
我们在第 7 个值处溢出,但第 6 个值仍然是正确的。
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
并传递“datetime64”或“timedelta64” dtype,但分辨率不受支持时(即除了“ns”以外的任何内容),pandas 会悄悄地用其纳秒模拟替换给定的 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:1219, in maybe_cast_to_datetime(value, dtype)
1215 raise TypeError("value must be listlike")
1217 # TODO: _from_sequence would raise ValueError in cases where
1218 # _ensure_nanosecond_dtype raises TypeError
-> 1219 _ensure_nanosecond_dtype(dtype)
1221 if lib.is_np_dtype(dtype, "m"):
1222 res = TimedeltaArray._from_sequence(value, dtype=dtype)
File ~/work/pandas/pandas/pandas/core/dtypes/cast.py:1276, in _ensure_nanosecond_dtype(dtype)
1273 raise ValueError(msg)
1274 # TODO: ValueError or TypeError? existing test
1275 # test_constructor_generic_timestamp_bad_frequency expects TypeError
-> 1276 raise TypeError(
1277 f"dtype={dtype} is not supported. Supported resolutions are 's', "
1278 "'ms', 'us', and 'ns'"
1279 )
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](https://github.com/pandas-dev/pandas/issues/49497))。
*之前的行为*:
```py
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()
),同样禁止转换为不受支持的 datetime64/timedelta64 dtypes
在之前的版本中,将Series
或DataFrame
从datetime64[ns]
转换为不同的datetime64[X]
dtype 会返回datetime64[ns]
dtype,而不是请求的 dtype。在 pandas 2.0 中,添加了对“datetime64[s]”、“datetime64[ms]”和“datetime64[us]” dtypes 的支持,因此转换为这些 dtypes 将确切地给出所请求的 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](https://github.com/pandas-dev/pandas/issues/34916))
*以前的行为*:
```py
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
),将返回对象 dtype 为空的空轴。
现在,轴返回一个空的 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 to 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` 仅在使用 JupyterNotebook 的 nbconvert 时生成 LaTeX,并且当用户运行笔记本时不会生成。现在,`styler.render.repr` 选项允许控制在操作期间(不仅在 nbconvert 上)在 JupyterNotebooks 中生成特定输出。参见[GH 39911](https://github.com/pandas-dev/pandas/issues/39911)。 ### 增加了依赖项的最低版本
更新了一些依赖项的最低支持版本。如果安装,现在我们要求:
| 包名 | 最低版本 | 必须 | 已更改 |
| --- | --- | --- | --- |
| mypy (dev) | 1.0 | | X |
| pytest (dev) | 7.0.0 | | X |
| pytest-xdist (dev) | 2.2.0 | | X |
| hypothesis (dev) | 6.34.2 | | X |
| python-dateutil | 2.8.2 | X | X |
| tzdata | 2022.1 | X | X |
对于[可选库](https://pandas.pydata.org/docs/getting_started/install.html),一般建议使用最新版本。以下表格列出了在 pandas 开发过程中当前正在测试的每个库的最低版本。低于最低测试版本的可选库可能仍然可用,但不被视为受支持的。
| 包名 | 最低版本 | 已更改 |
| --- | --- | --- |
| pyarrow | 7.0.0 | X |
| matplotlib | 3.6.1 | X |
| fastparquet | 0.6.3 | X |
| xarray | 0.21.0 | X |
更多信息请参见依赖项和可选依赖项。
### 现在使用一致的格式解析日期时间
以前,`to_datetime()` 会为每个元素独立地猜测格式。这对于一些元素具有混合日期格式的情况是合适的 - 但是,当用户期望一致的格式时,该函数会在元素之间切换格式,导致问题。从版本 2.0.0 开始,解析将使用一致的格式,由第一个非 NA 值确定(除非用户指定了格式,在这种情况下将使用该格式)。
*旧行为*:
```py
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
中,传递的nanoseconds
大于 999 或小于 0 现在会引发ValueError
(GH 48538, GH 48255) -
在
read_csv()
中,使用 c 解析器时,通过index_col
指定的列数不正确现在会引发ParserError
而不是在出现IndexError
时(GH 49715) -
在
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”类型(GH 48963) -
DatetimeIndex.astype()
,TimedeltaIndex.astype()
,PeriodIndex.astype()
Series.astype()
,DataFrame.astype()
现在不再允许将datetime64
,timedelta64
或PeriodDtype
类型的对象转换为除了“int64”以外的整数类型,而是应该使用obj.astype('int64', copy=False).astype(dtype)
(GH 49715) -
Index.astype()
现在允许从float64
类型转换为类似 datetime 的类型,与Series
的行为一致(GH 49660) -
将“timedelta64[s]”、“timedelta64[ms]”或“timedelta64[us]”的
dtype
数据传递给TimedeltaIndex
、Series
或DataFrame
构造函数现在将保留该dtype
,而不是转换为“timedelta64[ns]”;具有较低分辨率的 timedelta64 数据将被转换为最低支持的分辨率“timedelta64[s]”(GH 49014) -
将“timedelta64[s]”、“timedelta64[ms]”或“timedelta64[us]”的
dtype
传递给TimedeltaIndex
、Series
或DataFrame
构造函数现在将保留该dtype
,而不是转换为“timedelta64[ns]”;将具有较低分辨率的dtype
传递给Series
或DataFrame
的数据将被转换为最低支持的分辨率“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
,与DataFrame.where()
和Series.where()
保持一致。条目将填充相应的 NULL 值(对于 numpy 数据类型为np.nan
,对于扩展数据类型为pd.NA
)。(GH 49111) -
Series.quantile()
和DataFrame.quantile()
函数的行为已更改,现在会保留稀疏数据类型SparseDtype
。(GH 49583) -
当创建一个具有 datetime 对象的对象数据类型
Index
的Series
时,pandas 不再将索引悄悄地转换为DatetimeIndex
。(GH 39307, GH 23598) -
pandas.testing.assert_index_equal()
函数的exact="equiv"
参数现在在两个索引都是RangeIndex
或Index
且具有int64
数据类型时将它们视为相等。之前它指的是RangeIndex
或Int64Index
。(GH 51098) -
Series.unique()
函数对于数据类型为 “timedelta64[ns]” 或 “datetime64[ns]” 的唯一值现在返回TimedeltaArray
或DatetimeArray
而不是numpy.ndarray
。(GH 49176) -
to_datetime()
和DatetimeIndex
现在允许包含datetime
对象和数值输入的序列,与Series
的行为相匹配(GH 49037, GH 50453) -
pandas.api.types.is_string_dtype()
现在只有在推断元素为字符串时才会对dtype=object
的数组返回True
(GH 15585) -
将包含
datetime
对象和date
对象的序列传递给Series
构造函数将返回object
dtype 而不是datetime64[ns]
dtype,与Index
的行为一致(GH 49341) -
将无法解析为日期时间的字符串传递给
dtype="datetime64[ns]"
的Series
或DataFrame
将引发错误而不是在静默忽略关键字并返回object
dtype(GH 24435) -
将包含无法转换为
Timedelta
的类型的序列传递给to_timedelta()
或者以dtype="timedelta64[ns]"
形式传递给Series
或DataFrame
构造函数,或者传递给TimedeltaIndex
现在会引发TypeError
而不是ValueError
(GH 49525) -
将包含至少一个
NaT
和其他全部为None
或NaN
的序列传递给Index
构造函数的行为已更改,现在会推断为datetime64[ns]
dtype 而不是object
,与Series
的行为一致(GH 49340) -
使用参数
index_col
设置为None
(默认值)的read_stata()
现在将返回的DataFrame
的索引设置为RangeIndex
而不是Int64Index
(GH 49745) -
更改了在处理对象 dtype 时
Index
、Series
和DataFrame
的算术方法的行为,结果不再对数组操作的结果进行类型推断,使用result.infer_objects(copy=False)
对结果进行类型推断(GH 49999, GH 49714) -
更改了使用包含全部
bool
值或全部复数值的对象 dtypenumpy.ndarray
构造函数的行为,现在将保留对象 dtype,与Series
的行为一致(GH 49594) -
更改了
Series.astype()
的行为,从包含bytes
对象的对象 dtype 更改为字符串 dtype;现在对字节对象执行val.decode()
而不是str(val)
,与Index.astype()
的行为相匹配(GH 45326) -
在
read_csv()
的默认na_values
中添加了"None"
(GH 50286) -
更改了当给定整数 dtype 和不是整数的浮点数据时
Series
和DataFrame
构造函数的行为,现在会引发ValueError
而不是悄悄保留浮点 dtype;使用Series(data)
或DataFrame(data)
来获得旧的行为,并使用Series(data).astype(dtype)
或DataFrame(data).astype(dtype)
来获得指定的 dtype(GH 49599) -
当
axis=1
、整数fill_value
和同质日期时间样式 dtype 时,DataFrame.shift()
的行为发生了变化,现在将新列填充为整数 dtype,而不是转换为日期时间类型(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
在两个轴上进行全切片创建新的 DataFrame(因此,df.loc[:, :]
或df.iloc[:, :]
)现在返回一个新的 DataFrame(浅拷贝),而不是原始的 DataFrame,与其他获取全切片的方法保持一致(例如df.loc[:]
或df[:]
)(GH 49469) -
当传递一个 Series 和 DataFrame 时,
Series
和DataFrame
构造函数现在将返回一个浅拷贝(即共享数据,但不共享属性),默认情况下为copy=False
(如果没有其他关键字触发拷贝)。先前,新的 Series 或 DataFrame 会共享索引属性(例如df.index = ...
也会更新父级或子级的索引)(GH 49523) -
不允许为
Timedelta
对象计算cumprod
;先前这会返回不正确的值(GH 50246) -
从
HDFStore
文件读取的DataFrame
对象如果没有索引,现在将具有RangeIndex
而不是int64
索引(GH 51076) -
使用包含
NA
和/或NaT
数据的数值 numpy dtype 实例化Index
现在会引发ValueError
。先前会引发TypeError
(GH 51050) -
使用
read_json(orient='split')
加载具有重复列的 JSON 文件会重命名列以避免重复,就像read_csv()
和其他读取器一样做(GH 50370) -
从
Series.sparse.from_coo
返回的Series
索引的级别现在始终具有int32
类型。先前它们具有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) -
DataFrame
和DataFrameGroupBy
聚合(例如“sum”)不再为其结果推断非对象数据类型列,显式调用result.infer_objects(copy=False)
以获得旧行为(GH 51205,GH 49603) -
使用
ArrowDtype
数据类型进行除以零将返回-inf
,nan
或inf
,而不是引发异常(GH 51541) -
添加了
pandas.api.types.is_any_real_numeric_dtype()
以检查真实数值类型(GH 51152) -
value_counts()
现在返回具有pyarrow.int64
类型的ArrowDtype
数据,而不是"Int64"
类型(GH 51462) -
在传入具有非纳秒分辨率的 numpy timedelta64 或 datetime64 时,
factorize()
和unique()
保留原始数据类型(GH 48670)
注意
当前的 PDEP 提议弃用并删除 pandas API 中除了一小部分方法之外的所有关键字inplace
和copy
。当前的讨论发生在这里。在写时复制的上下文中,这两个关键字将不再必要。如果这个提案被接受,那么这两个关键字将在下一个 pandas 版本中被弃用,并在 pandas 3.0 中被移除。### 使用不支持的分辨率构造 datetime64 或 timedelta64 dtype
在以前的版本中,当构造一个Series
或DataFrame
并传递一个具有不支持的分辨率的“datetime64”或“timedelta64” dtype(即除了“ns”之外的任何东西)时,pandas 会默默地用其纳秒模拟替换给定的 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:1219, in maybe_cast_to_datetime(value, dtype)
1215 raise TypeError("value must be listlike")
1217 # TODO: _from_sequence would raise ValueError in cases where
1218 # _ensure_nanosecond_dtype raises TypeError
-> 1219 _ensure_nanosecond_dtype(dtype)
1221 if lib.is_np_dtype(dtype, "m"):
1222 res = TimedeltaArray._from_sequence(value, dtype=dtype)
File ~/work/pandas/pandas/pandas/core/dtypes/cast.py:1276, in _ensure_nanosecond_dtype(dtype)
1273 raise ValueError(msg)
1274 # TODO: ValueError or TypeError? existing test
1275 # test_constructor_generic_timestamp_bad_frequency expects TypeError
-> 1276 raise TypeError(
1277 f"dtype={dtype} is not supported. Supported resolutions are 's', "
1278 "'ms', 'us', and 'ns'"
1279 )
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 的支持,因此转换为这些 dtypes 会准确地给出请求的 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]
数据类型进行转换,旧行为转换为浮点格式。
先前的行为:
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 相同,要么给出完全请求的数据类型,要么引发异常:
新行为:
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
)将返回轴为空的对象Index
,带有对象 dtype。
现在,轴返回一个空的 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
会在使用 JupyterNotebook 的 nbconvert 时生成 LaTeX,而在用户运行笔记本时不会生成。现在styler.render.repr
选项允许控制 JupyterNotebooks 中特定操作的输出(不仅仅是在 nbconvert 上)。参见GH 39911。
提高了依赖项的最低版本
一些依赖项的最低支持版本已更新。如果安装了,我们现在要求:
Package | Minimum Version | Required | Changed |
---|---|---|---|
mypy (dev) | 1.0 | X | |
pytest (dev) | 7.0.0 | X | |
pytest-xdist (dev) | 2.2.0 | X | |
hypothesis (dev) | 6.34.2 | X | |
python-dateutil | 2.8.2 | X | X |
tzdata | 2022.1 | X | X |
对于可选库,一般建议使用最新版本。以下表格列出了在 pandas 开发过程中当前正在测试的每个库的最低版本。低于最低测试版本的可选库可能仍然可用,但不被认为是受支持的。
Package | Minimum Version | Changed |
---|---|---|
pyarrow | 7.0.0 | X |
matplotlib | 3.6.1 | X |
fastparquet | 0.6.3 | X |
xarray | 0.21.0 | X |
有关更多信息,请参见依赖项和可选依赖项。
现在使用一致的格式解析日期时间
在过去,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”数据类型 (GH 48963) -
DatetimeIndex.astype()
、TimedeltaIndex.astype()
、PeriodIndex.astype()
、Series.astype()
、DataFrame.astype()
在使用datetime64
、timedelta64
或PeriodDtype
数据类型时,不再允许转换为除“int64”之外的整数数据类型,而是应该使用obj.astype('int64', copy=False).astype(dtype)
(GH 49715) -
Index.astype()
现在允许从float64
dtype 转换为类似于 datetime 的 dtypes,与Series
的行为相匹配(GH 49660) -
将 dtype 为“timedelta64[s]”、“timedelta64[ms]”或“timedelta64[us]”的数据传递给
TimedeltaIndex
、Series
或DataFrame
构造函数将保留该 dtype,而不是转换为“timedelta64[ns]”;具有较低分辨率的 timedelta64 数据将被转换为最低支持的分辨率“timedelta64[s]”(GH 49014) -
将“timedelta64[s]”、“timedelta64[ms]”或“timedelta64[us]”的 dtype 传递给
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) -
改变了带有
SparseDtype
的Series.quantile()
和DataFrame.quantile()
的行为,以保留稀疏 dtype (GH 49583) -
当使用对象 dtype 的 datetime 对象创建一个带有
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
且元素被推断为字符串时返回True
(GH 15585) -
将包含
datetime
对象和date
对象的序列传递给Series
构造函数将返回object
dtype 而不是datetime64[ns]
dtype,与Index
的行为一致(GH 49341) -
将无法解析为日期时间的字符串传递给带有
dtype="datetime64[ns]"
的Series
或DataFrame
将引发错误,而不是默默地忽略关键字并返回object
dtype(GH 24435) -
将无法转换为
Timedelta
的类型传递给to_timedelta()
,或传递给dtype="timedelta64[ns]"
的Series
或DataFrame
构造函数,或传递给TimedeltaIndex
,现在会引发TypeError
而不是ValueError
(GH 49525) -
修改了当序列包含至少一个
NaT
并且其他所有元素要么为None
要么为NaN
时,Index
构造函数的行为,以推断datetime64[ns]
dtype 而不是object
,与Series
的行为匹配(GH 49340) -
当参数
index_col
设置为None
(默认值)时,read_stata()
现在会将返回的DataFrame
的索引设置为RangeIndex
而不是Int64Index
(GH 49745) -
改变了当处理对象 dtype 时
Index
、Series
和DataFrame
算术方法的行为,结果不再对数组操作的结果进行类型推断,使用result.infer_objects(copy=False)
对结果进行类型推断 (GH 49999, GH 49714) -
使用包含全
bool
值或全复数值的对象 dtypenumpy.ndarray
的Index
构造函数的行为已更改,现在将保留对象 dtype,与Series
行为一致 (GH 49594) -
将包含
bytes
对象的对象 dtype 的Series.astype()
行为更改为字符串 dtype;现在对字节对象执行val.decode()
而不是str(val)
,与Index.astype()
行为匹配 (GH 45326) -
在
read_csv()
中默认na_values
添加了"None"
(GH 50286) -
改变了当给定整数 dtype 和非整数数据时
Series
和DataFrame
构造函数的行为,现在会引发ValueError
而不是悄悄地保留浮点 dtype;使用Series(data)
或DataFrame(data)
来获得旧的行为,使用Series(data).astype(dtype)
或DataFrame(data).astype(dtype)
来获得指定的 dtype (GH 49599) -
DataFrame.shift()
方法在axis=1
、整数fill_value
和同质日期时间类型的情况下的行为已更改,现在会用整数 dtype 填充新列,而不是转换为日期时间类(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
在两个轴上进行完整切片创建新的 DataFrame(因此,df.loc[:, :]
或df.iloc[:, :]
)现在返回一个新的 DataFrame(浅复制),而不是原始 DataFrame,与其他获取完整切片的方法一致(例如df.loc[:]
或df[:]
)(GH 49469) -
构造函数
Series
和DataFrame
现在在传入 Series 和 DataFrame 时将返回浅拷贝(即共享数据,但不共享属性),默认情况下为copy=False
(如果没有其他关键字触发拷贝)。以前,新的 Series 或 DataFrame 会共享索引属性(例如,df.index = ...
也会更新父项或子项的索引)(GH 49523) -
不允许为
Timedelta
对象计算cumprod
;以前这会返回不正确的值(GH 50246) -
从
HDFStore
文件中读取的DataFrame
对象如果没有索引,则现在将具有RangeIndex
而不是int64
索引(GH 51076) -
使用包含
NA
和/或NaT
的数据实例化具有数值 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) -
使用“Y”或“M”作为
unit
的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) -
对于具有对象类型列的
DataFrame
和DataFrameGroupBy
聚合(例如“sum”),不再为其结果推断非对象类型,显式调用result.infer_objects(copy=False)
来获得旧行为 (GH 51205, GH 49603) -
使用
ArrowDtype
dtypes 进行除以零操作将返回-inf
、nan
或inf
,而不是抛出异常 (GH 51541) -
添加了
pandas.api.types.is_any_real_numeric_dtype()
来检查实数数字 dtypes (GH 51152) -
value_counts()
现在返回具有pyarrow.int64
类型而不是"Int64"
类型的数据,其中ArrowDtype
(GH 51462) -
当传递具有非纳秒分辨率的 numpy timedelta64 或 datetime64 时,
factorize()
和unique()
保留原始 dtype (GH 48670)
注意
当前的 PDEP 建议从 pandas API 中除了一小部分方法外,弃用并删除关键字 inplace
和 copy
。当前的讨论发生在 这里。在写时复制的上下文中,这些关键字将不再需要。如果这个提议被接受,这两个关键字将在 pandas 的下一个版本中被弃用,并在 pandas 3.0 中被移除。
弃用
-
弃用了使用系统本地时区解析日期时间字符串到
tzlocal
,请传递一个tz
关键字或明确调用tz_localize
来代替 (GH 50791) -
弃用了参数
infer_datetime_format
在to_datetime()
和read_csv()
中,因为现在的严格版本已经成为默认行为 (GH 48621) -
弃用了带有
unit
参数的to_datetime()
的行为,将来的版本中这些将被解析为日期时间(与无单位行为相匹配)而不是转换为浮点数。要保留旧行为,请在调用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) -
弃用了
read_csv()
、read_table()
、read_fwf()
和read_excel()
中的date_parser
参数,建议使用date_format
代替(GH 50601) -
弃用了
datetime64
和DatetimeTZDtype
数据类型的all
和any
缩减操作,使用例如(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
作为上下文管理器 (GH 49228) -
弃用了在对
DataFrameGroupBy
或SeriesGroupBy
进行迭代时产生标量的做法,该对象已经通过level
参数进行了分组,该参数是长度为 1 的列表;而现在将返回长度为一的元组代替 (GH 51583)
移除之前版本的弃用/更改
-
移除了
Int64Index
、UInt64Index
和Float64Index
。更多信息请参见此处 (GH 42717) -
移除了废弃的
Timestamp.freq
、Timestamp.freqstr
和Timestamp
构造函数中的freq
参数,以及Timestamp.fromordinal()
(GH 14146) -
移除了废弃的
CategoricalBlock
、Block.is_categorical()
,要求datetime64
和timedelta64
值在传递给Block.make_block_same_class()
前必须包装在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
的weekofyear
和week
属性,DatetimeIndex
和dt
访问器中的,改用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) -
强制不允许在
Series
或DataFrame
构造函数中传递时区感知的Timestamp
和dtype="datetime64[ns]"
(GH 41555) -
强制不允许在
Series
或DataFrame
构造函数中传递时区感知值的序列和dtype="datetime64[ns]"
(GH 41555) -
在
DataFrame
构造函数中强制不允许使用numpy.ma.mrecords.MaskedRecords
,而是使用"{name: data[name] for name in data.dtype.names}
(GH 40363) -
强制不允许在
Series.astype()
和DataFrame.astype()
中使用无单位的“datetime64”数据类型(GH 47844) -
强制废弃了使用
.astype
将datetime64[ns]
Series
、DataFrame
或DatetimeIndex
转换为时区感知 dtype 的操作,应改用obj.tz_localize
或ser.dt.tz_localize
(GH 39258) -
强制废弃了使用
.astype
将时区感知的Series
、DataFrame
或DatetimeIndex
转换为时区无关的datetime64[ns]
dtype 的操作,应改用obj.tz_localize(None)
或obj.tz_convert("UTC").tz_localize(None)
(GH 39258) -
强制废弃了在
concat()
中传递非布尔参数进行排序的操作(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()
中移除了参数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) -
从
DataFrame.to_csv()
和Series.to_csv()
中移除了参数line_terminator
,请使用lineterminator
代替(GH 45302) -
从
DataFrame.set_axis()
和Series.set_axis()
中移除了参数inplace
,请使用obj = obj.set_axis(..., copy=False)
代替(GH 48130) -
禁止向
MultiIndex.set_levels()
和MultiIndex.set_codes()
传递位置参数(GH 41485) -
禁止解析带有单位“Y”、“y”或“M”的时间增量字符串,因为这些不代表明确的持续时间(GH 36838)
-
移除了
MultiIndex.is_lexsorted()
和MultiIndex.lexsort_depth()
(GH 38701) -
从
PeriodIndex.astype()
中移除了参数how
,请使用PeriodIndex.to_timestamp()
代替(GH 37982) -
在
DataFrame.mask()
、DataFrame.where()
、Series.mask()
和Series.where()
中移除了参数try_cast
(GH 38836) -
在
Period.to_timestamp()
中移除了参数tz
,现在使用obj.to_timestamp(...).tz_localize(tz)
代替(GH 34522) -
在
DataFrame.plot()
和Series.plot()
中移除了参数sort_columns
(GH 47563) -
在
DataFrame.take()
和Series.take()
中移除了参数is_copy
(GH 30615) -
在
Index.get_slice_bound()
、Index.slice_indexer()
和Index.slice_locs()
中移除了参数kind
(GH 41378) -
在
read_csv()
中移除了参数prefix
、squeeze
、error_bad_lines
和warn_bad_lines
(GH 40413、GH 43427) -
在
read_excel()
中移除了参数squeeze
(GH 43427) -
在
DataFrame.describe()
和Series.describe()
中移除了参数datetime_is_numeric
,因为日期时间数据将始终被总结为数值数据(GH 34798) -
禁止将列表
key
传递给Series.xs()
和DataFrame.xs()
,改为传递元组(GH 41789) -
在
Index
构造函数中禁止子类特定关键字(例如“freq”,“tz”,“names”,“closed”)(GH 38597) -
从
Categorical.remove_unused_categories()
中删除参数inplace
(GH 37918) -
禁止将非四舍五入的浮点数传递给带有
unit="M"
或unit="Y"
的Timestamp
(GH 47266) -
从
read_excel()
中删除关键字convert_float
和mangle_dupe_cols
(GH 41176) -
从
read_csv()
和read_table()
中删除关键字mangle_dupe_cols
(GH 48137) -
从
DataFrame.where()
,Series.where()
,DataFrame.mask()
和Series.mask()
中删除关键字errors
(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) -
禁止向
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()
传递非关键字参数,除了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) -
禁止在不传递
data
的情况下构造CategoricalIndex
(GH 38944) -
移除了
Rolling.validate()
,Expanding.validate()
和ExponentialMovingWindow.validate()
(GH 43665) -
移除了
Rolling.win_type
返回"freq"
的功能(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) -
改变了带有
numeric_only=None
参数的DataFrame.median()
和DataFrame.mean()
的行为,不再排除类似于日期时间的列,一旦执行了对numeric_only=None
的弃用,此注释将变得无关紧要(GH 29941) -
改用
is_extension_array_dtype()
替代了is_extension_type()
(GH 29457) -
移除了
.ExponentialMovingWindow.vol
(GH 39220) -
移除了
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) -
改用
to_offset()
替代了get_offset
(GH 30340) -
移除了
infer_freq()
中的warn
关键字 (GH 45947) -
改用
inclusive
代替了DataFrame.between_time()
中的include_start
和include_end
参数 (GH 43248) -
改用
inclusive
参数代替了date_range()
和bdate_range()
中的closed
参数 (GH 40245) -
移除了
DataFrame.expanding()
中的center
关键字 (GH 20647) -
在
eval()
中移除了truediv
关键字 (GH 29812) -
使用
index.get_indexer([label], method=..., tolerance=...)
替代了Index.get_loc()
中的method
和tolerance
参数 (GH 42269) -
移除了
pandas.datetime
子模块 (GH 30489) -
移除了
pandas.np
子模块 (GH 30296) -
移除了
pandas.util.testing
,采用了pandas.testing
(GH 30745) -
移除了
Series.str.__iter__()
(GH 28277) -
改用
arrays.SparseArray
代替了pandas.SparseArray
(GH 30642) -
移除了
pandas.SparseSeries
和pandas.SparseDataFrame
,包括 pickle 支持。 (GH 30642) -
强制禁止将整数
fill_value
传递给具有 datetime64、timedelta64 或 period 数据类型的DataFrame.shift()
和Series.shift
()` (GH 32591) -
强制禁止将字符串列标签传递到
DataFrame.ewm()
的times
参数中(GH 43265) -
在
Series.between()
中,禁止将True
和False
传入inclusive
,而应分别使用"both"
和"neither"
(GH 40628) -
在
engine="c"
时,禁止使用超出界限的索引使用usecols
进行read_csv
(GH 25623) -
在
ExcelWriter
中强制禁止使用**kwargs
;改用关键字参数engine_kwargs
(GH 40430) -
禁止将列标签元组传入
DataFrameGroupBy.__getitem__()
(GH 30546) -
在使用
MultiIndex
层级的序列标签索引时,强制禁止缺失标签。现在会引发KeyError
(GH 42351) -
在使用
.loc
进行位置切片设置值时,强制禁止使用位置切片。改用带标签的.loc
或带位置的.iloc
(GH 31840) -
禁止使用
float
键进行位置索引,即使该键是一个整数,也需要手动转换为整数 (GH 34193) -
禁止在使用
.iloc
时使用DataFrame
索引器,改用.loc
进行自动对齐 (GH 39022) -
在
__getitem__
和__setitem__
方法中强制禁止使用set
或dict
索引器 (GH 42825) -
在
Index
上进行索引或在Series
上进行位置索引时生成多维对象,例如obj[:, None]
,请在索引之前转换为 numpy (GH 35141) -
在
merge()
的suffixes
中禁止使用dict
或set
对象 (GH 34810) -
禁止通过
suffixes
关键字和已存在的列在merge()
中产生重复列 (GH 22818) -
在不同层级数量上禁止使用
merge()
或join()
(GH 34862) -
强制禁止在
DataFrame.melt()
中使用value_name
参数来匹配DataFrame
列中的元素(GH 35003) -
强制禁止在
DataFrame.to_markdown()
和Series.to_markdown()
中将showindex
传递给**kwargs
,改用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) -
强制禁止使用单个项目列表对
Series
进行索引,并使用切片(例如ser[[slice(0, 2)]]
)。要么将列表转换为元组,要么直接传递切片(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
的行为;默认 dtype 将是object
而不是float64
(GH 29405) -
更改了
DatetimeIndex.union()
,DatetimeIndex.intersection()
和DatetimeIndex.symmetric_difference()
的行为,当时区不匹配时,转换为 UTC 而不是转换为对象 dtype(GH 39328) -
更改了带有参数“now”和
utc=False
的to_datetime()
的行为,以匹配Timestamp("now")
(GH 18705) -
更改了在时区感知的
DatetimeIndex
上进行索引的行为,当时区感知的datetime
对象或时区无关的datetime
对象进行索引时;现在像任何其他不可比较的类型一样,通过引发KeyError
来处理(GH 36148) -
更改了带有
datetime64
dtype 和datetime.date
对象作为fill_value
的Index.reindex()
,Series.reindex()
和DataFrame.reindex()
的行为;这些不再被视为等同于datetime.datetime
对象,因此重新索引会转换为对象 dtype(GH 39767) -
更改了
SparseArray.astype()
的行为,当给定一个不明确为SparseDtype
的 dtype 时,将精确转换为请求的 dtype,而不是默默地使用SparseDtype
(GH 34457) -
更改了
Index.ravel()
的行为,现在返回原始Index
的视图,而不是np.ndarray
(GH 36900) -
当
name=None
时,Series.to_frame()
和Index.to_frame()
的行为发生了变化,现在使用None
作为列名,而不是索引名或默认的0
(GH 45523) -
当一个数组是
bool
-dtype,另一个是整数 dtype 时,concat()
的行为发生了变化,现在返回object
dtype 而不是整数 dtype;在连接之前显式将 bool 对象转换为整数以获得旧的行为(GH 45101) -
当给定浮点数
data
和整数dtype
时,DataFrame
构造函数的行为发生了变化,当数据无法无损转换时,保留浮点数 dtype,与Series
的行为一致(GH 41170) -
当给定包含数值条目的 object-dtype 的
np.ndarray
时,Index
构造函数的行为发生了变化;现在保留 object dtype 而不是推断数值 dtype,与Series
的行为一致(GH 42870) -
Index.__and__()
,Index.__or__()
和Index.__xor__()
的行为发生了变化,现在作为逻辑操作(与Series
的行为一致)���而不是集合操作的别名(GH 37374) -
当传递一个列表,其第一个元素是
Categorical
时,DataFrame
构造函数的行为发生了变化,现在将元素视为行并转换为object
dtype,与其他类型的行为一致(GH 38845) -
当传递一个无法转换数据的
dtype
(非 int)时,DataFrame
构造函数的行为发生了变化;现在会引发异常,而不是静默忽略 dtype(GH 41733) -
Series
构造函数的行为发生了变化,它将不再从字符串条目中推断出 datetime64 或 timedelta64 dtype(GH 41731) -
改变了带有
np.datetime64
对象和传递给其的tz
的Timestamp
构造函数的行为,将输入解释为壁钟时间而不是 UTC 时间 (GH 42288) -
改变了
Timestamp.utcfromtimestamp()
的行为,返回一个满足Timestamp.utcfromtimestamp(val).timestamp() == val
的时区感知对象 (GH 45083) -
当传递
SparseArray
或SparseDtype
给Index
构造函数时,改变了其行为以保留该 dtype 而不是强制转换为numpy.ndarray
(GH 43930) -
当对象具有
DatetimeTZDtype
并且使用非匹配时区的值时,对类似于设置项的操作(__setitem__
、fillna
、where
、mask
、replace
、insert
、shift
的fill_value
)的行为进行了更改,该值将被转换为对象的时区而不是同时转换为对象的 dtype (GH 44243) -
当具有浮点 dtype 数据和
DatetimeTZDtype
时,改变了Index
、Series
、DataFrame
构造函数的行为,现在数据被解释为 UTC 时间而不是壁钟时间,与整数 dtype 数据的处理方式一致 (GH 45573) -
改变了带有整数 dtype 和包含
NaN
的浮点数据的Series
和DataFrame
构造函数的行为,现在会引发IntCastingNaNError
(GH 40110) -
改变了带有整数
dtype
和值过大以至于无法无损地转换为此dtype
的Series
和DataFrame
构造函数的行为,现在会引发ValueError
(GH 41734) -
更改了具有整数
dtype
和值为datetime64
或timedelta64
dtypes 的值的Series
和DataFrame
构造函数的行为,现在会引发TypeError
,请使用values.view("int64")
代替(GH 41770) -
移除了
pandas.DataFrame.resample()
、pandas.Series.resample()
和pandas.Grouper
中已弃用的base
和loffset
参数。现在请使用offset
或origin
代替(GH 31809) -
更改了带有不兼容
fill_value
的timedelta64[ns]
dtype 和Series.fillna()
和DataFrame.fillna()
的行为;现在会将其转换为object
dtype 而不是引发异常,与其他 dtypes 的行为一致(GH 45746) -
将
Series.str.replace()
的regex
默认参数从True
更改为False
。此外,具有regex=True
的单个字符pat
现在被视为正则表达式而不是字符串文字。(GH 36695, GH 24804) -
更改了带有
bool_only=True
的DataFrame.any()
和DataFrame.all()
的行为;具有全部布尔值的对象 dtype 列将不再被包括,首先手动转换为bool
dtype(GH 46188) -
改变了
DataFrame.max()
、DataFrame.min
、DataFrame.mean
、DataFrame.median
、DataFrame.skew
、DataFrame.kurt
函数在axis=None
的情况下改为返回一个标量,应用于两个轴上的聚合(GH 45072) -
改变了与
datetime.date
对象进行比较的Timestamp
的行为;现在这些比较会被视为不相等并在不相等时引发异常,与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()
实现样式化输出(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) -
改变了具有
ExtensionDtype
类型的数组不实现diff
的Series.diff()
和DataFrame.diff()
的行为,现在会引发TypeError
而不是转换为 numpy(GH 31025) -
在对具有
method="outer"
的DataFrame
上调用 numpy“ufunc”现已强制弃用;现在会引发NotImplementedError
(GH 36955) -
强制禁止将
numeric_only=True
传递给具有非数值 dtype 的Series
缩减(rank
、any
、all
等)(GH 47500) -
改变了
DataFrameGroupBy.apply()
和SeriesGroupBy.apply()
的行为,即使检测到转换器,也会尊重group_keys
(GH 34998) -
当
DataFrame
与Series
的列不匹配时,比较会引发ValueError
而不是自动对齐,在比较之前进行left, right = left.align(right, axis=1, copy=False)
(GH 36795) -
在 DataFrame 缩减中强制弃用了
numeric_only=None
(默认值),这会静默丢弃引发的列;numeric_only
现在默认为False
(GH 41480) -
在具有该参数的所有 DataFrame 方法中,将
numeric_only
的默认值更改为False
(GH 46096,GH 46906) -
Series.rank()
中numeric_only
的默认值更改为False
(GH 47561) -
在
numeric_only=False
时,强制在 groupby 和 resample 操作中静默丢弃无关紧要的列的弃用 (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) -
使用返回 DataFrame 的可调用函数的方法
DataFrameGroupBy.transform()
将与输入的索引对齐 (GH 47244) -
当向
DataFrame.groupby()
提供长度为一的列列表时,通过对生成的DataFrameGroupBy
对象进行迭代返回的键现在将是长度为一的元组 (GH 47761) -
移除了已弃用的方法
ExcelWriter.write_cells()
、ExcelWriter.save()
、ExcelWriter.cur_sheet()
、ExcelWriter.handles()
、ExcelWriter.path()
(GH 45795) -
属性
book
的ExcelWriter
不再可设置;仍可访问和修改 (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()
中进行了性能改进,适用于可空数据类型(GH 37493) -
在对象数据类型中,对
DataFrameGroupBy.all()
、DataFrameGroupBy.any()
、SeriesGroupBy.all()
和SeriesGroupBy.any()
进行了性能改进(GH 50623) -
在
MultiIndex.argsort()
和MultiIndex.sort_values()
中进行了性能改进(GH 48406) -
MultiIndex.size()
的性能改进(GH 48723) -
MultiIndex.difference()
的性能改进(GH 48606) -
具有
sort=None
选项的MultiIndex
集合操作的性能改进(GH 49010) -
扩展数组数据类型的
DataFrameGroupBy.mean()
、SeriesGroupBy.mean()
、DataFrameGroupBy.var()
和SeriesGroupBy.var()
的性能改进(GH 37493) -
MultiIndex.putmask()
中的性能改进 -
当索引包含重复项时,
Index.union()
和MultiIndex.union()
的性能改进(GH 48900) -
对于 pyarrow 支持的数据类型,
Series.rank()
的性能改进(GH 50264) -
对于 pyarrow 支持的数据类型,
Series.searchsorted()
的性能改进(GH 50447) -
在
Index
为单调时,针对掩码和箭头 dtype 的Index.join()
、Index.intersection()
和Index.union()
的性能改进(GH 50310,GH 51365) -
具有可空 dtype 的
Series.value_counts()
的性能改进(GH 48338) -
使用可空 dtype 的整数 numpy 数组构造器的
Series
的性能改进(GH 48338) -
使用列表构造器的
DatetimeIndex
的性能改进(GH 48609) -
在使用已排序的
MultiIndex
进行连接时,merge()
和DataFrame.join()
的性能改进(GH 48504) -
在带有时区偏移的字符串解析中,
to_datetime()
的性能改进(GH 50107) -
使用元组索引的
MultiIndex
的DataFrame.loc()
和Series.loc()
的性能改进(GH 48384) -
带有分类 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) -
对于传递了类型为
np.str_
的 numpy 数组的StringArray
构造函数的性能改进(GH 49109) -
在
from_tuples()
中的性能改进(GH 50620) -
在
factorize()
中的性能改进(GH 49177) -
当数组包含 NA 时,
ArrowExtensionArray
比较方法的性能改进(GH 50524) -
将字符串解析为
BooleanDtype
时的性能改进(GH 50613) -
在
DataFrame.join()
中对MultiIndex
的子集进行连接时的性能改进(GH 48611) -
对
MultiIndex.intersection()
的性能改进(GH 48604) -
在
DataFrame.__setitem__()
中的性能改进(GH 46267) -
对可空数据类型的
var
和std
的性能改进(GH 48379) -
RangeIndex.sort_values()
中的内存改进(GH 48801) -
如果
copy=True
,则在Series.to_numpy()
中通过避免两次复制来改进性能(GH 24345) -
Series.rename()
中的性能改进与MultiIndex
(GH 21055) -
当
DataFrameGroupBy
和SeriesGroupBy
的by
是分类类型且sort=False
时的性能改进(GH 48976) -
当
DataFrameGroupBy
和SeriesGroupBy
的by
是分类类型且observed=False
时的性能改进(GH 49596) -
在
read_stata()
中将参数index_col
设置为None
(默认值)的性能改进。现在索引将是RangeIndex
而不是Int64Index
(GH 49745) -
当不在索引上合并时,在
merge()
中的性能改进 - 新索引现在将是RangeIndex
而不是Int64Index
(GH 49478) -
在使用任何非对象数据类型时,
DataFrame.to_dict()
和Series.to_dict()
的性能改进(GH 46470) -
当存在多个表格时,
read_html()
的性能改进(GH 49929) -
从字符串或整数构造
Period
构造函数中的性能改进(GH 38312) -
使用
'%Y%m%d'
格式时,to_datetime()
的性能改进(GH 17410) -
当给定格式或可以推断时,
to_datetime()
的性能改进(GH 50465) -
可空数据类型的
Series.median()
性能改进(GH 50838) -
当传递
to_datetime()
lambda 函数给date_parser
并且输入具有混合时区偏移时,read_csv()
的性能改进(GH 35296) -
isna()
和isnull()
的性能改进(GH 50658) -
具有分类数据类型的
SeriesGroupBy.value_counts()
的性能改进(GH 46202) -
修复了
read_hdf()
中的引用泄漏(GH 37441) -
在序列化日期时间和时间增量时,修复了
DataFrame.to_json()
和Series.to_json()
中的内存泄漏(GH 40443) -
许多
DataFrameGroupBy
方法中内存使用减少(GH 51090) -
对于整数
decimal
参数,DataFrame.round()
的性能改进(GH 17254) -
使用大型字典进行
to_replace
时,在DataFrame.replace()
和Series.replace()
中的性能改进(GH 6697) -
在读取可寻址文件时,
StataReader
中的内存改进(GH 48922)
Bug fixes
分类
-
Categorical.set_categories()
中的错误会丢失数据类型信息(GH 48812) -
具有分类数据类型的
Series.replace()
中的错误,当to_replace
值与新值重叠时(GH 49404) -
具有分类数据类型的
Series.replace()
中的错误会丢失底层类别的可空数据类型(GH 49404) -
当作为分组器使用时,
DataFrame.groupby()
和Series.groupby()
中的错误会重新排序类别(GH 48749) -
从
Categorical
对象构造时,使用dtype="category"
时,Categorical
构造函数会丢失有序性的错误(GH 49309) -
具有无序的
CategoricalDtype
的SeriesGroupBy.min()
、SeriesGroupBy.max()
、DataFrameGroupBy.min()
和DataFrameGroupBy.max()
中的错误未能引发TypeError
(GH 51034)
Datetimelike
-
在
pandas.infer_freq()
中的错误,在对RangeIndex
进行推断时引发TypeError
(GH 47084) -
在字符串参数对应于大整数的情况下,
to_datetime()
中的错误不正确地引发OverflowError
(GH 50533) -
在使用
errors='coerce'
和infer_datetime_format=True
时,to_datetime()
中的错误在无效偏移时引发(GH 48633) -
在
DatetimeIndex
构造函数中的错误,在明确指定了tz=None
的情况下,与时区感知dtype
或数据一起时未能引发错误(GH 48659) -
从
DatetimeIndex
中减去一个datetime
标量时,未能保留原始的freq
属性,导致失败(GH 48818) -
在
pandas.tseries.holiday.Holiday
中的错误,半开放日期区间导致USFederalHolidayCalendar.holidays()
的返回类型不一致(GH 49075) -
在渲染带有
dateutil
或zoneinfo
时区感知 dtype 的DatetimeIndex
、Series
和DataFrame
时出现的错误,靠近夏令时转换期间的时区转换问题(GH 49684) -
在解析
Timestamp
、datetime.datetime
、datetime.date
或np.datetime64
对象时,当传递非 ISO8601format
时,to_datetime()
中的错误会引发ValueError
(GH 49298,GH 50036) -
to_datetime()
中的错误,当解析空字符串和非 ISO8601 格式时会引发ValueError
。现在,空字符串将被解析为NaT
,以兼容与 ISO8601 格式相同的处理方式(GH 50251) -
Timestamp
中的 Bug 在解析非 ISO8601 分隔日期字符串时显示了UserWarning
,用户无法执行任何操作(GH 50232) -
to_datetime()
中的 Bug 在解析包含 ISO 周指令和 ISO 工作日指令的格式的日期时,显示了误导性的ValueError
(GH 50308) -
Timestamp.round()
中的 Bug 在freq
参数为零持续时间(例如“0ns”)时返回不正确的结果而不是引发异常(GH 49737) -
to_datetime()
中的 Bug 在传递无效格式并且errors
为'ignore'
或'coerce'
时未能引发ValueError
(GH 50266) -
在构造
DateOffset
时,如果毫秒和另一个超过每日的参数同时出现,会引发TypeError
(GH 49897) -
to_datetime()
中的 Bug 在解析带有日期小数的字符串时,如果格式为'%Y%m%d'
,未能引发ValueError
(GH 50051) -
to_datetime()
中的 Bug 在解析混合偏移日期字符串(使用 ISO8601 格式)时,未能将None
转换为NaT
(GH 50071) -
to_datetime()
中的 Bug 在解析超出边界日期字符串时,使用errors='ignore'
和format='%Y%m%d'
时未能返回输入(GH 14487) -
to_datetime()
中的 Bug 在解析带有时区感知字符串、ISO8601 格式和utc=False
时,将时区无关的datetime.datetime
转换为时区感知时未能正确处理(GH 50254) -
to_datetime()
中的 Bug 在解析 ISO8601 格式的日期时,其中某些值未使用零填充时,会引发ValueError
(GH 21422) -
to_datetime()
中的 Bug 在使用format='%Y%m%d'
和errors='ignore'
时返回不正确的结果(GH 26493) -
Bug in
to_datetime()
在format
不是 ISO8601 时无法解析日期字符串'today'
和'now'
(GH 50359) -
Bug in
Timestamp.utctimetuple()
引发TypeError
(GH 32174) -
Bug in
to_datetime()
在解析混合偏移Timestamp
时,使用errors='ignore'
时引发ValueError
(GH 50585) -
Bug in
to_datetime()
在处理接近溢出边界的浮点输入时出现错误 (GH 50183) -
Bug in
to_datetime()
在单位为“Y”或“M”时给出不正确的结果,与逐点Timestamp
结果不匹配 (GH 50870) -
Bug in
Series.interpolate()
和DataFrame.interpolate()
在处理日期时间或时间增量数据类型时错误地引发ValueError
(GH 11312) -
Bug in
to_datetime()
在输入超出范围时,未使用errors='ignore'
返回输入 (GH 50587) -
Bug in
DataFrame.from_records()
在给定带有时区感知 datetime64 列的DataFrame
输入时错误地删除了时区感知信息 (GH 51162) -
Bug in
to_datetime()
在解析带有errors='coerce'
的日期字符串时引发decimal.InvalidOperation
(GH 51084) -
Bug in
to_datetime()
在同时指定unit
和origin
时返回不正确的结果 (GH 42624) -
Series.astype()
和DataFrame.astype()
中的 Bug,在将包含时区感知日期时间或字符串的对象 dtype 对象转换为datetime64[ns]
时,错误地将其本地化为 UTC 而不是引发TypeError
(GH 50140) -
DataFrameGroupBy.quantile()
和SeriesGroupBy.quantile()
中的 Bug,对包含NaT
的组给出了错误结果(GH 51373) -
DataFrameGroupBy.quantile()
和SeriesGroupBy.quantile()
中的 Bug,与PeriodDtype
或DatetimeTZDtype
不正确地引发错误(GH 51373)
时间差
-
to_timedelta()
中的 Bug,在输入具有可空 dtypeFloat64
时引发错误(GH 48796) -
Timedelta
构造函数在给定np.timedelta64("nat")
时,错误地引发而不是返回NaT
(GH 48898) -
Timedelta
构造函数在传递了Timedelta
对象和关键字(例如 days, seconds)时未能引发错误(GH 48898) -
Timedelta
与非常大的datetime.timedelta
对象比较时不正确地引发OutOfBoundsTimedelta
(GH 49021)
时区
-
Series.astype()
和DataFrame.astype()
中的错误,包含多个具有异构时区的时区感知datetime
对象的对象 dtype 不正确地引发DatetimeTZDtype
(GH 32581) -
to_datetime()
中的错误,在指定format
为%Z
时无法解析带有时区名称的日期字符串(GH 49748) -
在
Timestamp.tz_localize()
中传递无效值给ambiguous
参数时提供更好的错误消息(GH 49565) -
字符串解析中的错误,错误地允许使用无效时区构造
Timestamp
,在尝试打印时会引发错误(GH 50668) -
在
objects_to_datetime64ns()
中更正了 TypeError 消息,以通知 DatetimeIndex 具有混合时区(GH 50974)
数值
-
DataFrame.add()
中的错误,当输入包含混合的 DataFrame 类型和 Series 类型时无法应用 ufunc(GH 39853) -
在
Series
上的算术运算中,当组合掩码 dtype 和 numpy dtype 时,未传播掩码的错误(GH 45810,GH 42630) -
DataFrame.sem()
和Series.sem()
中的错误,在使用由ArrowDtype
支持的数据时,总是会引发错误的TypeError
(GH 49759) -
在
Series.__add__()
中的错误,将列表和掩码Series
强制转换为对象(GH 22962) -
在
mode()
中的错误,当存在NA
值时,dropna=False
未被尊重(GH 50982) -
Bug in
DataFrame.query()
使用engine="numexpr"
并且列名为min
或max
时会引发TypeError
(GH 50937) -
Bug in
DataFrame.min()
和DataFrame.max()
在包含pd.NaT
和axis=1
的 tz-aware 数据时会返回不正确的结果(GH 51242)
转换
-
构造带有
int64
dtype 的Series
时从字符串列表中引发错误而不是转换(GH 44923) -
构造带有掩码 dtype 和布尔值的
Series
时引发NA
错误(GH 42137) -
Bug in
DataFrame.eval()
在函数调用中存在负值时错误地引发AttributeError
(GH 46471) -
Bug in
Series.convert_dtypes()
当Series
包含NA
且 dtype 为object
时未将 dtype 转换为可空 dtype(GH 48791) -
任何
kind="M"
的ExtensionDtype
子类都会被解释为时区类型的错误(GH 34986) -
Bug in
arrays.ArrowExtensionArray
当传递字符串或二进制序列时会引发NotImplementedError
(GH 49172) -
Bug in
Series.astype()
在从非 pyarrow 字符串 dtype 转换为 pyarrow 数值类型时引发pyarrow.ArrowInvalid
(GH 50430) -
Bug in
DataFrame.astype()
在转换为string
且copy=False
时会修改输入数组(GH 51073) -
在应用
na_value
之前,Series.to_numpy()
存在 bug,将转换为 NumPy 数组(GH 48951) -
在转换为 pyarrow 数据类型时,
DataFrame.astype()
存在 bug,未复制数据(GH 50984) -
当
format
是 ISO8601 格式时,to_datetime()
不遵守exact
参数(GH 12649) -
当转换为 pyarrow 持续时间类型时,
TimedeltaArray.astype()
存在 bug,抛出TypeError
(GH 49795) -
在扩展数组数据类型时,
DataFrame.eval()
和DataFrame.query()
存在 bug,会抛出异常(GH 29618, GH 50261, GH 31913) -
在从
Index
创建并且dtype
等于从Index
创建的dtype
时,Series()
存在 bug,未复制数据(GH 52008)
字符串
-
pandas.api.types.is_string_dtype()
存在 bug,对于StringDtype
或ArrowDtype
,不会返回True
,带有pyarrow.string()
(GH 15585) -
将字符串数据类型转换为“datetime64[ns]”或“timedelta64[ns]”时,存在 bug,错误地抛出
TypeError
(GH 36153) -
当将值设置在具有数组的字符串数据类型列中时,存在 bug,当数组包含缺失值时,会作为副作用突变(GH 51299)
区间
-
如果区间具有重复的左边界,则
IntervalIndex.is_overlapping()
存在 bug,输出不正确(GH 49581) -
Bug in
Series.infer_objects()
未能推断IntervalDtype
为对象系列的Interval
对象(GH 50090) -
Bug in
Series.shift()
使用IntervalDtype
和无效的空fill_value
时未能��发TypeError
错误(GH 51258)
索引
-
Bug in
DataFrame.__setitem__()
当索引器为具有boolean
数据类型的DataFrame
时引发错误(GH 47125) -
Bug in
DataFrame.reindex()
在索引列和索引为uint
类型时填充错误值(GH 48184) -
Bug in
DataFrame.loc()
在设置具有不同数据类型的DataFrame
时,将值强制转换为单一数据类型(GH 50467) -
Bug in
DataFrame.sort_values()
当by
为空列表且inplace=True
时未返回None
(GH 50643) -
Bug in
DataFrame.loc()
在使用列表索引器设置值时强制转换数据类型(GH 49159) -
Bug in
Series.loc()
对于超出边界的切片索引器末端引发错误(GH 50161) -
Bug in
DataFrame.loc()
在所有False
bool
索引器和空对象时引发ValueError
错误(GH 51450) -
Bug in
DataFrame.loc()
在bool
索引器和MultiIndex
时引发ValueError
错误(GH 47687) -
DataFrame.loc()
中的 Bug 在使用非标量索引器设置具有非标量索引器的 pyarrow-backed 列值时引发IndexError
(GH 50085) -
在
DataFrame.__getitem__()
、Series.__getitem__()
、DataFrame.__setitem__()
和Series.__setitem__()
中的 Bug 在使用整数索引复杂数据类型的扩展浮点数据类型 (Float64
&Float64
) 或使用整数时引发IndexError
(GH 51053) -
在
DataFrame.loc()
中的 Bug 在使用空索引器设置不兼容值时修改对象(GH 45981) -
在
DataFrame.__setitem__()
中的 Bug 在右侧为具有MultiIndex
列的DataFrame
时引发ValueError
(GH 49121) -
在
DataFrame.reindex()
中的 Bug 在重新索引columns
和index
时将数据类型转换为object
,当DataFrame
具有单个扩展数组列时(GH 48190) -
在
DataFrame.iloc()
中的 Bug 在索引器为具有数值扩展数组数据类型的Series
时引发IndexError
(GH 49521) -
在
describe()
中的 Bug 在格式化百分位数时,结果索引显示比所需更多的小数位数(GH 46362) -
在
DataFrame.compare()
中的 Bug 在比较具有可空数据类型的NA
与值时不识别差异(GH 48939) -
在
Series.rename()
中的 Bug 在丢失扩展数组数据类型时 (GH 21055) -
在
DataFrame.isetitem()
中的 Bug 在将扩展数组数据类型强制转换为对象时 (GH 49922) -
Series.__getitem__()
存在错误,在从空的 pyarrow 支持的对象中进行选择时会返回损坏的对象(GH 51734) -
BusinessHour
中存在错误,当索引中未包含开放小时时,会导致DatetimeIndex
创建失败(GH 49835)
缺失
-
Index.equals()
存在错误,当Index
包含包含NA
的元组时会引发TypeError
(GH 48446) -
Series.map()
存在错误,当数据中存在 NaN 且使用 defaultdict 映射时会导致结果不正确(GH 48813) -
NA
存在错误,当与bytes
对象进行二进制操作时,会引发TypeError
而不是返回NA
(GH 49108) -
DataFrame.update()
中存在错误,当overwrite=False
时,若self
中存在具有NaT
值的列且other
中不存在该列时,会引发TypeError
(GH 16713) -
Series.replace()
存在错误,当在包含NA
的对象类型Series
中替换值时会引发RecursionError
(GH 47480) -
Series.replace()
存在错误,当在数值类型的Series
中替换值时会引发RecursionError
,且该系列含有NA
(GH 50758)
MultiIndex
-
MultiIndex.get_indexer()
存在错误,不匹配NaN
值(GH 29252,GH 37222,GH 38623,GH 42883,GH 43222,GH 46173,GH 48905) -
MultiIndex.argsort()
存在的 Bug 在索引包含NA
时引发TypeError
(GH 48495) -
MultiIndex.difference()
存在的 Bug 导致扩展数组的数据类型丢失 (GH 48606) -
MultiIndex.set_levels
存在的 Bug 在设置空级别时引发IndexError
(GH 48636) -
MultiIndex.unique()
存在的 Bug 导致扩展数组的数据类型丢失 (GH 48335) -
MultiIndex.intersection()
存在的 Bug 导致扩展数组丢失 (GH 48604) -
MultiIndex.union()
存在的 Bug 导致扩展数组丢失 (GH 48498, GH 48505, GH 48900) -
MultiIndex.union()
存在的 Bug 在 sort=None 且索引包含缺失值时未排序 (GH 49010) -
MultiIndex.append()
中存在的 Bug 未检查名称是否相等 (GH 48288) -
MultiIndex.symmetric_difference()
存在的 Bug 导致扩展数组丢失 (GH 48607) -
MultiIndex.join()
存在的 Bug 当MultiIndex
存在重复项时丢失数据类型 (GH 49830) -
MultiIndex.putmask()
存在的 Bug 导致扩展数组丢失 (GH 49830) -
MultiIndex.value_counts()
存在的 Bug 返回一个由元组的扁平索引索引的Series
而不是一个MultiIndex
(GH 49558)
I/O
-
read_sas()
中存在的 Bug 导致DataFrame
的碎片化,并引发errors.PerformanceWarning
(GH 48595) -
read_excel()
中改进了错误消息,当读取文件时引发异常时,包含有问题的工作表名称 (GH 48706) -
当对部分 PyArrow 支持的数据进行 pickling 时,存在一个 Bug,会序列化整个数据而不是部分数据(GH 42600)
-
当指定
chunksize
且结果为空时,read_sql_query()
存在一个 Bug,会忽略dtype
参数(GH 50245) -
当 CSV 文件只有一行且列数少于
names
指定的列数时,read_csv()
存在一个 Bug,使用engine="c"
会引发errors.ParserError
(GH 47566) -
read_json()
在orient="table"
和存在NA
值时存在一个 Bug,会抛出异常(GH 40255) -
显示
string
数据类型时存在一个 Bug,未显示存储选项(GH 50099) -
DataFrame.to_string()
存在一个 Bug,当header=False
时,会将索引名和数据的第一行打印在同一行上(GH 49230) -
DataFrame.to_string()
存在一个 Bug,在扩展数组中忽略了浮点格式化程序(GH 39336) -
修复了内部 JSON 模块初始化引起的内存泄漏(GH 49222)
-
修复了
json_normalize()
的问题,该问题会错误地从与sep
参数匹配的列名中删除前导字符(GH 49861) -
当包含
NA
且扩展数组数据类型时,read_csv()
存在一个 Bug,不必要地溢出(GH 32134) -
DataFrame.to_dict()
存在一个 Bug,不能将NA
转换为None
(GH 50795) -
DataFrame.to_json()
存在一个 Bug,当无法编码字符串时会导致段错误(GH 50307) -
DataFrame.to_html()
中的 Bug,在DataFrame
包含非标量数据时设置na_rep
时(GH 47103) -
read_xml()
中的 Bug,在使用 iterparse 时,文件类对象失败(GH 50641) -
read_csv()
中的 Bug,在engine="pyarrow"
时,未正确处理encoding
参数(GH 51302) -
read_xml()
中的 Bug,在使用 iterparse 时,忽略了重复的元素(GH 51183) -
ExcelWriter
中的 Bug,如果在实例化期间发生异常,则会保留文件句柄(GH 51443) -
DataFrame.to_parquet()
中的 Bug,在使用engine="pyarrow"
时,非字符串索引或列会引发ValueError
(GH 52036)
期间
-
Period.strftime()
和PeriodIndex.strftime()
中的 Bug,在传递特定于区域设置的指令时引发UnicodeDecodeError
(GH 46319) -
将
Period
对象添加到DateOffset
对象数组中时出现的 Bug,错误地引发TypeError
(GH 50162) -
Period
中的 Bug,在传递比纳秒更精细的字符串时,会导致KeyError
而不是丢弃额外的精度(GH 50417) -
解析表示周期的字符串时出现 Bug,例如 “2017-01-23/2017-01-29”,以分钟频率而不是周频率(GH 50803)
-
在
DataFrameGroupBy.sum()
、DataFrameGroupByGroupBy.cumsum()
、DataFrameGroupByGroupBy.prod()
、DataFrameGroupByGroupBy.cumprod()
中的 Bug,使用PeriodDtype
时未能引发TypeError
(GH 51040) -
在使用
Period
解析空字符串时的 Bug,不正确地引发ValueError
而不是返回NaT
(GH 51349)
Plotting
-
在
DataFrame.plot.hist()
中的 Bug,在data
中对应于NaN
值的weights
元素未被删除(GH 48884) -
ax.set_xlim
有时会引发UserWarning
,用户无法处理,因为set_xlim
不接受解析参数 - 转换器现在使用Timestamp()
代替(GH 49148)
Groupby/resample/rolling
-
在
ExponentialMovingWindow
中的 Bug,当使用online
参数时未对不支持的操作抛出NotImplementedError
(GH 48834) -
在
DataFrameGroupBy.sample()
中的 Bug,当对象为空时引发ValueError
(GH 48459) -
在
Series.groupby()
中的 Bug,当索引的某个条目等于索引的名称时,会引发ValueError
(GH 48567) -
在使用
DataFrameGroupBy.resample()
时,当传递空 DataFrame 时产生不一致的结果(GH 47705) -
在
DataFrameGroupBy
和SeriesGroupBy
中的 Bug,在按分类索引分组时,未包含未观察到的类别在结果中(GH 49354) -
在
DataFrameGroupBy
和SeriesGroupBy
中的 Bug,当按分类分组时,结果顺序会根据输入索引而改变(GH 49223) -
当在分类数据上进行分组时,
DataFrameGroupBy
和SeriesGroupBy
中的错误会在使用sort=False
时排序结果值 (GH 42482) -
当使用
as_index=False
且使用失败时,DataFrameGroupBy.apply()
和SeriesGroupBy.apply
中的错误不会尝试使用分组键进行计算时引发错误 (GH 49256) -
DataFrameGroupBy.describe()
中的错误会描述组键 (GH 49256) -
当
as_index=False
时,SeriesGroupBy.describe()
中的错误会导致形状不正确 (GH 49256) -
当 grouper 为分类数据时,
DataFrameGroupBy
和SeriesGroupBy
中的错误在dropna=False
时会丢弃 NA 值 (GH 36327) -
SeriesGroupBy.nunique()
中的错误在 grouper 为空分类且observed=True
时会不正确地引发错误 (GH 21334) -
SeriesGroupBy.nth()
中的错误在从DataFrameGroupBy
子集中使用 NA 值后会引发错误 (GH 26454) -
当
as_index=False
时,DataFrame.groupby()
中的错误不会在结果中包含由key
指定的Grouper
,当as_index=False
时 (GH 50413) -
DataFrameGroupBy.value_counts()
中的错误在与TimeGrouper
一起使用时会引发错误 (GH 50486) -
Resampler.size()
中的 Bug 导致返回宽的DataFrame
而不是具有MultiIndex
的Series
(GH 46826) -
DataFrameGroupBy.transform()
和SeriesGroupBy.transform()
中的 Bug 会在 grouper 具有axis=1
的情况下,对"idxmin"
和"idxmax"
参数错误地引发错误 (GH 45986) -
当使用空 DataFrame、分类分组器和
dropna=False
时,DataFrameGroupBy
中的 Bug 会引发错误 (GH 50634) -
SeriesGroupBy.value_counts()
中的 Bug 不遵守sort=False
(GH 50482) -
DataFrameGroupBy.resample()
存在 Bug,当在时间索引上重新采样时,从键列表获取结果时会引发KeyError
(GH 50840) -
DataFrameGroupBy.transform()
和SeriesGroupBy.transform()
中的 Bug 会在 grouper 具有axis=1
的情况下,对"ngroup"
参数错误地引发错误 (GH 45986) -
DataFrameGroupBy.describe()
中的 Bug 在数据具有重复列时会产生不正确的结果 (GH 50806) -
在
DataFrameGroupBy.agg()
中存在 bug,使用engine="numba"
时未能尊重as_index=False
(GH 51228) -
DataFrameGroupBy.agg()
、SeriesGroupBy.agg()
和Resampler.agg()
存在 bug,当传递函数列表时会忽略参数(GH 50863) -
在
DataFrameGroupBy.ohlc()
中存在 bug,会忽略as_index=False
(GH 51413) -
在对列进行子集化之后,
DataFrameGroupBy.agg()
存在 bug(例如.groupby(...)[["a", "b"]]
),结果中不会包括分组(GH 51186)
重塑
-
在
DataFrame.pivot_table()
中存在 bug,对可空 dtype 和margins=True
引发TypeError
(GH 48681) -
在
DataFrame.unstack()
和Series.unstack()
中存在 bug,当MultiIndex
的级别名称混合时,会展开错误的级别(GH 48763) -
在
DataFrame.melt()
中存在 bug,会丢失扩展数组的 dtype(GH 41570) -
DataFrame.pivot()
中存在 bug,不尊重None
作为列名(GH 48293) -
在
DataFrame.join()
中存在 bug,当left_on
或right_on
是或包含CategoricalIndex
时,会错误地引发AttributeError
(GH 48464) -
Bug in
DataFrame.pivot_table()
raisingValueError
with parametermargins=True
when result is an emptyDataFrame
(GH 49240) -
Clarified error message in
merge()
when passing invalidvalidate
option (GH 49417) -
Bug in
DataFrame.explode()
raisingValueError
on multiple columns withNaN
values or empty lists (GH 46084) -
Bug in
DataFrame.transpose()
withIntervalDtype
column withtimedelta64[ns]
endpoints (GH 44917) -
Bug in
DataFrame.agg()
andSeries.agg()
would ignore arguments when passed a list of functions (GH 50863)
Sparse
-
Bug in
Series.astype()
when converting aSparseDtype
withdatetime64[ns]
subtype toint64
dtype raising, inconsistent with the non-sparse behavior (GH 49631,:issue:50087) -
Bug in
Series.astype()
when converting a fromdatetime64[ns]
toSparse[datetime64[ns]]
incorrectly raising (GH 50082) -
Bug in
Series.sparse.to_coo()
raisingSystemError
whenMultiIndex
contains aExtensionArray
(GH 50996)
ExtensionArray
-
Bug in
Series.mean()
overflowing unnecessarily with nullable integers (GH 48378) -
Bug in
Series.tolist()
for nullable dtypes returning numpy scalars instead of python scalars (GH 49890) -
Series.round()
中存在 Bug,对于 pyarrow-backed dtypes 引发AttributeError
(GH 50437) -
当将空 DataFrame 与具有相同 ExtensionDtype 的另一个 DataFrame 连接时存在 Bug,结果的 dtype 变为 object(GH 48510)
-
array.PandasArray.to_numpy()
中存在 Bug,当指定na_value
时引发NA
值异常(GH 40638) -
api.types.is_numeric_dtype()
中存在 Bug,在自定义ExtensionDtype
返回_is_numeric
为True
时不会返回True
(GH 50563) -
api.types.is_integer_dtype()
、api.types.is_unsigned_integer_dtype()
、api.types.is_signed_integer_dtype()
、api.types.is_float_dtype()
中存在 Bug,在自定义ExtensionDtype
返回kind
对应的 NumPy 类型时不会返回True
(GH 50667) -
Series
构造函数存在 Bug,对于可空无符号整数 dtype 不必要地溢出(GH 38798, GH 25880) -
设置非字符串值到
StringArray
中存在 Bug,抛出ValueError
而不是TypeError
(GH 49632) -
DataFrame.reindex()
存在 Bug,在处理带有 ExtensionDtype 的列时,不遵守默认的copy=True
关键字(结果也会导致使用getitem
([]
) 选择多列时未正确复制)(GH 51197) -
ArrowExtensionArray
中的逻辑操作&
和|
存在 Bug,抛出KeyError
(GH 51688)
Styler
- 修复了带有
NA
值的可空数据类型Series
的background_gradient()
(GH 50712)
元数据
- 修复了
DataFrame.corr()
和DataFrame.cov()
中的元数据传播问题(GH 28283)
其他
-
在不正确地接受包含“[pyarrow]”的数据类型字符串时存在的错误(GH 51548)
-
在接受
DataFrame
作为参数value
时,Series.searchsorted()
存在的不一致行为(GH 49620) -
在
array()
中的错误,在DataFrame
输入失败时未引发错误(GH 51167)
分类
-
在
Categorical.set_categories()
中存在的失去数据类型信息的错误(GH 48812) -
在分类数据类型时,
Series.replace()
存在的错误,当to_replace
值与新值重叠时未引发错误(GH 49404) -
在分类数据类型时,
Series.replace()
存在的错误,失去了底层类别的可空数据类型(GH 49404) -
在用作分组键时,
DataFrame.groupby()
和Series.groupby()
存在的错误,会重新排序类别(GH 48749) -
在从
Categorical
对象构造时,构造函数Categorical
存在的错误,dtype="category"
时丢失了有序性(GH 49309) -
SeriesGroupBy.min()
、SeriesGroupBy.max()
、DataFrameGroupBy.min()
和DataFrameGroupBy.max()
中的 Bug,在使用无序的CategoricalDtype
且没有分组的情况下,未能引发TypeError
错误(GH 51034)
Datetimelike
-
pandas.infer_freq()
中的 Bug,在对RangeIndex
推断时引发TypeError
错误(GH 47084) -
在对应于大整数的字符串参数时,
to_datetime()
错误地引发OverflowError
(GH 50533) -
在使用
errors='coerce'
和infer_datetime_format=True
时,to_datetime()
对无效的偏移引发错误 (GH 48633) -
在明确指定
tz=None
与时区感知的dtype
或数据结合使用时,DatetimeIndex
构造函数未能引发错误 (GH 48659) -
从
DatetimeIndex
中减去datetime
标量时的 Bug,未能保留原始的freq
属性 (GH 48818) -
pandas.tseries.holiday.Holiday
中的 Bug,在半开区间日期间隔导致从USFederalHolidayCalendar.holidays()
返回类型不一致(GH 49075) -
使用
dateutil
或zoneinfo
时区的时区感知数据类型渲染DatetimeIndex
、Series
和DataFrame
在夏令时转换附近时出现错误(GH 49684) -
当解析非 ISO8601
format
时,to_datetime()
中的错误在解析Timestamp
、datetime.datetime
、datetime.date
或np.datetime64
对象时引发ValueError
(GH 49298,GH 50036) -
当解析空字符串并传递非 ISO8601 格式时,
to_datetime()
中的错误会引发ValueError
。现在,空字符串将被解析为NaT
,以便与 ISO8601 格式的处理方式兼容(GH 50251) -
Timestamp
中的错误显示了UserWarning
,当解析非 ISO8601 分隔日期字符串时,用户无法采取行动(GH 50232) -
to_datetime()
中的错误在解析包含 ISO 周指令和 ISO 工作日指令的格式的日期时显示了误导性的ValueError
(GH 50308) -
当
freq
参数为零持续时间(例如“0ns”)时,Timestamp.round()
中的错误返回了不正确的结果而不是引发异常(GH 49737) -
当传递无效格式并且
errors
为'ignore'
或'coerce'
时,to_datetime()
中的错误未引发ValueError
(GH 50266) -
在使用毫秒和另一个超日常参数构造
DateOffset
时,出现TypeError
错误(GH 49897) -
当解析带有
'%Y%m%d'
格式的小数日期字符串时,to_datetime()
中的错误未引发ValueError
(GH 50051) -
在解析使用 ISO8601 格式的混合偏移日期字符串时,
to_datetime()
中的错误未将None
转换为NaT
(GH 50071) -
在解析超出边界的日期字符串时,当
errors='ignore'
和format='%Y%m%d'
时,to_datetime()
中的错误未返回输入 (GH 14487) -
当使用时区感知字符串、ISO8601 格式和
utc=False
时,to_datetime()
在解析时区非感知的datetime.datetime
时出现错误,将其转换为时区感知的时间 (GH 50254) -
在解析带有 ISO8601 格式的日期字符串时,某些值未进行零填充,导致
to_datetime()
中的错误抛出ValueError
(GH 21422) -
当使用
format='%Y%m%d'
和errors='ignore'
时,to_datetime()
中的错误给出了错误的结果 (GH 26493) -
当
format
不是 ISO8601 时,to_datetime()
在解析日期字符串'today'
和'now'
时失败,导致错误 (GH 50359) -
Timestamp.utctimetuple()
中的错误引发了TypeError
(GH 32174) -
在解析带有混合偏移的
Timestamp
时,to_datetime()
的错误引发了ValueError
,并且使用errors='ignore'
选项时(GH 50585) -
在超出溢出边界的 1 个单位内处理浮点输入时,
to_datetime()
中的错误处理不正确 (GH 50183) -
当使用“Y”或“M”作为单位时,
to_datetime()
中的错误给出了错误的结果,与Timestamp
的结果不匹配 (GH 50870) -
当具有 datetime 或 timedelta 数据类型的
Series.interpolate()
和DataFrame.interpolate()
中存在错误时,不正确地引发ValueError
(GH 11312) -
当输入超出范围时,
to_datetime()
未使用errors='ignore'
返回输入(GH 50587) -
当给定一个具有时区感知的 datetime64 列的
DataFrame
输入时,DataFrame.from_records()
中存在错误,不正确地删除时区感知(GH 51162) -
当使用
errors='coerce'
解析日期字符串时,to_datetime()
引发decimal.InvalidOperation
错误(GH 51084) -
当同时指定
unit
和origin
时,to_datetime()
返回不正确的结果(GH 42624) -
当将包含时区感知日期时间或字符串的对象数据类型对象转换为
datetime64[ns]
时,Series.astype()
和DataFrame.astype()
中存在错误,不正确地将其本地化为 UTC,而不是引发TypeError
(GH 50140) -
当具有 datetime 或 timedelta 数据类型的组包含
NaT
时,DataFrameGroupBy.quantile()
和SeriesGroupBy.quantile()
中存在错误,给出不正确的结果(GH 51373) -
DataFrameGroupBy.quantile()
和SeriesGroupBy.quantile()
中的 Bug 在使用PeriodDtype
或DatetimeTZDtype
时错误地引发异常(GH 51373)
Timedelta
-
在输入具有可空类型
Float64
时,to_timedelta()
引发错误(GH 48796) -
在给定
np.timedelta64("nat")
时,Timedelta
构造函数错误地引发异常而不是返回NaT
(GH 48898) -
在传递
Timedelta
对象和关键字(例如天数、秒数)时,Timedelta
构造函数未能引发异常(GH 48898) -
在与非常大的
datetime.timedelta
对象比较时,Timedelta
中的 Bug 错误地引发OutOfBoundsTimedelta
(GH 49021)
时区
-
在包含多个时区感知的异质时区的
datetime
对象的对象类型中,Series.astype()
和DataFrame.astype()
转换为DatetimeTZDtype
时错误地引发异常(GH 32581) -
在指定
%Z
格式时,to_datetime()
无法解析带有时区名称的日期字符串的 Bug(GH 49748) -
在
Timestamp.tz_localize()
中传递无效值给ambiguous
参数时,提供更好的错误消息(GH 49565) -
字符串解析中的错误,错误地允许使用无效时区构造
Timestamp
,在尝试打印时会引发错误 (GH 50668) -
在
objects_to_datetime64ns()
中更正了TypeError
消息,以提示 DatetimeIndex 具有混合时区 (GH 50974)
数值
-
DataFrame.add()
中的错误,在输入包含混合的 DataFrame 类型和 Series 类型时无法应用 ufunc (GH 39853) -
对
Series
上的算术操作的错误,在组合掩码数据类型和 numpy 数据类型时不传播掩码 (GH 45810, GH 42630) -
DataFrame.sem()
和Series.sem()
中的错误,当使用由ArrowDtype
支持的数据时,会始终引发错误的TypeError
(GH 49759) -
Series.__add__()
中的错误,对列表和掩码Series
进行对象转换 (GH 22962) -
mode()
中的错误,当存在NA
值时未遵循dropna=False
(GH 50982) -
使用
engine="numexpr"
和列名为min
或max
时,在DataFrame.query()
中会引发TypeError
(GH 50937) -
DataFrame.min()
和DataFrame.max()
中的错误,当包含pd.NaT
和axis=1
的时区感知数据时会返回不正确的结果 (GH 51242)
转换
-
在使用字符串列表构建带有
int64
数据类型的Series
时引发错误,而不是进行转换 (GH 44923) -
构建带有掩码数据类型和布尔值的
Series
时的错误,带有NA
的布尔值会引发错误 (GH 42137) -
在
DataFrame.eval()
中的错误,当函数调用中存在负值时错误地引发AttributeError
(GH 46471) -
在
Series.convert_dtypes()
中的错误,在Series
包含NA
且 dtype 为object
时未将 dtype 转换为可空 dtype(GH 48791) -
任何具有
kind="M"
的ExtensionDtype
子类都将被解释为时区类型的错误(GH 34986) -
在
arrays.ArrowExtensionArray
中的错误,当传递一个字符串或二进制序列时错误地引发NotImplementedError
(GH 49172) -
在
Series.astype()
中的错误,当从非 pyarrow 字符串 dtype 转换为 pyarrow 数值类型时引发pyarrow.ArrowInvalid
(GH 50430) -
在
DataFrame.astype()
中的错误,当转换为string
且copy=False
时错误地修改输入数组(GH 51073) -
在
Series.to_numpy()
中的错误,在应用na_value
之前将其转换为 NumPy 数组(GH 48951) -
在
DataFrame.astype()
中的错误,转换为 pyarrow dtype 时未复制数据(GH 50984) -
在
to_datetime()
中的错误,当format
是 ISO8601 格式时未尊重exact
参数(GH 12649) -
在将
TimedeltaArray.astype()
转换为 pyarrow 持续时间类型时引发TypeError
的错误(GH 49795) -
DataFrame.eval()
和DataFrame.query()
中的 Bug,对于扩展数组 dtypes 引发错误(GH 29618, GH 50261, GH 31913) -
Series()
中的 Bug,在从Index
创建并且dtype
等于Index
的dtype
时未复制数据(GH 52008)
字符串
-
pandas.api.types.is_string_dtype()
中的 Bug,对于带有pyarrow.string()
的StringDtype
或ArrowDtype
不会返回True
(GH 15585) -
将字符串 dtypes 转换为“datetime64[ns]”或“timedelta64[ns]”时出现 Bug,错误地引发
TypeError
(GH 36153) -
在具有数组的字符串 dtype 列中设置值时出现 Bug,当数组包含缺失值时作为副作用改变数组 (GH 51299)
间隔
-
IntervalIndex.is_overlapping()
中的 Bug,如果间隔具有重复的左边界,则输出不正确(GH 49581) -
Series.infer_objects()
中的 Bug,未能推断IntervalDtype
为对象系列的Interval
对象 (GH 50090) -
Series.shift()
中的 Bug,使用IntervalDtype
和无效的空fill_value
时未能引发TypeError
(GH 51258)
索引
-
当索引器为具有
boolean
数据类型的DataFrame
时,DataFrame.__setitem__()
中的错误会引发异常(GH 47125) -
在为
uint
数据类型的列和索引进行索引时,DataFrame.reindex()
中的错误填充了错误的值(GH 48184) -
设置不同数据类型的
DataFrame
时,DataFrame.loc()
中的错误会将值强制转换为单一数据类型(GH 50467) -
当
by
为空列表且inplace=True
时,DataFrame.sort_values()
中的错误没有返回None
(GH 50643) -
在使用列表索引器设置值时,
DataFrame.loc()
中的错误会强制转换数据类型(GH 49159) -
在索引结束切片超出范围时,
Series.loc()
中的错误引发错误(GH 50161) -
DataFrame.loc()
中的错误导致所有False
布尔索引器和空对象引发ValueError
(GH 51450) -
使用
bool
索引器和MultiIndex
时,DataFrame.loc()
中的错误会引发ValueError
(GH 47687) -
使用非标量索引器为 pyarrow-backed 列设置值时,
DataFrame.loc()
中的错误会引发IndexError
(GH 50085) -
在使用整数索引时,
DataFrame.__getitem__()
、Series.__getitem__()
、DataFrame.__setitem__()
和Series.__setitem__()
中的错误会对具有扩展浮点数据类型(Float64
和Float64
)或复数数据类型的索引进行索引(GH 51053) -
使用不兼容值设置空索引器时,
DataFrame.loc()
中的错误会修改对象(GH 45981) -
DataFrame.__setitem__()
中的 Bug 在右侧为具有MultiIndex
列的DataFrame
时引发ValueError
(GH 49121) -
DataFrame.reindex()
中的 Bug 在重新索引columns
和index
时,当DataFrame
具有单个扩展数组列时将数据类型转换为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
中的 Bug(GH 49922) -
Series.__getitem__()
中的 Bug 在从空的 pyarrow 支持的对象中进行选择时返回损坏的对象(GH 51734) -
BusinessHour
中的 Bug 会导致在索引中不包含开放时间时创建DatetimeIndex
失败(GH 49835)
缺失
-
Index.equals()
中的 Bug 在包含NA
的元组的Index
引发TypeError
时(GH 48446) -
Series.map()
中的错误导致数据中包含 NaN 且使用 defaultdict 映射时结果不正确(GH 48813) -
NA
在与bytes
对象执行二进制操作时引发TypeError
而不是返回NA
的错误(GH 49108) -
DataFrame.update()
中的错误在overwrite=False
时,当self
具有NaT
值的列且other
中不存在该列时引发TypeError
(GH 16713) -
Series.replace()
中的错误在包含NA
的对象类型Series
中替换数值时引发RecursionError
(GH 47480) -
Series.replace()
中的错误在用NA
替换数值型Series
中引发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()
存在 bug,丢失扩展数组 (GH 48498, GH 48505, GH 48900) -
MultiIndex.union()
存在 bug,在 sort=None 且索引包含缺失值时不排序 (GH 49010) -
MultiIndex.append()
存在 bug,不检查名称是否相等 (GH 48288) -
MultiIndex.symmetric_difference()
存在 bug,丢失扩展数组 (GH 48607) -
MultiIndex.join()
存在 bug,当MultiIndex
包含重复值时,丢失 dtypes (GH 49830) -
MultiIndex.putmask()
存在 bug,丢失扩展数组 (GH 49830) -
MultiIndex.value_counts()
存在 bug,返回一个由元组的扁平索引索引的Series
而不是一个MultiIndex
(GH 49558)
I/O
-
read_sas()
存在 bug,���致DataFrame
的碎片化,并引发errors.PerformanceWarning
(GH 48595) -
在
read_excel()
中改进了错误消息,当读取文件时引发异常时,包含有问题的工作表名称 (GH 48706) -
当对由 PyArrow 支持的数据的子集进行 pickling 时出现 bug,会序列化整个数据而不是子集 (GH 42600)
-
read_sql_query()
存在 bug,当指定chunksize
且结果为空时,忽略dtype
参数 (GH 50245) -
单行 csv 中
read_csv()
存在 bug,列数少于names
时会引发errors.ParserError
,使用engine="c"
(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()
中的错误,在无法编码字符串时会导致段错误(GH 50307) -
DataFrame.to_html()
中的错误,当设置na_rep
时,DataFrame
包含非标量数据时(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()
中的错误,当传递了区域特定指令时引发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()
中的错误,在data
中不删除与NaN
值对应的weights
元素(GH 48884) -
ax.set_xlim
有时会引发UserWarning
,用户无法处理set_xlim
不接受解析参数的情况 - 现在转换器使用了Timestamp()
代替(GH 49148)
Groupby/resample/rolling
-
在
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()
中的 Bug 在as_index=False
时将会具有不正确的形状(GH 49256)。 -
在
DataFrameGroupBy
和SeriesGroupBy
中的 Bug 在dropna=False
时会在 grouper 是分类时丢弃 NA 值(GH 36327)。 -
在
SeriesGroupBy.nunique()
中的 Bug 会在 grouper 为空分类且observed=True
时不正确地触发错误(GH 21334)。 -
在
SeriesGroupBy.nth()
中的 Bug 会在 grouper 从DataFrameGroupBy
中子集化后包含 NA 值时触发错误(GH 26454)。 -
在
DataFrame.groupby()
中的 Bug 不会在as_index=False
时将由key
指定的Grouper
包含在结果中(GH 50413)。 -
在
DataFrameGroupBy.value_counts()
中的 Bug 会在与TimeGrouper
一起使用时触发错误(GH 50486)。 -
在
Resampler.size()
中的 Bug 会导致返回宽DataFrame
而不是带有MultiIndex
的Series
(GH 46826)。 -
在
DataFrameGroupBy.transform()
和SeriesGroupBy.transform()
中的 Bug 会在 grouper 使用axis=1
参数时不正确地触发"idxmin"
和"idxmax"
参数(GH 45986)。 -
当与空 DataFrame、分类分组器和
dropna=False
一起使用时,DataFrameGroupBy
中的错误会引发异常(GH 50634) -
SeriesGroupBy.value_counts()
中的错误未遵守sort=False
(GH 50482) -
DataFrameGroupBy.resample()
中的错误在对时间索引重新采样时从键列表获取结果时引发KeyError
(GH 50840) -
当分组器对
"ngroup"
参数具有axis=1
时,DataFrameGroupBy.transform()
和SeriesGroupBy.transform()
中的错误会在分组时不正确地引发异常(GH 45986) -
当数据具有重复列时,
DataFrameGroupBy.describe()
中的错误会产生不正确的结果(GH 50806) -
当
engine="numba"
时,DataFrameGroupBy.agg()
中的错误未能遵守as_index=False
(GH 51228) -
当传递函数列表时,
DataFrameGroupBy.agg()
、SeriesGroupBy.agg()
和Resampler.agg()
中的错误会忽略参数(GH 50863) -
在
DataFrameGroupBy.ohlc()
中忽略as_index=False
(GH 51413) -
在对列进行子集化后,
DataFrameGroupBy.agg()
中的错误(例如.groupby(...)[["a", "b"]]
)不会在结果中包含分组(GH 51186)
重塑
-
DataFrame.pivot_table()
中的错误导致可空数据类型和margins=True
时引发TypeError
(GH 48681) -
DataFrame.unstack()
和Series.unstack()
在MultiIndex
具有混合名称时解堆叠错误级别(GH 48763) -
DataFrame.melt()
中的错误导致丢失扩展数组数据类型(GH 41570) -
DataFrame.pivot()
中的错误,不将None
作为列名(GH 48293) -
DataFrame.join()
中的错误,当left_on
或right_on
是或包含CategoricalIndex
时,错误地引发AttributeError
(GH 48464) -
DataFrame.pivot_table()
中的错误,当结果是空的DataFrame
时,使用参数margins=True
引发ValueError
(GH 49240) -
在传递无效
validate
选项时,merge()
中澄清的错误消息(GH 49417) -
DataFrame.explode()
中的错误在多列具有NaN
值或空列表时引发ValueError
(GH 46084) -
DataFrame.transpose()
中的错误,带有timedelta64[ns]
端点的IntervalDtype
列(GH 44917) -
DataFrame.agg()
和Series.agg()
中的一个错误,在传递函数列表时会忽略参数 (GH 50863)
稀疏
-
Series.astype()
中的一个错误,当将带有datetime64[ns]
子类型的SparseDtype
转换为int64
dtype 时抛出异常,与非稀疏行为不一致 (GH 49631,:issue:50087) -
当将从
datetime64[ns]
转换为Sparse[datetime64[ns]]
时,Series.astype()
中的一个错误,错误地引发异常 (GH 50082) -
Series.sparse.to_coo()
中的一个错误,当MultiIndex
包含一个ExtensionArray
时引发SystemError
(GH 50996)
扩展数组
-
Series.mean()
中的一个错误,对可空整数不必要地溢出 (GH 48378) -
Series.tolist()
中的一个错误,对于可空的数据类型返回 numpy 标量而不是 python 标量 (GH 49890) -
当使用 pyarrow-backed 数据类型时,
Series.round()
中的一个错误,引发AttributeError
(GH 50437) -
当将一个空的 DataFrame 与一个具有相同扩展数据类型的另一个 DataFrame 连接时,结果 dtype 变为 object (GH 48510)
-
当指定
na_value
时,array.PandasArray.to_numpy()
中的一个错误,会在存在NA
值时抛出异常 (GH 40638) -
api.types.is_numeric_dtype()
中的一个错误,当自定义ExtensionDtype
返回_is_numeric
为True
时不会返回True
(GH 50563) -
Bug in
api.types.is_integer_dtype()
、api.types.is_unsigned_integer_dtype()
、api.types.is_signed_integer_dtype()
、api.types.is_float_dtype()
中,如果自定义的ExtensionDtype
返回True
,则kind
返回相应的 NumPy 类型(GH 50667) -
将非字符串值设置为
StringArray
引发ValueError
而不是TypeError
的错误(GH 49632) -
Bug in
DataFrame.reindex()
在具有 ExtensionDtype 的列的默认copy=True
关键字的情况下不遵守(结果也选择多列与 getitem([]
)不正确地导致复制)(GH 51197) -
Bug in
ArrowExtensionArray
逻辑操作&
和|
引发KeyError
(GH 51688)
Styler
- 修复了对具有
NA
值的可空 dtypeSeries
使用background_gradient()
的问题(GH 50712)
元数据
- 修复了
DataFrame.corr()
和DataFrame.cov()
中的元数据传播问题(GH 28283)
其他
-
Bug in 错误地接受包含“[pyarrow]”的 dtype 字符串超过一次(GH 51548)
-
Series.searchsorted()
中的 Bug 在接受DataFrame
作为参数value
时行为不一致(GH 49620) -
array()
中的 Bug 未能在接受DataFrame
输入时触发(GH 51167)
贡献者
这个版本共有 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 开发团队
-
Parfait Gasana
-
Patrick Hoefler
-
Pedro Nacht +
-
Philip +
-
Pietro Battiston
-
Pooja Subramaniam +
-
Pranav Saibhushan Ravuri +
-
Pranav. P. A +
-
Ralf Gommers +
-
RaphSku +
-
Richard Shadrach
-
Robsdedude +
-
罗杰
-
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 +
-
肖元 +
-
Xnot +
-
Yasin Tatar +
-
Yuanhao Geng
-
Yvan Cywan +
-
Zachary Moon +
-
郑博王 +
-
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 +
-
草莓沙滩拖鞋 +
-
tmoschou +
-
uzzell +
-
yqyqyq-W +
-
yun +
-
Ádám Lippai
-
김동현 (Daniel Donghyun Kim) +
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 单元测试从入门到精通
· 上周热点回顾(3.3-3.9)
· winform 绘制太阳,地球,月球 运作规律
2023-06-26 Bert Pytorch 源码分析:五、模型架构简图
2023-06-26 Bert Pytorch 源码分析:四、编解码器
2023-06-26 Bert Pytorch 源码分析:三、Transformer块
2020-06-26 PythonGuru 中文系列教程·翻译完成