Pandas-2-2-中文文档-五十-
Pandas 2.2 中文文档(五十)
0.24.2 版本的新内容(2019 年 3 月 12 日)
警告
0.24.x 系列发布将是最后支持 Python 2 的版本。未来的功能版本将仅支持 Python 3。查看Dropping Python 2.7以获取更多信息。
这些是 pandas 0.24.2 版本中的更改。查看发布说明以获取包括其他版本的完整更改日志。
修复的回归问题
-
修复了
DataFrame.all()
和DataFrame.any()
中bool_only=True
被忽略的回归问题(GH 25101) -
修复了使用混合类型列表进行
DataFrame
构造时可能导致段错误的问题。 (GH 25075) -
修复了
DataFrame.apply()
中的回归问题,在传递类似dict
的类作为参数时导致RecursionError
。(GH 25196) -
修复了
DataFrame.replace()
中regex=True
仅替换匹配字符串开头的模式的回归问题(GH 25259) -
修复了
DataFrame.duplicated()
中的回归问题,其中空数据框未返回布尔值数据类型的 Series。 (GH 25184) -
修复了
Series.min()
和Series.max()
中numeric_only=True
被忽略的回归问题,当Series
包含Categorical
数据时(GH 25299) -
修复了在
datetime64[ns]
dtype 的Series
对象之间的减法中,当右侧的Series
包含 null 值时错误地引发OverflowError
的回归问题(GH 25317) -
修复了
TimedeltaIndex
中的回归问题,其中np.sum(index)
错误地返回了零维对象而不是标量(GH 25282) -
修复了在
IntervalDtype
构造中的回归,其中传递带有“Interval”前缀的不正确字符串可能导致RecursionError
。(GH 25338) -
修复了从只读 NumPy 数组创建周期数据类型数组时的回归。(GH 25403)
-
修复了在
Categorical
中的回归,其中从分类Series
和与创建Series
中不同的显式categories=
构造它会创��无效对象,可能触发段错误。(GH 25318) -
修复了在将浮点数据转换为
Timedelta
数据时,to_timedelta()
丢失精度的回归。(GH 25077). -
修复了在没有 NumPy 的环境中从源代码安装 pip 时的问题。(GH 25193)
-
修复了在
DataFrame.replace()
中的回归,其中大量数字字符串将被强制转换为int64
,导致OverflowError
。(GH 25616) -
修复了在传递带有
sort=True
的自定义na_sentinel
值时,factorize()
中的回归。(GH 25409). -
修复了在使用 gzip 压缩时
DataFrame.to_csv()
写入重复行结束的回归。(GH 25311) ## Bug fixes
I/O
-
在终端尺寸未知时更好地处理终端打印。(GH 25080)
-
在 Python 3 中读取由 Python 2 创建的 HDF5 表格格式
DataFrame
时出现的错误。(GH 24925) -
在使用
orient='table'
由DataFrame.to_json()
生成的 JSON 中读取时出现的错误,其中index=False
。(GH 25170) -
在打印时,浮点索引可能具有不对齐的值的错误。(GH 25061)
Categorical
- 在分类数据上调用
Series.replace()
可能返回维度不正确的Series
的错误。(GH 24971)
Reshaping
-
在
GroupBy.transform()
中的错误,将函数应用于时区感知列将返回时区无关的结果(GH 24198) -
在
DataFrame.join()
中的错误,当在时区感知的DatetimeIndex
上进行连接时发生错误(GH 23931)
可视化
- 在
Series.plot()
中的错误,无法将次要 y 轴设置为对数刻度(GH 25545)
其他
-
在
Series.is_unique()
中的错误,未将单个NaN
视为唯一值(GH 25180) -
在
merge()
中的错误,当将空的DataFrame
与具有Int64
列的DataFrame
或所有为NaN
的Int64
列的非空DataFrame
合并时发生错误(GH 25183) -
在
IntervalTree
中的错误,由于在添加端点时溢出导致构造时发生RecursionError
,这也导致IntervalIndex
在索引操作期间崩溃(GH 25485) -
在
Series.size
中的错误,对于一些由扩展数组支持的Series
,而不是返回大小,而是引发异常(GH 25580) -
在重新采样中的错误,对于可空整数 dtype 列引发异常(GH 25580) ## 贡献者
总共有 25 人为此版本贡献了补丁。名字后面带有“+”的人第一次贡献了补丁。
-
Albert Villanova del Moral
-
Arno Veenstra +
-
chris-b1
-
Devin Petersohn +
-
EternalLearner42 +
-
Flavien Lambert +
-
gfyoung
-
Gioia Ballin
-
jbrockmendel
-
Jeff Reback
-
Jeremy Schendel
-
Johan von Forstner +
-
Joris Van den Bossche
-
Josh
-
Justin Zheng
-
Kendall Masse
-
Matthew Roeschke
-
Max Bolingbroke +
-
rbenes +
-
Sterling Paramore +
-
Tao He +
-
Thomas A Caswell
-
Tom Augspurger
-
Vibhu Agarwal +
-
William Ayd
-
Zach Angell ## 修复的回归
-
修复了
DataFrame.all()
和DataFrame.any()
中的回归,其中bool_only=True
被忽略(GH 25101) -
修复了通过传递混合类型的混合列表进行
DataFrame
构造时的问题可能导致分段错误。(GH 25075) -
修复了在
DataFrame.apply()
中的回归,当作为参数传递dict
-like 类时导致RecursionError
。(GH 25196) -
修复了在
DataFrame.replace()
中的回归,其中regex=True
只替换与字符串开头匹配的模式。(GH 25259) -
修复了在
DataFrame.duplicated()
中的回归,其中空数据框没有返回一个布尔值的系列。(GH 25184) -
修复了在
Series.min()
和Series.max()
中的回归,当Series
包含Categorical
数据时,忽略了numeric_only=True
。(GH 25299) -
修复了在两个具有
datetime64[ns]
dtype 的Series
对象之间的减法中的回归错误,当右侧的Series
包含空值时不正确地引发OverflowError
。(GH 25317) -
修复了在创建
TimedeltaIndex
时的回归,其中np.sum(index)
不正确地返回零维对象而不是标量。(GH 25282) -
修复了在构建
IntervalDtype
时的回归,其中传递一个带有“Interval”前缀的不正确字符串可能会导致RecursionError
。(GH 25338) -
修复了从只读 NumPy 数组创建周期 dtype 数组时的回归问题。(GH 25403)
-
修复了在
Categorical
中的回归,其中从一个分类Series
和一个明确的categories=
构造它,这与Series
中的不同,创建了一个无效的对象,可能触发分段错误。(GH 25318) -
修复了在
to_timedelta()
中失去精度的回归问题,当将浮点数据转换为Timedelta
数据时。(GH 25077)。 -
修复了在没有 NumPy 的环境中从源代码进行 pip 安装的问题 (GH 25193)
-
修复了在大量数字字符串被强制转换为
int64
时导致OverflowError
的回归错误 (GH 25616) -
在使用
sort=True
时,通过自定义na_sentinel
值传递给factorize()
时存在回归错误 (GH 25409) -
在使用 gzip 压缩时,
DataFrame.to_csv()
写入重复行结束符的回归错误已修复 (GH 25311)
Bug 修复
输入输出(I/O)
-
当终端尺寸未知时更好地处理终端打印 (GH 25080)
-
在 Python 3 中读取 Python 2 中创建的 HDF5 表格格式
DataFrame
时存在 Bug (GH 24925) -
在使用
index=False
生成的orient='table'
的 JSON 中存在 Bug,该 JSON 是由DataFrame.to_json()
生成的 (GH 25170) -
打印时浮点索引可能具有不对齐的值的 Bug (GH 25061)
分类(Categorical)
- 在分类数据上调用
Series.replace()
可能会返回维度不正确的Series
的 Bug 已修复 (GH 24971)
重塑(Reshaping)
-
在应用函数到具有时区信息的列时,
GroupBy.transform()
中存在 Bug,会返回时区不明确的结果 (GH 24198) -
在具有时区信息的
DatetimeIndex
上使用DataFrame.join()
连接时存在 Bug (GH 23931)
可视化(Visualization)
- 在
Series.plot()
中,无法将辅助 y 轴设置为对数刻度的 Bug 已修复 (GH 25545)
其他(Other)
-
在
NaN
的单个出现不被认为是唯一的情况下,Series.is_unique()
存在 Bug 已修复 (GH 25180) -
在使用
merge()
时,当将空的DataFrame
与具有Int64
列的非空DataFrame
合并时,该列全为NaN
,会出现错误(GH 25183) -
IntervalTree
中的错误,在构造时由于添加端点时溢出而导致RecursionError
发生,这也导致IntervalIndex
在索引操作期间崩溃(GH 25485) -
Series.size
中的错误,对于一些由扩展数组支持的Series
,而不是返回大小,而是引发错误(GH 25580) -
在对可空整数类型列进行重新采样时引发错误(GH 25580)
贡献者
总共有 25 人为这个版本贡献了补丁。名字后面带有“+”的人第一次贡献了补丁。
-
Albert Villanova del Moral
-
Arno Veenstra +
-
chris-b1
-
Devin Petersohn +
-
EternalLearner42 +
-
Flavien Lambert +
-
gfyoung
-
Gioia Ballin
-
jbrockmendel
-
Jeff Reback
-
Jeremy Schendel
-
Johan von Forstner +
-
Joris Van den Bossche
-
Josh
-
Justin Zheng
-
Kendall Masse
-
Matthew Roeschke
-
Max Bolingbroke +
-
rbenes +
-
Sterling Paramore +
-
Tao He +
-
Thomas A Caswell
-
Tom Augspurger
-
Vibhu Agarwal +
-
William Ayd
-
Zach Angell
0.24.1 版本中的新功能(2019 年 2 月 3 日)
警告
0.24.x 系列发布将是最后支持 Python 2 的版本。未来的功能发布将仅支持 Python 3。查看Dropping Python 2.7了解更多信息。
这些是 pandas 0.24.1 的更改。查看发布说明获取包括 pandas 其他版本在内的完整更改日志。查看 0.24.0 版本新特性(2019 年 1 月 25 日)获取 0.24.0 更改日志。
API 更改
更改 Index
集合操作的 sort
参数
Index.union()
的默认 sort
值已从 True
更改为 None
(GH 24959)。然而,默认 behavior 保持不变:结果被排序,除非
-
self
和other
相同 -
self
或other
为空。 -
self
或other
包含无法比较的值(引发RuntimeWarning
)。
此更改将允许在未来版本中 sort=True
意味着“始终排序”。
更改同样适用于Index.difference()
和Index.symmetric_difference()
,当值无法比较时,结果不会排序。
Index.intersection()
的 sort
选项有三个变化。
-
默认已从
True
更改为False
,以恢复 pandas 0.23.4 及更早版本的默认不排序行为。 -
现在可以使用
sort=None
来获取sort=True
的行为。这仅在self
和other
的值不相同时才会排序结果。 -
不再允许值为
sort=True
。pandas 的未来版本将正确支持sort=True
,意思是“始终排序”。 ## 修复回归
-
在
DataFrame
包含超过 255 列或错误转换非有效 Python 标识符的列名时,修复了DataFrame.to_dict()
中records
方向引发AttributeError
的回归(GH 24939, GH 24940)。 -
修复了使用 MySQL/pymysql 传递某些查询时
read_sql()
中的回归错误(GH 24988)。 -
修复了
Index.intersection
中的回归问题,错误地默认排序值 (GH 24959). -
修复了在将空
DataFrame
与多个时区感知列合并时,merge()
中的回归问题 (GH 25014). -
修复了在
Series.rename_axis()
和DataFrame.rename_axis()
中传递None
未能移除轴名称的回归问题 (GH 25034) -
修复了
to_timedelta()
中box=False
选项错误地返回datetime64
对象而不是timedelta64
对象的回归问题(GH 24961) -
修复了自定义可哈希类型不能用作
DataFrame.set_index()
中列键的回归问题 (GH 24969) ## Bug 修复
重塑
DataFrame.groupby()
中的一个 bug,在存在时间更改(DST)且分组频率为'1d'
时出现问题 (GH 24972)
可视化
- 修复了隐式注册的 matplotlib 转换器不显示警告的问题。有关更多信息,请参见 Restore Matplotlib datetime converter registration (GH 24963).
其他
- 修复了访问 IPython 配置对象后打印 DataFrame 的 HTML 表示时出现 AttributeError 的问题 (GH 25036) ## 贡献者
本次发布共有 7 人贡献了补丁。名字后带有“+”符号的人第一次贡献了补丁。
-
Alex Buchkovsky
-
Roman Yurchak
-
h-vetinari
-
jbrockmendel
-
Jeremy Schendel
-
Joris Van den Bossche
-
Tom Augspurger ## API 变更
更改了 Index
设置操作的 sort
参数
Index.union()
的默认 sort
值已从 True
更改为 None
(GH 24959)。然而,默认 行为 保持不变:结果会排序,除非
-
self
和other
相同 -
self
或other
为空 -
self
或other
包含无法比较的值(会引发RuntimeWarning
)。
此变更将允许 sort=True
在未来版本中表示“始终排序”。
当值无法进行比较时,Index.difference()
和 Index.symmetric_difference()
的结果不会排序,此变化也适用。
Index.intersection()
的 sort
选项有三种方式发生了变化。
-
默认值已从
True
更改为False
,以恢复 pandas 0.23.4 及更早版本默认情况下不进行排序的行为。 -
sort=True
的行为现在可以通过sort=None
来获得。只有当self
和other
中的值不相同时,才会对结果进行排序。 -
不再允许值
sort=True
。未来版本的 pandas 将正确支持sort=True
表示“始终排序”。
更改 Index
集合操作的 sort
参数
Index.union()
的默认 sort
值已从 True
更改为 None
(GH 24959)。然而,默认 行为 保持不变:结果会排序,除非
-
self
和other
相同 -
self
或other
为空 -
self
或other
包含无法比较的值(会引发RuntimeWarning
)。
此变更将允许 sort=True
在未来版本中表示“始终排序”。
当值无法进行比较时,Index.difference()
和 Index.symmetric_difference()
的结果不会排序,此变化也适用。
Index.intersection()
的 sort
选项有三种方式发生了变化。
-
默认值已从
True
更改为False
,以恢复 pandas 0.23.4 及更早版本默认情况下不进行排序的行为。 -
sort=True
的行为现在可以通过sort=None
来获得。只有当self
和other
中的值不相同时,才会对结果进行排序。 -
不再允许使用
sort=True
。未来版本的 pandas 将正确支持sort=True
,意思是“始终排序”。
修复的回归问题
-
修复了在使用
records
方向时DataFrame.to_dict()
在包含超过 255 列的DataFrame
时引发AttributeError
,或者错误地转换不是有效 python 标识符的列名的回归问题(GH 24939, GH 24940)。 -
修复了在使用 MySQL/pymysql 时传递某些查询时
read_sql()
的回归问题(GH 24988)。 -
修复了在默认情况下
Index.intersection
错误地对值进行排序的回归问题(GH 24959)。 -
修复了当在一个带有多个时区感知列的空
DataFrame
上合并一个时区感知列时的回归问题(GH 25014)。 -
修复了在
Series.rename_axis()
和DataFrame.rename_axis()
中传递None
时未能移除轴名称的回归问题(GH 25034) -
修复了在使用
box=False
时to_timedelta()
错误地返回datetime64
对象而不是timedelta64
对象的回归问题(GH 24961) -
修复了自定义可散列类型无法在
DataFrame.set_index()
中用作列键的回归问题(GH 24969)
错误修复
重塑
- 在有时间更改(DST)和分组频率为
'1d'
时,DataFrame.groupby()
与Grouper
中的错误(GH 24972)
可视化
- 修复了未显示隐式注册的 matplotlib 转换器的警告。更多信息请参阅 Restore Matplotlib datetime converter registration(GH 24963)。
其他
- 在访问 IPython 配置对象后打印 DataFrame 的 HTML repr 时修复了 AttributeError(GH 25036)
贡献者
总共有 7 人为这个版本贡献了补丁。名字后面带有“+”的人是第一次贡献补丁。
-
Alex Buchkovsky
-
Roman Yurchak
-
h-vetinari
-
jbrockmendel
-
Jeremy Schendel
-
Joris Van den Bossche
-
Tom Augspurger
0.24.0 中的新功能(2019 年 1 月 25 日)
警告
0.24.x 系列发布将是最后一个支持 Python 2 的版本。 未来的功能发布将仅支持 Python 3。 有关更多详情,请参阅Dropping Python 2.7。
这是从 0.23.4 的重大发布,并包括许多 API 更改、新功能、增强功能和性能改进以及大量的错误修复。
亮点包括:
-
可选整数 NA 支持
-
访问 Series 或 Index 支撑数组的新 API
-
创建数组的新顶级方法
-
在 Series 或 DataFrame 中存储间隔和周期数据
-
支持在两个 MultiIndexes 上进行连接
在更新之前,请检查 API 更改和弃用。
这些是 pandas 0.24.0 中的更改。 请参阅发布说明以获取包括 pandas 其他版本的完整更改日志。
增强
可选整数 NA 支持
pandas 已经获得了具有缺失值的整数 dtype 的能力。 通过使用扩展类型来启用此长期请求的功能。
注意
IntegerArray 目前处于试验阶段。 其 API 或实现可能会在没有警告的情况下更改。
我们可以使用指定的 dtype 构造一个Series
。 dtype 字符串Int64
是 pandas 的ExtensionDtype
。 使用传统的缺失值标记np.nan
来指定列表或数组将推断为整数 dtype。 在字符串输出中,Series
的显示也将使用NaN
来指示缺失值。 (GH 20700, GH 20747, GH 22441, GH 21789, GH 22346)
In [1]: s = pd.Series([1, 2, np.nan], dtype='Int64')
In [2]: s
Out[2]:
0 1
1 2
2 <NA>
Length: 3, dtype: Int64
对这些 dtype 的操作将像其他 pandas 操作一样传播NaN
。
# arithmetic
In [3]: s + 1
Out[3]:
0 2
1 3
2 <NA>
Length: 3, dtype: Int64
# comparison
In [4]: s == 1
Out[4]:
0 True
1 False
2 <NA>
Length: 3, dtype: boolean
# indexing
In [5]: s.iloc[1:3]
Out[5]:
1 2
2 <NA>
Length: 2, dtype: Int64
# operate with other dtypes
In [6]: s + s.iloc[1:3].astype('Int8')
Out[6]:
0 <NA>
1 4
2 <NA>
Length: 3, dtype: Int64
# coerce when needed
In [7]: s + 0.01
Out[7]:
0 1.01
1 2.01
2 <NA>
Length: 3, dtype: Float64
这些 dtype 可以作为DataFrame
的一部分操作。
In [8]: df = pd.DataFrame({'A': s, 'B': [1, 1, 3], 'C': list('aab')})
In [9]: df
Out[9]:
A B C
0 1 1 a
1 2 1 a
2 <NA> 3 b
[3 rows x 3 columns]
In [10]: df.dtypes
Out[10]:
A Int64
B int64
C object
Length: 3, dtype: object
这些 dtype 可以合并、重塑和转换。
In [11]: pd.concat([df[['A']], df[['B', 'C']]], axis=1).dtypes
Out[11]:
A Int64
B int64
C object
Length: 3, dtype: object
In [12]: df['A'].astype(float)
Out[12]:
0 1.0
1 2.0
2 NaN
Name: A, Length: 3, dtype: float64
sum
等减少和分组操作有效。
In [13]: df.sum()
Out[13]:
A 3
B 5
C aab
Length: 3, dtype: object
In [14]: df.groupby('B').A.sum()
Out[14]:
B
1 3
3 0
Name: A, Length: 2, dtype: Int64
警告
整数 NA 支持当前使用大写的 dtype 版本,例如Int8
,而不是传统的int8
。 这可能在将来更改。
有关更多信息,请参阅可空整数数据类型。### 访问 Series 或 Index 中的值
Series.array
和 Index.array
已添加用于提取支持 Series
或 Index
的数组。 (GH 19954, GH 23623)
In [15]: idx = pd.period_range('2000', periods=4)
In [16]: idx.array
Out[16]:
<PeriodArray>
['2000-01-01', '2000-01-02', '2000-01-03', '2000-01-04']
Length: 4, dtype: period[D]
In [17]: pd.Series(idx).array
Out[17]:
<PeriodArray>
['2000-01-01', '2000-01-02', '2000-01-03', '2000-01-04']
Length: 4, dtype: period[D]
从历史上看,这可能是用 series.values
来完成的,但是用 .values
来完成时,无法确定返回的值是实际数组,还是它的某种变换,或者是 pandas 自定义数组之一(例如 Categorical
)。例如,对于 PeriodIndex
,.values
每次生成一组新的周期对象的 ndarray。
In [18]: idx.values
Out[18]:
array([Period('2000-01-01', 'D'), Period('2000-01-02', 'D'),
Period('2000-01-03', 'D'), Period('2000-01-04', 'D')], dtype=object)
In [19]: id(idx.values)
Out[19]: 140678188264656
In [20]: id(idx.values)
Out[20]: 140678188258896
如果你需要一个实际的 NumPy 数组,请使用 Series.to_numpy()
或 Index.to_numpy()
。
In [21]: idx.to_numpy()
Out[21]:
array([Period('2000-01-01', 'D'), Period('2000-01-02', 'D'),
Period('2000-01-03', 'D'), Period('2000-01-04', 'D')], dtype=object)
In [22]: pd.Series(idx).to_numpy()
Out[22]:
array([Period('2000-01-01', 'D'), Period('2000-01-02', 'D'),
Period('2000-01-03', 'D'), Period('2000-01-04', 'D')], dtype=object)
对于由普通 NumPy 数组支持的 Series 和 Indexes,Series.array
将返回一个新的 arrays.PandasArray
,它是一个细(不复制)的包装器,围绕着一个numpy.ndarray
。 PandasArray
本身并不特别有用,但它提供了与 pandas 中定义的任何扩展数组或由第三方库定义的扩展数组相同的接口。
In [23]: ser = pd.Series([1, 2, 3])
In [24]: ser.array
Out[24]:
<NumpyExtensionArray>
[1, 2, 3]
Length: 3, dtype: int64
In [25]: ser.to_numpy()
Out[25]: array([1, 2, 3])
我们没有移除或废弃 Series.values
或 DataFrame.values
,但我们强烈建议使用 .array
或 .to_numpy()
代替。
更多信息请参阅 Dtypes 和 Attributes and Underlying Data。### pandas.array
: 一个用于创建数组的新顶级方法
新的顶级方法 array()
已添加用于创建一维数组(GH 22860)。这可以用于创建任何扩展数组,包括由第三方库注册的扩展数组。更多有关扩展数组的信息,请参阅 dtypes 文档。
In [26]: pd.array([1, 2, np.nan], dtype='Int64')
Out[26]:
<IntegerArray>
[1, 2, <NA>]
Length: 3, dtype: Int64
In [27]: pd.array(['a', 'b', 'c'], dtype='category')
Out[27]:
['a', 'b', 'c']
Categories (3, object): ['a', 'b', 'c']
传递数据,没有专用扩展类型(例如浮点数、整数等),将返回一个新的 arrays.PandasArray
,它只是一个细(不复制)的包装器,围绕着一个numpy.ndarray
,满足 pandas 扩展数组接口。
In [28]: pd.array([1, 2, 3])
Out[28]:
<IntegerArray>
[1, 2, 3]
Length: 3, dtype: Int64
单独使用 PandasArray
并不是一个非常有用的对象。但是,如果您需要编写适用于任何 ExtensionArray
的低级代码,PandasArray
可以满足这个需求。
请注意,默认情况下,如果未指定 dtype
,则从数据推断返回数组的 dtype。特别要注意的是,第一个示例 [1, 2, np.nan]
会返回一个浮点数数组,因为 NaN
是一个浮点数。
In [29]: pd.array([1, 2, np.nan])
Out[29]:
<IntegerArray>
[1, 2, <NA>]
Length: 3, dtype: Int64
``` ### 在 Series 和 DataFrame 中存储区间和周期数据
现在可以将 `Interval` 和 `Period` 数据存储在 `Series` 或 `DataFrame` 中,除了以前的 `IntervalIndex` 和 `PeriodIndex` ([GH 19453](https://github.com/pandas-dev/pandas/issues/19453), [GH 22862](https://github.com/pandas-dev/pandas/issues/22862))。
```py
In [30]: ser = pd.Series(pd.interval_range(0, 5))
In [31]: ser
Out[31]:
0 (0, 1]
1 (1, 2]
2 (2, 3]
3 (3, 4]
4 (4, 5]
Length: 5, dtype: interval
In [32]: ser.dtype
Out[32]: interval[int64, right]
对于周期数据:
In [33]: pser = pd.Series(pd.period_range("2000", freq="D", periods=5))
In [34]: pser
Out[34]:
0 2000-01-01
1 2000-01-02
2 2000-01-03
3 2000-01-04
4 2000-01-05
Length: 5, dtype: period[D]
In [35]: pser.dtype
Out[35]: period[D]
以前,这些都会被转换为具有对象 dtype 的 NumPy 数组。一般来说,当在 Series
或 DataFrame
中存储一组区间或周期时,这样做应该会产生更好的性能。
使用 Series.array
从 Series
中提取区间或周期的基础数组:
In [36]: ser.array
Out[36]:
<IntervalArray>
[(0, 1], (1, 2], (2, 3], (3, 4], (4, 5]]
Length: 5, dtype: interval[int64, right]
In [37]: pser.array
Out[37]:
<PeriodArray>
['2000-01-01', '2000-01-02', '2000-01-03', '2000-01-04', '2000-01-05']
Length: 5, dtype: period[D]
这些返回一个 arrays.IntervalArray
或 arrays.PeriodArray
的实例,这是支持区间和周期数据的新扩展数组。
警告
为了向后兼容,对于区间和周期数据,Series.values
继续返回对象的 NumPy 数组。我们建议在需要存储在 Series
中的数据数组时使用 Series.array
,在需要 NumPy 数组时使用 Series.to_numpy()
。
更多信息请参见 数据类型 和 属性和底层数据 ### 与两个多索引连接
DataFrame.merge()
和 DataFrame.join()
现在可以用于在重叠的索引级别上连接多级索引的 Dataframe
实例 (GH 6360)
查看合并、连接和连接文档部分。
In [38]: index_left = pd.MultiIndex.from_tuples([('K0', 'X0'), ('K0', 'X1'),
....: ('K1', 'X2')],
....: names=['key', 'X'])
....:
In [39]: left = pd.DataFrame({'A': ['A0', 'A1', 'A2'],
....: 'B': ['B0', 'B1', 'B2']}, index=index_left)
....:
In [40]: index_right = pd.MultiIndex.from_tuples([('K0', 'Y0'), ('K1', 'Y1'),
....: ('K2', 'Y2'), ('K2', 'Y3')],
....: names=['key', 'Y'])
....:
In [41]: right = pd.DataFrame({'C': ['C0', 'C1', 'C2', 'C3'],
....: 'D': ['D0', 'D1', 'D2', 'D3']}, index=index_right)
....:
In [42]: left.join(right)
Out[42]:
A B C D
key X Y
K0 X0 Y0 A0 B0 C0 D0
X1 Y0 A1 B1 C0 D0
K1 X2 Y1 A2 B2 C1 D1
[3 rows x 4 columns]
对于早期版本,可以使用以下方法。
In [43]: pd.merge(left.reset_index(), right.reset_index(),
....: on=['key'], how='inner').set_index(['key', 'X', 'Y'])
....:
Out[43]:
A B C D
key X Y
K0 X0 Y0 A0 B0 C0 D0
X1 Y0 A1 B1 C0 D0
K1 X2 Y1 A2 B2 C1 D1
[3 rows x 4 columns]
``` ### 函数 `read_html` 增强
`read_html()` 以前忽略了 `colspan` 和 `rowspan` 属性。现在它理解它们,将它们视为具有相同值的单元格序列。 ([GH 17054](https://github.com/pandas-dev/pandas/issues/17054))
```py
In [44]: from io import StringIO
In [45]: result = pd.read_html(StringIO("""
....: <table>
....: <thead>
....: <tr>
....: <th>A</th><th>B</th><th>C</th>
....: </tr>
....: </thead>
....: <tbody>
....: <tr>
....: <td colspan="2">1</td><td>2</td>
....: </tr>
....: </tbody>
....: </table>"""))
....:
先前行为:
In [13]: result
Out [13]:
[ A B C
0 1 2 NaN]
新行为:
In [46]: result
Out[46]:
[ A B C
0 1 1 2
[1 rows x 3 columns]]
新的 Styler.pipe()
方法
Styler
类已经获得了一个 pipe()
方法。这提供了一种方便的方式来应用用户预定义的样式函数,并且可以帮助减少在笔记本中重复使用 DataFrame 样式功能时的“样板文件”。 (GH 23229)
In [47]: df = pd.DataFrame({'N': [1250, 1500, 1750], 'X': [0.25, 0.35, 0.50]})
In [48]: def format_and_align(styler):
....: return (styler.format({'N': '{:,}', 'X': '{:.1%}'})
....: .set_properties(**{'text-align': 'right'}))
....:
In [49]: df.style.pipe(format_and_align).set_caption('Summary of results.')
Out[49]: <pandas.io.formats.style.Styler at 0x7ff231a272e0>
pandas 中其他类已经存在类似的方法,包括 DataFrame.pipe()
、GroupBy.pipe()
和 Resampler.pipe()
。
在多级索引中重命名名称
DataFrame.rename_axis()
现在支持 index
和 columns
参数,Series.rename_axis()
支持 index
参数(GH 19978)。
此更改允许传递字典,以便更改 MultiIndex
的一些名称。
示例:
In [50]: mi = pd.MultiIndex.from_product([list('AB'), list('CD'), list('EF')],
....: names=['AB', 'CD', 'EF'])
....:
In [51]: df = pd.DataFrame(list(range(len(mi))), index=mi, columns=['N'])
In [52]: df
Out[52]:
N
AB CD EF
A C E 0
F 1
D E 2
F 3
B C E 4
F 5
D E 6
F 7
[8 rows x 1 columns]
In [53]: df.rename_axis(index={'CD': 'New'})
Out[53]:
N
AB New EF
A C E 0
F 1
D E 2
F 3
B C E 4
F 5
D E 6
F 7
[8 rows x 1 columns]
查看重命名的高级文档以获取更多详细信息。 ### 其他增强功能
-
merge()
现在直接允许在DataFrame
和命名Series
类型对象之间进行合并,无需事先将Series
对象转换为DataFrame
(GH 21220) -
ExcelWriter
现在接受mode
作为关键字参数,使用openpyxl
引擎时允许追加到现有工作簿(GH 3441) -
FrozenList
已经获得了.union()
和.difference()
方法。此功能极大地简化了依赖于显式排除某些列的 groupby 操作。有关更多信息,请参阅将对象拆分为组。 (GH 15475, GH 15506) -
DataFrame.to_parquet()
现在接受index
作为参数,允许用户覆盖引擎的默认行为,包括或省略结果 Parquet 文件中的数据框索引。 (GH 20768) -
read_feather()
现在接受columns
作为参数,允许用户指定应读取哪些列。 (GH 24025) -
DataFrame.corr()
和Series.corr()
现在接受可调用的方法来进行相关性的一般计算,例如直方图交集。 (GH 22684) -
DataFrame.to_string()
现在接受decimal
作为参数,允许用户指定输出中应使用的十进制分隔符。 (GH 23614) -
DataFrame.to_html()
现在接受render_links
作为参数,允许用户生成带有链接到数据框中任何 URL 的 HTML。请参阅 IO 文档中的 HTML 编写部分以查看示例用法。 (GH 2679) -
pandas.read_csv()
现在支持将 pandas 扩展类型作为dtype
参数的参数,允许用户在读取 CSV 时使用 pandas 扩展类型。 (GH 23228) -
shift()
方法现在接受fill_value
作为参数,允许用户指定在空期间中使用的值,而不是 NA/NaT。 (GH 15486) -
to_datetime()
现在在传入format
时支持%Z
和%z
指令(GH 13486) -
Series.mode()
和DataFrame.mode()
现在支持dropna
参数,可用于指定是否应考虑NaN
/NaT
值 (GH 17534) -
DataFrame.to_csv()
和Series.to_csv()
现在在传入文件句柄时支持compression
关键字。(GH 21227) -
Index.droplevel()
现在也对平坦索引实现了,以便与MultiIndex
兼容 (GH 21115) -
Series.droplevel()
和DataFrame.droplevel()
现已实现(GH 20342) -
新增对通过
gcsfs
库读取/写入 Google Cloud Storage 的支持(GH 19454, GH 23094) -
DataFrame.to_gbq()
和read_gbq()
的签名和文档已更新以反映pandas-gbq 库版本 0.8.0的更改。新增了一个credentials
参数,可用于使用任何类型的google-auth 凭据。(GH 21627, GH 22557, GH 23662) -
新方法
HDFStore.walk()
将递归遍历 HDF5 文件的组层次结构 (GH 10932) -
read_html()
现在可以跨越colspan
和rowspan
复制单元格数据,并且如果未提供header
参数且没有thead
,则将所有th
表行视为表头。 -
Series.nlargest()
,Series.nsmallest()
,DataFrame.nlargest()
, 和DataFrame.nsmallest()
现在接受值"all"
作为keep
参数。这将保留所有与第 n 个最大/最小值相同的数值 (GH 16818)。 -
IntervalIndex
增加了set_closed()
方法,用于更改现有的closed
值 (GH 21670)。 -
to_csv()
,to_csv()
,to_json()
, 和to_json()
现在支持compression='infer'
,根据文件扩展名推断压缩方式(GH 15008)。to_csv
、to_json
和to_pickle
方法的默认压缩方式已更新为'infer'
(GH 22004)。 -
DataFrame.to_sql()
现在支持对支持的数据库写入TIMESTAMP WITH TIME ZONE
类型。对于不支持时区的数据库,日期时间数据将存储为不带时区信息的本地时间戳。参见日期时间数据类型以了解其影响 (GH 9086)。 -
to_timedelta()
现在支持 ISO 格式的时间增量字符串 (GH 21877)。 -
Series
和DataFrame
构造函数现在支持Iterable
对象 (GH 2193) -
DatetimeIndex
新增了DatetimeIndex.timetz
属性。该属性返回带有时区信息的本地时间。 (GH 21358) -
round()
,ceil()
, 和floor()
方法现在支持一个ambiguous
参数来处理舍入为模糊时间的日期时间 (GH 18946),以及一个nonexistent
参数来处理舍入为不存在时间的日期时间。参见本地化时不存在的时间 (GH 22647) -
resample()
方法的结果现在与groupby()
类似可迭代 (GH 15314). -
Series.resample()
和DataFrame.resample()
方法新增了Resampler.quantile()
(GH 15023). -
DataFrame.resample()
和Series.resample()
方法在使用PeriodIndex
时将会像使用DatetimeIndex
时一样,尊重base
参数。 (GH 23882) -
pandas.api.types.is_list_like()
现在具有一个关键字allow_sets
,默认为True
;如果为False
,则所有的set
实例将不再被视为“类似列表”(GH 23061)。 -
Index.to_frame()
现在支持覆盖列名(GH 22580)。 -
Categorical.from_codes()
现在可以接受一个dtype
参数,作为传递categories
和ordered
的替代方法(GH 24398)。 -
新属性
__git_version__
将返回当前构建的 git 提交 sha(GH 21295)。 -
与 Matplotlib 3.0 兼容性(GH 22790)。
-
添加了
Interval.overlaps()
,arrays.IntervalArray.overlaps()
和IntervalIndex.overlaps()
用于确定间隔型对象之间的重叠情况(GH 21998)。 -
read_fwf()
现在接受关键字infer_nrows
(GH 15138)。 -
to_parquet()
现在在engine = 'pyarrow'
时支持将DataFrame
以列的子集分区写入 Parquet 文件目录(GH 23283)。 -
Timestamp.tz_localize()
,DatetimeIndex.tz_localize()
和Series.tz_localize()
现在具有nonexistent
参数,用于替代处理不存在的时间。参见本地化时不存在的时间(GH 8917,GH 24466)。 -
Index.difference()
、Index.intersection()
、Index.union()
和Index.symmetric_difference()
现在具有可选的sort
参数,用于控制是否应尽可能对结果进行排序(GH 17839, GH 24471) -
read_excel()
现在接受usecols
作为列名列表或可调用对象(GH 18273) -
MultiIndex.to_flat_index()
已添加,将多个级别展平为单个级别的Index
对象。 -
DataFrame.to_stata()
和pandas.io.stata.StataWriter117
可以将混合字符串列写入 Stata strl 格式(GH 23633) -
DataFrame.between_time()
和DataFrame.at_time()
已经增加了axis
参数(GH 8839) -
DataFrame.to_records()
现在接受index_dtypes
和column_dtypes
参数,允许在存储的列和索引记录中使用不同的数据类型(GH 18146) -
IntervalIndex
已经增加了is_overlapping
属性,用于指示IntervalIndex
是否包含任何重叠的区间(GH 23309) -
pandas.DataFrame.to_sql()
已增加method
参数,用于控制 SQL 插入子句。请参阅文档中的 插入方法 部分。(GH 8953) -
DataFrame.corrwith()
现在支持 Spearman's 秩相关、Kendall's tau 以及可调用的相关方法。(GH 21925) -
DataFrame.to_json()
,DataFrame.to_csv()
,DataFrame.to_pickle()
,以及其他导出方法现在支持路径参数中的波浪号(~)。(GH 23473) ## 不兼容的 API 更改
pandas 0.24.0 包含许多破坏 API 的更改。
增加了依赖项的最低版本
我们已更新我们的依赖项的最低支持版本(GH 21242, GH 18742, GH 23774, GH 24767)。如果已安装,我们现在要求:
Package | Minimum Version | Required |
---|---|---|
numpy | 1.12.0 | X |
bottleneck | 1.2.0 | |
fastparquet | 0.2.1 | |
matplotlib | 2.0.0 | |
numexpr | 2.6.1 | |
pandas-gbq | 0.8.0 | |
pyarrow | 0.9.0 | |
pytables | 3.4.2 | |
scipy | 0.18.1 | |
xlrd | 1.0.0 | |
pytest (dev) | 3.6 |
另外,我们不再依赖于feather-format
进行基于 feather 的存储,并用对pyarrow
的引用替换了它(GH 21639 和 GH 23053)。 ### DataFrame.to_csv
的 line_terminator
使用 os.linesep
DataFrame.to_csv()
现在使用 os.linesep()
而不是 '\n'
作为默认行终止符 (GH 20353)。这个更改仅影响在 Windows 上运行时,即使在line_terminator
中传递'\n'
时,也会使用'\r\n'
作为行终止符。
Windows 上的先前行为:
In [1]: data = pd.DataFrame({"string_with_lf": ["a\nbc"],
...: "string_with_crlf": ["a\r\nbc"]})
In [2]: # When passing file PATH to to_csv,
...: # line_terminator does not work, and csv is saved with '\r\n'.
...: # Also, this converts all '\n's in the data to '\r\n'.
...: data.to_csv("test.csv", index=False, line_terminator='\n')
In [3]: with open("test.csv", mode='rb') as f:
...: print(f.read())
Out[3]: b'string_with_lf,string_with_crlf\r\n"a\r\nbc","a\r\r\nbc"\r\n'
In [4]: # When passing file OBJECT with newline option to
...: # to_csv, line_terminator works.
...: with open("test2.csv", mode='w', newline='\n') as f:
...: data.to_csv(f, index=False, line_terminator='\n')
In [5]: with open("test2.csv", mode='rb') as f:
...: print(f.read())
Out[5]: b'string_with_lf,string_with_crlf\n"a\nbc","a\r\nbc"\n'
Windows 上的新行为:
显式传递line_terminator
,将line terminator
设置为该字符。
In [1]: data = pd.DataFrame({"string_with_lf": ["a\nbc"],
...: "string_with_crlf": ["a\r\nbc"]})
In [2]: data.to_csv("test.csv", index=False, line_terminator='\n')
In [3]: with open("test.csv", mode='rb') as f:
...: print(f.read())
Out[3]: b'string_with_lf,string_with_crlf\n"a\nbc","a\r\nbc"\n'
在 Windows 上,os.linesep
的值为'\r\n'
,因此如果未设置line_terminator
,则使用'\r\n'
作为行终止符。
In [1]: data = pd.DataFrame({"string_with_lf": ["a\nbc"],
...: "string_with_crlf": ["a\r\nbc"]})
In [2]: data.to_csv("test.csv", index=False)
In [3]: with open("test.csv", mode='rb') as f:
...: print(f.read())
Out[3]: b'string_with_lf,string_with_crlf\r\n"a\nbc","a\r\nbc"\r\n'
对于文件对象,仅指定newline
不足以设置行终止符。即使在这种情况下,您也必须显式传递line_terminator
。
In [1]: data = pd.DataFrame({"string_with_lf": ["a\nbc"],
...: "string_with_crlf": ["a\r\nbc"]})
In [2]: with open("test2.csv", mode='w', newline='\n') as f:
...: data.to_csv(f, index=False)
In [3]: with open("test2.csv", mode='rb') as f:
...: print(f.read())
Out[3]: b'string_with_lf,string_with_crlf\r\n"a\nbc","a\r\nbc"\r\n'
``` ### 在 Python 引擎中正确处理带有`np.nan`的字符串数据类型列
在使用 Python 引擎的`read_excel()`和`read_csv()`中存在一个 bug,其中缺失值在`dtype=str`和`na_filter=True`的情况下转换为`'nan'`。现在,这些缺失值被转换为字符串缺失指示符`np.nan`。([GH 20377](https://github.com/pandas-dev/pandas/issues/20377))
*之前的行为*:
```py
In [5]: data = 'a,b,c\n1,,3\n4,5,6'
In [6]: df = pd.read_csv(StringIO(data), engine='python', dtype=str, na_filter=True)
In [7]: df.loc[0, 'b']
Out[7]:
'nan'
新的行为:
In [54]: data = 'a,b,c\n1,,3\n4,5,6'
In [55]: df = pd.read_csv(StringIO(data), engine='python', dtype=str, na_filter=True)
In [56]: df.loc[0, 'b']
Out[56]: nan
请注意,我们现在输出np.nan
本身而不是其字符串形式。 ### 解析带有时区偏移的日期时间字符串
以前,使用to_datetime()
或DatetimeIndex
解析带有 UTC 偏移的日期时间字符串会自动将日期时间转换为 UTC 而不进行时区本地化。这与使用Timestamp
解析相同日期时间字符串的行为不一致,后者会保留tz
属性中的 UTC 偏移。现在,当所有日期时间字符串具有相同的 UTC 偏移时,to_datetime()
会在tz
属性中保留 UTC 偏移(GH 17697,GH 11736,GH 22457)
之前的行为:
In [2]: pd.to_datetime("2015-11-18 15:30:00+05:30")
Out[2]: Timestamp('2015-11-18 10:00:00')
In [3]: pd.Timestamp("2015-11-18 15:30:00+05:30")
Out[3]: Timestamp('2015-11-18 15:30:00+0530', tz='pytz.FixedOffset(330)')
# Different UTC offsets would automatically convert the datetimes to UTC (without a UTC timezone)
In [4]: pd.to_datetime(["2015-11-18 15:30:00+05:30", "2015-11-18 16:30:00+06:30"])
Out[4]: DatetimeIndex(['2015-11-18 10:00:00', '2015-11-18 10:00:00'], dtype='datetime64[ns]', freq=None)
新的行为:
In [57]: pd.to_datetime("2015-11-18 15:30:00+05:30")
Out[57]: Timestamp('2015-11-18 15:30:00+0530', tz='UTC+05:30')
In [58]: pd.Timestamp("2015-11-18 15:30:00+05:30")
Out[58]: Timestamp('2015-11-18 15:30:00+0530', tz='UTC+05:30')
解析具有相同 UTC 偏移的日期时间字符串将保留tz
中的 UTC 偏移
In [59]: pd.to_datetime(["2015-11-18 15:30:00+05:30"] * 2)
Out[59]: DatetimeIndex(['2015-11-18 15:30:00+05:30', '2015-11-18 15:30:00+05:30'], dtype='datetime64[ns, UTC+05:30]', freq=None)
解析具有不同 UTC 偏移的日期时间字符串现在将创建具有不同 UTC 偏移的datetime.datetime
对象的索引
In [59]: idx = pd.to_datetime(["2015-11-18 15:30:00+05:30",
"2015-11-18 16:30:00+06:30"])
In[60]: idx
Out[60]: Index([2015-11-18 15:30:00+05:30, 2015-11-18 16:30:00+06:30], dtype='object')
In[61]: idx[0]
Out[61]: Timestamp('2015-11-18 15:30:00+0530', tz='UTC+05:30')
In[62]: idx[1]
Out[62]: Timestamp('2015-11-18 16:30:00+0630', tz='UTC+06:30')
传递utc=True
将模仿以前的行为,但将正确指示日期已转换为 UTC
In [60]: pd.to_datetime(["2015-11-18 15:30:00+05:30",
....: "2015-11-18 16:30:00+06:30"], utc=True)
....:
Out[60]: DatetimeIndex(['2015-11-18 10:00:00+00:00', '2015-11-18 10:00:00+00:00'], dtype='datetime64[ns, UTC]', freq=None)
``` ### 使用`read_csv()`解析混合时区
`read_csv()`不再将混合时区列悄悄转换为 UTC ([GH 24987](https://github.com/pandas-dev/pandas/issues/24987)).
*之前的行为*
```py
>>> import io
>>> content = """\
... a
... 2000-01-01T00:00:00+05:00
... 2000-01-01T00:00:00+06:00"""
>>> df = pd.read_csv(io.StringIO(content), parse_dates=['a'])
>>> df.a
0 1999-12-31 19:00:00
1 1999-12-31 18:00:00
Name: a, dtype: datetime64[ns]
新的行为
In[64]: import io
In[65]: content = """\
...: a
...: 2000-01-01T00:00:00+05:00
...: 2000-01-01T00:00:00+06:00"""
In[66]: df = pd.read_csv(io.StringIO(content), parse_dates=['a'])
In[67]: df.a
Out[67]:
0 2000-01-01 00:00:00+05:00
1 2000-01-01 00:00:00+06:00
Name: a, Length: 2, dtype: object
可以看到,dtype
为 object;列中的每个值都是一个字符串。要将字符串转换为日期时间数组,可以使用date_parser
参数
In [3]: df = pd.read_csv(
...: io.StringIO(content),
...: parse_dates=['a'],
...: date_parser=lambda col: pd.to_datetime(col, utc=True),
...: )
In [4]: df.a
Out[4]:
0 1999-12-31 19:00:00+00:00
1 1999-12-31 18:00:00+00:00
Name: a, dtype: datetime64[ns, UTC]
查看解析带有时区偏移的日期时间字符串获取更多信息。 ### dt.end_time
和to_timestamp(how='end')
中的时间值
当调用 Series.dt.end_time
、Period.end_time
、PeriodIndex.end_time
、Period.to_timestamp()
以 how='end'
调用时,或者使用 how='end'
调用 PeriodIndex.to_timestamp()
,Period
和 PeriodIndex
对象中的时间值现在被设置为‘23:59:59.999999999’(GH 17157)。
先前的行为:
In [2]: p = pd.Period('2017-01-01', 'D')
In [3]: pi = pd.PeriodIndex([p])
In [4]: pd.Series(pi).dt.end_time[0]
Out[4]: Timestamp(2017-01-01 00:00:00)
In [5]: p.end_time
Out[5]: Timestamp(2017-01-01 23:59:59.999999999)
新行为:
调用 Series.dt.end_time
现在会导致时间为‘23:59:59.999999999’,与 Period.end_time
相同,例如
In [61]: p = pd.Period('2017-01-01', 'D')
In [62]: pi = pd.PeriodIndex([p])
In [63]: pd.Series(pi).dt.end_time[0]
Out[63]: Timestamp('2017-01-01 23:59:59.999999999')
In [64]: p.end_time
Out[64]: Timestamp('2017-01-01 23:59:59.999999999')
``` ### 时区感知数据的 Series.unique
对于带有时区值的日期时间,`Series.unique()` 的返回类型已从 [`numpy.ndarray`](https://numpy.org/doc/stable/reference/generated/numpy.ndarray.html#numpy.ndarray "(在 NumPy v1.26 中)") 的 `Timestamp` 对象更改为 `arrays.DatetimeArray`([GH 24024](https://github.com/pandas-dev/pandas/issues/24024))。
```py
In [65]: ser = pd.Series([pd.Timestamp('2000', tz='UTC'),
....: pd.Timestamp('2000', tz='UTC')])
....:
先前的行为:
In [3]: ser.unique()
Out[3]: array([Timestamp('2000-01-01 00:00:00+0000', tz='UTC')], dtype=object)
新行为:
In [66]: ser.unique()
Out[66]:
<DatetimeArray>
['2000-01-01 00:00:00+00:00']
Length: 1, dtype: datetime64[ns, UTC]
``` ### 稀疏数据结构重构
`SparseArray`,支持 `SparseSeries` 和 `SparseDataFrame` 中列的数组,现在是扩展数组([GH 21978](https://github.com/pandas-dev/pandas/issues/21978),[GH 19056](https://github.com/pandas-dev/pandas/issues/19056),[GH 22835](https://github.com/pandas-dev/pandas/issues/22835))。为了符合此接口并与 pandas 的其他部分保持一致,进行了一些破坏 API 的更改:
+ `SparseArray` 不再是 [`numpy.ndarray`](https://numpy.org/doc/stable/reference/generated/numpy.ndarray.html#numpy.ndarray "(在 NumPy v1.26 中)") 的子类。要将 `SparseArray` 转换为 NumPy 数组,请使用 [`numpy.asarray()`](https://numpy.org/doc/stable/reference/generated/numpy.asarray.html#numpy.asarray "(在 NumPy v1.26 中)")。
+ `SparseArray.dtype` 和 `SparseSeries.dtype` 现在是 `SparseDtype` 的实例,而不是 `np.dtype`。使用 `SparseDtype.subtype` 访问底层 dtype。
+ `numpy.asarray(sparse_array)` 现在返回一个包含所有值的密集数组,而不仅仅是非填充值的值([GH 14167](https://github.com/pandas-dev/pandas/issues/14167))。
+ `SparseArray.take` 现在匹配 `pandas.api.extensions.ExtensionArray.take()` 的 API([GH 19506](https://github.com/pandas-dev/pandas/issues/19506)):
+ `allow_fill` 的默认值已从 `False` 更改为 `True`。
+ 不再接受 `out` 和 `mode` 参数(以前,如果指定了这些参数,会引发错误)。
+ 不再允许将标量用于 `indices`。
+ 使用混合稀疏和密集 Series 进行 `concat()` 的结果是一个具有稀疏值的 Series,而不是 `SparseSeries`。
+ `SparseDataFrame.combine` 和 `DataFrame.combine_first` 不再支持将稀疏列与密集列进行合并,并保留稀疏子类型。结果将是一个对象类型的 SparseArray。
+ 现在允许将 `SparseArray.fill_value` 设置为具有不同 dtype 的填充值。
+ 当对具有稀疏值的单个列进行切片时,`DataFrame[column]` 现在是一个具有稀疏值的 `Series`,而不是 `SparseSeries`([GH 23559](https://github.com/pandas-dev/pandas/issues/23559))。
+ `Series.where()` 的结果现在是一个具有稀疏值的 `Series`,与其他扩展数组一样([GH 24077](https://github.com/pandas-dev/pandas/issues/24077))。
对于需要或可能会生成大型密集数组的操作,会发出一些新的警告:
+ 当使用 `method` 进行 fillna 时,将发出 `errors.PerformanceWarning`,因为会构建一个密集数组来创建填充数组。使用 `value` 进行填充是填充稀疏数组的高效方式。
+ 当连接具有不同填充值的稀疏 Series 时,将发出 `errors.PerformanceWarning`。继续使用第一个稀疏数组的填充值。
除了这些 API 破坏性变化外,还进行了许多性能改进和错误修复。
最后,添加了 `Series.sparse` 访问器,以提供稀疏特定方法,如`Series.sparse.from_coo()`。
```py
In [67]: s = pd.Series([0, 0, 1, 1, 1], dtype='Sparse[int]')
In [68]: s.sparse.density
Out[68]: 0.6
``` ### `get_dummies()` 总是返回一个 DataFrame
以前,当 `sparse=True` 传递给`get_dummies()`时,返回值可以是`DataFrame`或`SparseDataFrame`,具体取决于是否对所有列或仅对一部分列进行了虚拟编码。 现在,始终返回`DataFrame` ([GH 24284](https://github.com/pandas-dev/pandas/issues/24284)).
*先前行为*
第一个`get_dummies()`返回一个`DataFrame`,因为列`A`没有进行虚拟编码。 当只传递`["B", "C"]`时,所有列都进行了虚拟编码,并返回了一个`SparseDataFrame`。
```py
In [2]: df = pd.DataFrame({"A": [1, 2], "B": ['a', 'b'], "C": ['a', 'a']})
In [3]: type(pd.get_dummies(df, sparse=True))
Out[3]: pandas.core.frame.DataFrame
In [4]: type(pd.get_dummies(df[['B', 'C']], sparse=True))
Out[4]: pandas.core.sparse.frame.SparseDataFrame
新行为
现在,返回类型始终为DataFrame
。
In [69]: type(pd.get_dummies(df, sparse=True))
Out[69]: pandas.core.frame.DataFrame
In [70]: type(pd.get_dummies(df[['B', 'C']], sparse=True))
Out[70]: pandas.core.frame.DataFrame
注意
在稀疏值的SparseDataFrame
和DataFrame
之间的内存使用没有区别。 内存使用量与 pandas 的先前版本相同。### 在DataFrame.to_dict(orient='index')
中引发 ValueError
当使用 orient='index'
和非唯一索引时,DataFrame.to_dict()
中的 Bug 引发 ValueError
,而不是丢失数据 (GH 22801)
In [71]: df = pd.DataFrame({'a': [1, 2], 'b': [0.5, 0.75]}, index=['A', 'A'])
In [72]: df
Out[72]:
a b
A 1 0.50
A 2 0.75
[2 rows x 2 columns]
In [73]: df.to_dict(orient='index')
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
Cell In[73], line 1
----> 1 df.to_dict(orient='index')
File ~/work/pandas/pandas/pandas/util/_decorators.py:333, in deprecate_nonkeyword_arguments.<locals>.decorate.<locals>.wrapper(*args, **kwargs)
327 if len(args) > num_allow_args:
328 warnings.warn(
329 msg.format(arguments=_format_argument_list(allow_args)),
330 FutureWarning,
331 stacklevel=find_stack_level(),
332 )
--> 333 return func(*args, **kwargs)
File ~/work/pandas/pandas/pandas/core/frame.py:2178, in DataFrame.to_dict(self, orient, into, index)
2075 """
2076 Convert the DataFrame to a dictionary.
2077
(...)
2174 defaultdict(<class 'list'>, {'col1': 2, 'col2': 0.75})]
2175 """
2176 from pandas.core.methods.to_dict import to_dict
-> 2178 return to_dict(self, orient, into=into, index=index)
File ~/work/pandas/pandas/pandas/core/methods/to_dict.py:242, in to_dict(df, orient, into, index)
240 elif orient == "index":
241 if not df.index.is_unique:
--> 242 raise ValueError("DataFrame index must be unique for orient='index'.")
243 columns = df.columns.tolist()
244 if are_all_object_dtype_cols:
ValueError: DataFrame index must be unique for orient='index'.
``` ### Tick DateOffset 规范化限制
使用 `normalize=True` 创建 `Tick` 对象 (`Day`, `Hour`, `Minute`, `Second`, `Milli`, `Micro`, `Nano`) 不再支持。 这样可以防止出现无法预料的行为,其中加法可能无法保持单调性或结合性。 ([GH 21427](https://github.com/pandas-dev/pandas/issues/21427))
*先前行为*:
```py
In [2]: ts = pd.Timestamp('2018-06-11 18:01:14')
In [3]: ts
Out[3]: Timestamp('2018-06-11 18:01:14')
In [4]: tic = pd.offsets.Hour(n=2, normalize=True)
...:
In [5]: tic
Out[5]: <2 * Hours>
In [6]: ts + tic
Out[6]: Timestamp('2018-06-11 00:00:00')
In [7]: ts + tic + tic + tic == ts + (tic + tic + tic)
Out[7]: False
新行为:
In [74]: ts = pd.Timestamp('2018-06-11 18:01:14')
In [75]: tic = pd.offsets.Hour(n=2)
In [76]: ts + tic + tic + tic == ts + (tic + tic + tic)
Out[76]: True
``` ### 期间减法
从一个 `Period` 减去另一个 `Period` 将给出一个 `DateOffset`,而不是一个整数 ([GH 21314](https://github.com/pandas-dev/pandas/issues/21314))
*先前行为*:
```py
In [2]: june = pd.Period('June 2018')
In [3]: april = pd.Period('April 2018')
In [4]: june - april
Out [4]: 2
新行为:
In [77]: june = pd.Period('June 2018')
In [78]: april = pd.Period('April 2018')
In [79]: june - april
Out[79]: <2 * MonthEnds>
类似地,从 PeriodIndex
减去一个 Period
现在将返回一个 DateOffset
对象的 Index
,而不是一个 Int64Index
先前行为:
In [2]: pi = pd.period_range('June 2018', freq='M', periods=3)
In [3]: pi - pi[0]
Out[3]: Int64Index([0, 1, 2], dtype='int64')
新行为:
In [80]: pi = pd.period_range('June 2018', freq='M', periods=3)
In [81]: pi - pi[0]
Out[81]: Index([<0 * MonthEnds>, <MonthEnd>, <2 * MonthEnds>], dtype='object')
``` ### 从 `DataFrame` 中添加/减去 `NaN`
对于具有 `timedelta64[ns]` dtype 的 `DataFrame` 列进行 `NaN` 的添加或减法现在会引发 `TypeError`,而不是返回全为 `NaT`。这是为了与 `TimedeltaIndex` 和 `Series` 的行为兼容。([GH 22163](https://github.com/pandas-dev/pandas/issues/22163))
```py
In [82]: df = pd.DataFrame([pd.Timedelta(days=1)])
In [83]: df
Out[83]:
0
0 1 days
[1 rows x 1 columns]
先前的行为:
In [4]: df = pd.DataFrame([pd.Timedelta(days=1)])
In [5]: df - np.nan
Out[5]:
0
0 NaT
新行为:
In [2]: df - np.nan
...
TypeError: unsupported operand type(s) for -: 'TimedeltaIndex' and 'float'
``` ### DataFrame 比较操作广播更改
以前,`DataFrame` 比较操作(`==`, `!=`, …)的广播行为与算术操作(`+`, `-`, …)的行为不一致。在这些情况下,比较操作的行为已更改为与算术操作匹配。([GH 22880](https://github.com/pandas-dev/pandas/issues/22880))
受影响的情况是:
+ 与具有 1 行或 1 列的二维 `np.ndarray` 进行操作现在会以与 `np.ndarray` 相同的方式广播。([GH 23000](https://github.com/pandas-dev/pandas/issues/23000)).
+ 与行数匹配长度的列表或元组现在将引发 `ValueError`,而不是逐列操作。([GH 22880](https://github.com/pandas-dev/pandas/issues/22880))
+ 与 `DataFrame` 中列数匹配长度的列表或元组现在将逐行操作,而不是引发 `ValueError`。([GH 22880](https://github.com/pandas-dev/pandas/issues/22880))
```py
In [84]: arr = np.arange(6).reshape(3, 2)
In [85]: df = pd.DataFrame(arr)
In [86]: df
Out[86]:
0 1
0 0 1
1 2 3
2 4 5
[3 rows x 2 columns]
先前的行为:
In [5]: df == arr[[0], :]
...: # comparison previously broadcast where arithmetic would raise
Out[5]:
0 1
0 True True
1 False False
2 False False
In [6]: df + arr[[0], :]
...
ValueError: Unable to coerce to DataFrame, shape must be (3, 2): given (1, 2)
In [7]: df == (1, 2)
...: # length matches number of columns;
...: # comparison previously raised where arithmetic would broadcast
...
ValueError: Invalid broadcasting comparison [(1, 2)] with block values
In [8]: df + (1, 2)
Out[8]:
0 1
0 1 3
1 3 5
2 5 7
In [9]: df == (1, 2, 3)
...: # length matches number of rows
...: # comparison previously broadcast where arithmetic would raise
Out[9]:
0 1
0 False True
1 True False
2 False False
In [10]: df + (1, 2, 3)
...
ValueError: Unable to coerce to Series, length must be 2: given 3
新行为:
# Comparison operations and arithmetic operations both broadcast.
In [87]: df == arr[[0], :]
Out[87]:
0 1
0 True True
1 False False
2 False False
[3 rows x 2 columns]
In [88]: df + arr[[0], :]
Out[88]:
0 1
0 0 2
1 2 4
2 4 6
[3 rows x 2 columns]
# Comparison operations and arithmetic operations both broadcast.
In [89]: df == (1, 2)
Out[89]:
0 1
0 False False
1 False False
2 False False
[3 rows x 2 columns]
In [90]: df + (1, 2)
Out[90]:
0 1
0 1 3
1 3 5
2 5 7
[3 rows x 2 columns]
# Comparison operations and arithmetic operations both raise ValueError.
In [6]: df == (1, 2, 3)
...
ValueError: Unable to coerce to Series, length must be 2: given 3
In [7]: df + (1, 2, 3)
...
ValueError: Unable to coerce to Series, length must be 2: given 3
``` ### DataFrame 算术运算广播更改
当与二维 `np.ndarray` 对象一起进行操作时,`DataFrame` 算术运算现在以与 `np.ndarray` 广播相同的方式进行。([GH 23000](https://github.com/pandas-dev/pandas/issues/23000))
```py
In [91]: arr = np.arange(6).reshape(3, 2)
In [92]: df = pd.DataFrame(arr)
In [93]: df
Out[93]:
0 1
0 0 1
1 2 3
2 4 5
[3 rows x 2 columns]
先前的行为:
In [5]: df + arr[[0], :] # 1 row, 2 columns
...
ValueError: Unable to coerce to DataFrame, shape must be (3, 2): given (1, 2)
In [6]: df + arr[:, [1]] # 1 column, 3 rows
...
ValueError: Unable to coerce to DataFrame, shape must be (3, 2): given (3, 1)
新行为:
In [94]: df + arr[[0], :] # 1 row, 2 columns
Out[94]:
0 1
0 0 2
1 2 4
2 4 6
[3 rows x 2 columns]
In [95]: df + arr[:, [1]] # 1 column, 3 rows
Out[95]:
0 1
0 1 2
1 5 6
2 9 10
[3 rows x 2 columns]
``` ### Series 和 Index 数据类型不兼容
当数据与传递的 `dtype=` 不兼容时,`Series` 和 `Index` 构造函数现在会引发异常。([GH 15832](https://github.com/pandas-dev/pandas/issues/15832))
*先前的行为*:
```py
In [4]: pd.Series([-1], dtype="uint64")
Out [4]:
0 18446744073709551615
dtype: uint64
新行为:
In [4]: pd.Series([-1], dtype="uint64")
Out [4]:
...
OverflowError: Trying to coerce negative values to unsigned integers
``` ### 连接更改
当对具有 NA 值的整数 `Categorical` 进行 `pandas.concat()` 调用时,现在除了与另一个整数 `Categorical` 连接时,将它们视为对象进行处理。([GH 19214](https://github.com/pandas-dev/pandas/issues/19214))
```py
In [96]: s = pd.Series([0, 1, np.nan])
In [97]: c = pd.Series([0, 1, np.nan], dtype="category")
先前的行为
In [3]: pd.concat([s, c])
Out[3]:
0 0.0
1 1.0
2 NaN
0 0.0
1 1.0
2 NaN
dtype: float64
新行为
In [98]: pd.concat([s, c])
Out[98]:
0 0.0
1 1.0
2 NaN
0 0.0
1 1.0
2 NaN
Length: 6, dtype: float64
Datetimelike API 更改
-
对于具有非
None
freq
属性的DatetimeIndex
和TimedeltaIndex
,对整数类型数组或Index
进行加减运算将返回相同类别的对象(GH 19959) -
DateOffset
对象现在是不可变的。尝试修改其中一个将引发AttributeError
(GH 21341) -
PeriodIndex
减去另一个PeriodIndex
现在将返回一个DateOffset
对象的对象类型Index
,而不是引发TypeError
(GH 20049) -
cut()
和qcut()
现在在输入为日期时间或时间间隔数据类型且retbins=True
时,返回一个DatetimeIndex
或TimedeltaIndex
的分箱(GH 19891) -
DatetimeIndex.to_period()
和Timestamp.to_period()
在时区信息将丢失时会发出警告(GH 21333) -
PeriodIndex.tz_convert()
和PeriodIndex.tz_localize()
已被移除(GH 21781)
其他 API 更改
-
以整数为
dtype
��构建的空DataFrame
现在只有在指定index
时才会转换为float64
(GH 22858) -
Series.str.cat()
现在会在others
是set
时引发异常(GH 23009) -
将标量值传递给
DatetimeIndex
或TimedeltaIndex
现在会引发TypeError
而不是ValueError
(GH 23539) -
HTMLFormatter
中移除了max_rows
和max_cols
参数,因为截断由DataFrameFormatter
处理 (GH 23818) -
read_csv()
现在会在声明具有缺失值的列的 dtype 为bool
时引发ValueError
(GH 20591) -
DataFrame
的列顺序现在保证与MultiIndex.to_frame()
的MultiIndex.names
顺序相匹配。(GH 22420) -
错误地将
DatetimeIndex
传递给MultiIndex.from_tuples()
,而不是元组序列,现在会引发TypeError
而不是ValueError
(GH 24024) -
pd.offsets.generate_range()
的参数time_rule
已被移除;请改用offset
(GH 24157) -
在 0.23.x 版本中,pandas 在合并数字列(例如
int
类型的列)和object
类型的列时会引发ValueError
(GH 9780)。我们已重新启用了合并object
和其他类型的能力;pandas 仍然会在数字和仅包含字符串的object
类型的列之间的合并时引发异常 (GH 21681) -
使用重复名称的
MultiIndex
的级别访问(例如在get_level_values()
中)现在会引发ValueError
而不是KeyError
(GH 21678). -
如果子类型无效,
IntervalDtype
的错误构造现在始终会引发TypeError
而不是ValueError
(GH 21185) -
尝试使用非唯一的
MultiIndex
对DataFrame
进行重新索引现在会引发ValueError
而不是异常 (GH 21770) -
Index
的减法现在尝试进行逐元素操作,而不是引发TypeError
(GH 19369) -
在使用
to_excel()
时,pandas.io.formats.style.Styler
支持number-format
属性(GH 22015)。 -
当提供无效方法时,
DataFrame.corr()
和Series.corr()
现在会引发ValueError
并提供有用的错误信息,而不是KeyError
(GH 22298)。 -
shift()
现在总是返回一个副本,而不是以前的在移动 0 时返回 self 的行为(GH 22397)。 -
DataFrame.set_index()
现在提供了更好(且更少出现)的 KeyError,对于不正确的类型会引发ValueError
,并且在drop=True
时不会因为重复的列名而失败(GH 22484)。 -
对一个 DataFrame 的多个相同类型的 ExtensionArrays 进行单行切片现在会保留 dtype,而不是强制转换为对象(GH 22784)。
-
DateOffset
属性_cacheable
和方法_should_cache
已被移除(GH 23118)。 -
当
Series.searchsorted()
提供一个标量值进行搜索时,现在返回一个标量而不是一个数组(GH 23801)。 -
当
Categorical.searchsorted()
提供一个标量值进行搜索时,现在返回一个标量而不是一个数组(GH 23466)。 -
Categorical.searchsorted()
现在在其类别中找不到搜索的键时会引发KeyError
而不是ValueError
(GH 23466)。 -
Index.hasnans()
和Series.hasnans()
现在总是返回一个 Python 布尔值。以前,根据情况可能返回 Python 或 numpy 布尔值(GH 23294)。 -
DataFrame.to_html()
和DataFrame.to_string()
的参数顺序已重新排列,以保持彼此一致。 (GH 23614)。 -
如果目标索引是非唯一的且不等于当前索引,则
CategoricalIndex.reindex()
现在会引发ValueError
。 它以前只在目标索引不是分类 dtype 时引发(GH 23963)。 -
Series.to_list()
和Index.to_list()
现在分别是Series.tolist
和Index.tolist
的别名(GH 8826)。 -
SparseSeries.unstack
的结果现在是具有稀疏值的DataFrame
,而不是SparseDataFrame
(GH 24372)。 -
DatetimeIndex
和TimedeltaIndex
不再忽略 dtype 的精度。 传递非纳秒分辨率 dtype 将引发ValueError
(GH 24753) ## 扩展类型更改
相等性和哈希性
现在,pandas 要求扩展类型是可哈希的(即对应的 ExtensionDtype
对象;哈希性不是相应的 ExtensionArray
的值的要求)。基类实现了默认的 __eq__
和 __hash__
。如果您有一个带参数的 dtype,则应更新 ExtensionDtype._metadata
元组以匹配您的 __init__
方法的签名。有关更多信息,请参见pandas.api.extensions.ExtensionDtype
(GH 22476)。
新方法和更改的方法
-
已添加
dropna()
(GH 21185)。 -
已添加
repeat()
(GH 24349)。 -
ExtensionArray
构造函数_from_sequence
现在接受关键字参数copy=False
(GH 21185)。 -
pandas.api.extensions.ExtensionArray.shift()
作为基本ExtensionArray
接口的一部分添加(GH 22387) -
添加了
searchsorted()
(GH 24350) -
通过选择基类方法重写,支持
sum
、mean
等归约操作(GH 22762) -
ExtensionArray.isna()
允许返回一个ExtensionArray
(GH 22325).
Dtype 更改
-
ExtensionDtype
获得了通过字符串 dtype 实例化的能力,例如,decimal
将实例化一个已注册的DecimalDtype
;此外,ExtensionDtype
还增加了construct_array_type
方法(GH 21185) -
添加了
ExtensionDtype._is_numeric
来控制扩展 dtype 是否被视为数值型 (GH 22290) -
添加了
pandas.api.types.register_extension_dtype()
以在 pandas 中注册扩展类型 (GH 22664) -
更新了
PeriodDtype
、DatetimeTZDtype
和IntervalDtype
的.type
属性,使其成为对应的 dtype 实例(分别为Period
、Timestamp
和Interval
)(GH 22938)
操作符支持
基于ExtensionArray
的Series
现在支持算术和比较操作符 (GH 19577). 为ExtensionArray
提供操作符支持有两种方法:
-
在你的
ExtensionArray
子类上定义每个操作符。 -
使用来自 pandas 的操作符实现,这些操作符依赖于
ExtensionArray
底层元素(标量)上已定义的操作符。
有关两种添加操作符支持方式的详细信息,请参阅 ExtensionArray Operator Support 文档部分。
其他更改
-
现在提供了
pandas.api.extensions.ExtensionArray
的默认 repr (GH 23601). -
ExtensionArray._formatting_values()
已弃用。请改用ExtensionArray._formatter
。 (GH 23601) -
具有布尔 dtype 的
ExtensionArray
现在作为布尔索引器正常工作。pandas.api.types.is_bool_dtype()
现在正确地将它们视为布尔值(GH 22326)。
Bug 修复
-
在使用
ExtensionArray
和整数索引的Series
中,Series.get()
存在 Bug(GH 21257)。 -
shift()
现在派发到ExtensionArray.shift()
(GH 22386)。 -
Series.combine()
现在在Series
内部正确地与ExtensionArray
一起工作(GH 20825)。 -
现在,带有标量参数的
Series.combine()
可以适用于任何函数类型(GH 21248)。 -
Series.astype()
和DataFrame.astype()
现在派发到ExtensionArray.astype()
(GH 21185)。 -
使用相同类型的多个 ExtensionArrays 切片 DataFrame 的单行现在会保留 dtype,而不是强制转换为对象 dtype(GH 22784)。
-
在连接具有不同扩展 dtype 的多个
Series
时存在 Bug,不会转换为对象 dtype(GH 22994)。 -
由
ExtensionArray
支持的 Series 现在可以与util.hash_pandas_object()
一起使用(GH 23066)。 -
对于每列具有相同扩展 dtype 的 DataFrame,
DataFrame.stack()
不再转换为对象 dtype。输出 Series 的 dtype 将与列相同(GH 23077)。 -
Series.unstack()
和DataFrame.unstack()
不再将扩展数组转换为对象类型的 ndarrays。输出DataFrame
中的每列现在将具有与输入相同的 dtype (GH 23077). -
当对
Dataframe.groupby()
进行分组并在ExtensionArray
上进行聚合时存在错误,它没有返回实际的ExtensionArray
dtype (GH 23227). -
在使用基于扩展数组的列进行合并时
pandas.merge()
存在错误(GH 23020)。## 弃用 -
MultiIndex.labels
已被弃用,并被MultiIndex.codes
替代。功能不变。新名称更好地反映了这些代码的性质,并使MultiIndex
API 更类似于CategoricalIndex
的 API (GH 13443)。因此,MultiIndex
中其他使用labels
名称的用法也已被弃用,并替换为codes
:-
你应该使用名为
codes
的参数来初始化MultiIndex
实例,而不是labels
。 -
MultiIndex.set_labels
已被弃用,推荐使用MultiIndex.set_codes()
。 -
对于方法
MultiIndex.copy()
,labels
参数已被弃用,并替换为codes
参数。
-
-
DataFrame.to_stata()
,read_stata()
,StataReader
和StataWriter
已弃用encoding
参数。Stata dta 文件的编码由文件类型确定,无法更改 (GH 21244) -
MultiIndex.to_hierarchical()
已被弃用,并将在将来的版本中删除 (GH 21613) -
Series.ptp()
已被弃用。请改用numpy.ptp
(GH 21614) -
Series.compress()
已被弃用。请改用Series[condition]
(GH 18262) -
Series.to_csv()
的签名已统一为DataFrame.to_csv()
的签名:第一个参数现在是path_or_buf
,后续参数的顺序已更改,header
参数现在默认为True
。(GH 19715) -
Categorical.from_codes()
已弃用为codes
参数提供浮点值。(GH 21767) -
pandas.read_table()
已被弃用。取而代之的是,如果有必要,使用read_csv()
并传递sep='\t'
。这个弃用已经在 0.25.0 版本中移除。(GH 21948) -
Series.str.cat()
已弃用在列表内使用任意列表类对象。列表类容器仍可包含许多Series
,Index
或 1 维np.ndarray
,或者只包含标量值。(GH 21950) -
FrozenNDArray.searchsorted()
已弃用v
参数,推荐使用value
参数(GH 14645) -
DatetimeIndex.shift()
和PeriodIndex.shift()
现在接受periods
参数而不是n
,以与Index.shift()
和Series.shift()
保持一致。使用n
会产生弃用警告(GH 22458,GH 22912) -
不同索引构造函数的
fastpath
关键字已被弃用(GH 23110)。 -
Timestamp.tz_localize()
,DatetimeIndex.tz_localize()
和Series.tz_localize()
已弃用errors
参数,推荐使用nonexistent
参数(GH 8917) -
类
FrozenNDArray
已弃用。一旦此类被移除,反序列化时FrozenNDArray
将被反序列化为np.ndarray
(GH 9031) -
DataFrame.update()
和Panel.update()
方法已弃用raise_conflict=False|True
参数,推荐使用errors='ignore'|'raise'
(GH 23585) -
Series.str.partition()
和Series.str.rpartition()
方法已弃用pat
参数,推荐使用sep
参数 (GH 22676) -
弃用了
pandas.read_feather()
的nthreads
参数,推荐使用use_threads
来反映pyarrow>=0.11.0
的更改。 (GH 23053) -
pandas.read_excel()
已经弃用了接受整数作为usecols
的参数。请改为传入从0
到usecols
的整数列表(包括usecols
)代替 (GH 23527) -
从具有
datetime64
类型数据的数据构建TimedeltaIndex
已弃用,在将来的版本中将引发TypeError
(GH 23539) -
从具有
timedelta64
类型数据的数据构建DatetimeIndex
已弃用,在将来的版本中将引发TypeError
(GH 23675) -
keep_tz=False
选项(默认)的keep_tz
关键字已弃用,适用于DatetimeIndex.to_series()
(GH 17832). -
使用时区感知的
datetime.datetime
或Timestamp
进行时区转换,并且tz
参数现在已弃用。请改用Timestamp.tz_convert()
(GH 23579) -
pandas.api.types.is_period()
已被弃用,推荐使用pandas.api.types.is_period_dtype
(GH 23917) -
pandas.api.types.is_datetimetz()
已被弃用,推荐使用pandas.api.types.is_datetime64tz
(GH 23917) -
通过传递范围参数
start
、end
和periods
来创建TimedeltaIndex
、DatetimeIndex
或PeriodIndex
已被弃用,推荐使用timedelta_range()
、date_range()
或period_range()
(GH 23919) -
将字符串别名如
'datetime64[ns, UTC]'
作为unit
参数传递给DatetimeTZDtype
已被弃用。请改用DatetimeTZDtype.construct_from_string
(GH 23990)。 -
infer_dtype()
的skipna
参数将在 pandas 的将来版本中默认切换为True
(GH 17066, GH 24050) -
在带有分类数据的
Series.where()
中,提供一个不在分类中的other
已被弃用。请将分类转换为不同的 dtype 或首先将other
添加到分类中(GH 24077)。 -
Series.clip_lower()
,Series.clip_upper()
,DataFrame.clip_lower()
和DataFrame.clip_upper()
已被弃用,并将在将来的版本中移除。请使用Series.clip(lower=threshold)
,Series.clip(upper=threshold)
和相应的DataFrame
方法(GH 24203) -
Series.nonzero()
已被弃用,并将在将来的版本中移除(GH 18262) -
传递带有
timedelta64[ns]
类型的整数给Series.fillna()
和DataFrame.fillna()
已被弃用,将在未来版本中引发TypeError
。改用obj.fillna(pd.Timedelta(...))
代替(GH 24694) -
Series.cat.categorical
、Series.cat.name
和Series.cat.index
已被弃用。请使用Series.cat
或Series
上的属性。(GH 24751)。 -
将没有精度的 dtype(如
np.dtype('datetime64')
或timedelta64
)传递给Index
、DatetimeIndex
和TimedeltaIndex
现已被弃用。请改用纳秒精度 dtype 代替(GH 24753)。
使用日期时间和时间增减的整数已被弃用
在过去,用户可以在某些情况下从Timestamp
、DatetimeIndex
和TimedeltaIndex
中添加或减去整数或整数类型的数组。
此用法现已弃用。而是添加或减去对象的freq
属性的整数倍数(GH 21939,GH 23878)。
先前的行为:
In [5]: ts = pd.Timestamp('1994-05-06 12:15:16', freq=pd.offsets.Hour())
In [6]: ts + 2
Out[6]: Timestamp('1994-05-06 14:15:16', freq='H')
In [7]: tdi = pd.timedelta_range('1D', periods=2)
In [8]: tdi - np.array([2, 1])
Out[8]: TimedeltaIndex(['-1 days', '1 days'], dtype='timedelta64[ns]', freq=None)
In [9]: dti = pd.date_range('2001-01-01', periods=2, freq='7D')
In [10]: dti + pd.Index([1, 2])
Out[10]: DatetimeIndex(['2001-01-08', '2001-01-22'], dtype='datetime64[ns]', freq=None)
新行为:
In [108]: ts = pd.Timestamp('1994-05-06 12:15:16', freq=pd.offsets.Hour())
In[109]: ts + 2 * ts.freq
Out[109]: Timestamp('1994-05-06 14:15:16', freq='H')
In [110]: tdi = pd.timedelta_range('1D', periods=2)
In [111]: tdi - np.array([2 * tdi.freq, 1 * tdi.freq])
Out[111]: TimedeltaIndex(['-1 days', '1 days'], dtype='timedelta64[ns]', freq=None)
In [112]: dti = pd.date_range('2001-01-01', periods=2, freq='7D')
In [113]: dti + pd.Index([1 * dti.freq, 2 * dti.freq])
Out[113]: DatetimeIndex(['2001-01-08', '2001-01-22'], dtype='datetime64[ns]', freq=None)
``` ### 将整数数据和时区传递给 DatetimeIndex
当传递整数数据和时区给`DatetimeIndex`时,pandas 未来版本中的行为将发生变化。以前,这些被解释为所需时区的墙上时间。将来,这些将被解释为 UTC 中的墙上时间,然后转换为所需时区([GH 24559](https://github.com/pandas-dev/pandas/issues/24559))。
默认行为保持不变,但会发出警告:
```py
In [3]: pd.DatetimeIndex([946684800000000000], tz="US/Central")
/bin/ipython:1: FutureWarning:
Passing integer-dtype data and a timezone to DatetimeIndex. Integer values
will be interpreted differently in a future version of pandas. Previously,
these were viewed as datetime64[ns] values representing the wall time
*in the specified timezone*. In the future, these will be viewed as
datetime64[ns] values representing the wall time *in UTC*. This is similar
to a nanosecond-precision UNIX epoch. To accept the future behavior, use
pd.to_datetime(integer_data, utc=True).tz_convert(tz)
To keep the previous behavior, use
pd.to_datetime(integer_data).tz_localize(tz)
#!/bin/python3
Out[3]: DatetimeIndex(['2000-01-01 00:00:00-06:00'], dtype='datetime64[ns, US/Central]', freq=None)
如警告消息所述,通过指定整数值为 UTC 并转换为最终时区来选择未来行为:
In [99]: pd.to_datetime([946684800000000000], utc=True).tz_convert('US/Central')
Out[99]: DatetimeIndex(['1999-12-31 18:00:00-06:00'], dtype='datetime64[ns, US/Central]', freq=None)
可以通过直接定位到最终时区来保留旧行为:
In [100]: pd.to_datetime([946684800000000000]).tz_localize('US/Central')
Out[100]: DatetimeIndex(['2000-01-01 00:00:00-06:00'], dtype='datetime64[ns, US/Central]', freq=None)
``` ### 将时区感知的 Series 和 Index 转换为 NumPy 数组
从具有时区感知日期时间数据的 `Series` 或 `Index` 转换将更改为默认保留时区([GH 23569](https://github.com/pandas-dev/pandas/issues/23569))
NumPy 没有专门的 dtype 用于时区感知日期时间。过去,将具有时区感知日期时间的 `Series` 或 `DatetimeIndex` 转换为 NumPy 数组时
1. 将 tz-aware 数据转换为 UTC
1. 删除时区信息
1. 返回一个带有 `datetime64[ns]` dtype 的 [`numpy.ndarray`](https://numpy.org/doc/stable/reference/generated/numpy.ndarray.html#numpy.ndarray "(在 NumPy v1.26)")
pandas 的未来版本将通过返回一个对象 dtype 的 NumPy 数组来保留时区信息,其中每个值都是带有正确时区的 `Timestamp`
```py
In [101]: ser = pd.Series(pd.date_range('2000', periods=2, tz="CET"))
In [102]: ser
Out[102]:
0 2000-01-01 00:00:00+01:00
1 2000-01-02 00:00:00+01:00
Length: 2, dtype: datetime64[ns, CET]
默认行为保持不变,但会发出警告
In [8]: np.asarray(ser)
/bin/ipython:1: FutureWarning: Converting timezone-aware DatetimeArray to timezone-naive
ndarray with 'datetime64[ns]' dtype. In the future, this will return an ndarray
with 'object' dtype where each element is a 'pandas.Timestamp' with the correct 'tz'.
To accept the future behavior, pass 'dtype=object'.
To keep the old behavior, pass 'dtype="datetime64[ns]"'.
#!/bin/python3
Out[8]:
array(['1999-12-31T23:00:00.000000000', '2000-01-01T23:00:00.000000000'],
dtype='datetime64[ns]')
以前或未来的行为可以通过指定 dtype
来获得,而不会收到任何警告
以前的行为
In [103]: np.asarray(ser, dtype='datetime64[ns]')
Out[103]:
array(['1999-12-31T23:00:00.000000000', '2000-01-01T23:00:00.000000000'],
dtype='datetime64[ns]')
未来行为
# New behavior
In [104]: np.asarray(ser, dtype=object)
Out[104]:
array([Timestamp('2000-01-01 00:00:00+0100', tz='CET'),
Timestamp('2000-01-02 00:00:00+0100', tz='CET')], dtype=object)
或者通过使用 Series.to_numpy()
In [105]: ser.to_numpy()
Out[105]:
array([Timestamp('2000-01-01 00:00:00+0100', tz='CET'),
Timestamp('2000-01-02 00:00:00+0100', tz='CET')], dtype=object)
In [106]: ser.to_numpy(dtype="datetime64[ns]")
Out[106]:
array(['1999-12-31T23:00:00.000000000', '2000-01-01T23:00:00.000000000'],
dtype='datetime64[ns]')
所有上述内容也适用于具有时区感知值的 DatetimeIndex
。## 删除之前版本的弃用/更改
-
LongPanel
和WidePanel
类已删除(GH 10892) -
Series.repeat()
将reps
参数重命名为repeats
(GH 14645) -
几个私有函数已从(非公开)模块
pandas.core.common
中删除(GH 22001) -
传递给
DataFrame.groupby()
的字符串既引用列级别又引用索引级别会引发ValueError
(GH 14432) -
Index.repeat()
和MultiIndex.repeat()
将n
参数重命名为repeats
(GH 14645) -
如果在
dtype
参数中传递了时间戳 dtype 而没有单位(例如np.datetime64
),则Series
构造函数和.astype
方法现在会引发ValueError
(GH 15987) -
模块
pandas.types
、pandas.computation
和pandas.util.decorators
已被移除(GH 16157, GH 16250) -
移除了
pandas.io.formats.style.Styler
的pandas.formats.style
代理层(GH 16059) -
pandas.pnow
、pandas.match
、pandas.groupby
、pd.get_store
、pd.Expr
和pd.Term
已被移除(GH 15538, GH 15940) -
Categorical.searchsorted()
和Series.searchsorted()
已将v
参数改名为value
(GH 14645) -
移除了
pandas.parser
、pandas.lib
和pandas.tslib
(GH 15537) -
Index.searchsorted()
已将key
参数改名为value
(GH 14645) -
DataFrame.consolidate
和Series.consolidate
已被移除(GH 15501) -
移除了先前弃用的模块
pandas.json
(GH 19944) -
SparseArray.get_values()
和SparseArray.to_dense()
已移除了fill
参数(GH 14686) -
DataFrame.sortlevel
和Series.sortlevel
已被移除(GH 15099) -
SparseSeries.to_dense()
已移除了sparse_only
参数(GH 14686) -
DataFrame.astype()
和Series.astype()
已将raise_on_error
参数改名为errors
(GH 14967) -
pandas.api.types
中的is_sequence
、is_any_int_dtype
和is_floating_dtype
已被移除(GH 16163, GH 16189)。 ## 性能改进 -
使用单调递增的
CategoricalIndex
对 Series 和 DataFrame 进行切片现在非常快,并且速度与使用Int64Index
进行切片相当。 在按标签索引(使用.loc)和位置索引(.iloc)时,速度增加(GH 20395)。 对单调递增的CategoricalIndex
本身进行切片(即ci[1000:2000]
)显示出与上述类似的速度改进(GH 21659)。 -
当与另一个
CategoricalIndex
进行比较时,改进了CategoricalIndex.equals()
的性能(GH 24023)。 -
在数值类型的情况下,改进了
Series.describe()
的性能(GH 21274)。 -
当处理并列排名时,改进了
GroupBy.rank()
的性能(GH 21237)。 -
当列由
Period
对象组成时,改进了DataFrame.set_index()
的性能(GH 21582, GH 21606)。 -
对于扩展数组值(例如
Categorical``](../reference/api/pandas.Series.at.html#pandas.Series.at "pandas.Series.at")和
Index.get_value()`的性能(GH 24204)。 -
在
Categorical
和CategoricalIndex
中的成员检查性能得到改进(即x in cat
-style 检查更快)。CategoricalIndex.contains()
同样更快(GH 21369, GH 21508)。 -
改进了
HDFStore.groups()
的性能(以及依赖函数如HDFStore.keys()
。即x in store
检查速度更快)(GH 21372) -
改进了带有
sparse=True
的pandas.get_dummies()
的性能(GH 21997) -
改进了对排序的非唯一索引使用
IndexEngine.get_indexer_non_unique()
的性能(GH 9466) -
改进了
PeriodIndex.unique()
的性能(GH 23083) -
改进了
concat()
在Series
对象上的性能(GH 23404) -
改进了时区无关或 UTC 日期时间的
DatetimeIndex.normalize()
和Timestamp.normalize()
的性能(GH 23634) -
改进了
DatetimeIndex.tz_localize()
和各种带有 dateutil UTC 时区的DatetimeIndex
属性的性能(GH 23772) -
修复了在 Windows 上使用 Python 3.7 时
read_csv()
的性能退化(GH 23516) -
改进了
Series
对象的Categorical
构造函数的性能(GH 23814) -
改进了用于分类数据的
where()
的性能(GH 24077) -
改进了遍历
Series
的性能。现在使用DataFrame.itertuples()
创建的迭代器不再在内部分配所有元素的列表(GH 20783) -
改进了
Period
构造函数的性能,同时也有利于PeriodArray
和PeriodIndex
的创建(GH 24084,GH 24118) -
改进了带有时区感知的
DatetimeArray
二进制操作的性能(GH 24491)## Bug 修复
分类
-
Categorical.from_codes()
中的错误,codes
中的NaN
值被悄悄地转换为0
(GH 21767)。将来这将引发ValueError
。还更改了.from_codes([1.1, 2.0])
的行为。 -
Categorical.sort_values()
中的错误,NaN
值始终位于前面,而不考虑na_position
值。(GH 22556) -
使用布尔值
Categorical
进行索引时的错误。现在布尔值Categorical
被视为布尔掩码(GH 22665) -
使用空值和布尔类别构造
CategoricalIndex
在 dtype 强制转换后引发ValueError
(GH 22702) -
Categorical.take()
中的错误,当用户提供fill_value
时未对fill_value
进行编码,可能导致ValueError
、不正确的结果或分段错误(GH 23296) -
在
Series.unstack()
中,指定一个在类别中不存在的fill_value
现在会引发TypeError
,而不是忽略fill_value
(GH 23284) -
当在分类数据上重新采样
DataFrame.resample()
并对其进行聚合时,分类 dtype 会丢失。(GH 23227) -
多个
.str
访问器方法中存在的错误,在调用CategoricalIndex.str
构造函数时总是失败(GH 23555,GH 23556) -
Series.where()
中的错误,对于分类数据丢失了分类 dtype(GH 24077) -
Categorical.apply()
中的错误,NaN
值可能会被不可预测地处理。现在它们保持不变(GH 24241) -
Categorical
比较方法中的错误导致在与DataFrame
进行操作时错误地引发ValueError
(GH 24630) -
在
Categorical.set_categories()
中存在错误���使用rename=True
设置较少的新类别导致分段错误(GH 24675)
日期时间类
-
修复了两个具有不同
normalize
属性的DateOffset
对象可能被评估为相等的错误(GH 21404) -
修复了
Timestamp.resolution()
错误地返回 1 微秒timedelta
而不是 1 纳秒Timedelta
的错误(GH 21336,GH 21365) -
在
to_datetime()
中存在错误,当指定box=True
时未始终返回Index
(GH 21864) -
在
DatetimeIndex
比较中,字符串比较错误地引发TypeError
(GH 22074) -
在与
timedelta64[ns]
数据类型数组进行比较时,DatetimeIndex
比较存在错误;在某些情况下错误地引发TypeError
,在其他情况下错误地未引发异常(GH 22074) -
在与对象数据类型数组进行比较时,
DatetimeIndex
比较存在错误(GH 22074) -
在具有
datetime64[ns]
数据类型的DataFrame
中,使用Timedelta
类似对象进行加减运算时存在错误(GH 22005,GH 22163) -
在具有
datetime64[ns]
数据类型的DataFrame
中,使用DateOffset
对象进行加减运算时返回object
数据类型而不是datetime64[ns]
数据类型的错误(GH 21610,GH 22163) -
具有
datetime64[ns]
dtype 的DataFrame
与NaT
的比较存在错误 (GH 22242, GH 22163) -
具有
datetime64[ns]
dtype 的DataFrame
减去Timestamp
-like 对象时,不正确地返回datetime64[ns]
dtype 而不是timedelta64[ns]
dtype (GH 8554, GH 22163) -
具有
datetime64[ns]
dtype 的DataFrame
减去具有非纳秒单位的np.datetime64
对象时,未能将单位转换为纳秒 (GH 18874, GH 22163) -
对于混合类型的
DataFrame
与Timestamp
类似对象的比较,不等式检查中类型不匹配时未能引发TypeError
的错误 (GH 8932, GH 22163) -
具有包括
datetime64[ns]
的混合 dtypes 的DataFrame
不正确地在相等比较时引发TypeError
(GH 13128, GH 22163) -
DataFrame.values
存在一个错误,当单列DataFrame
包含带有时区信息的日期时间值时,会返回一个DatetimeIndex
。现在返回一个由Timestamp
对象组成的二维numpy.ndarray
(GH 24024) -
DataFrame.eq()
对NaT
的比较存在错误,不正确地返回True
或NaN
(GH 15697, GH 22163) -
DatetimeIndex
减法存在错误,未能正确引发OverflowError
(GH 22492, GH 22508) -
在
DatetimeIndex
中存在 Bug,错误地允许使用Timedelta
对象进行索引(GH 20464) -
在
DatetimeIndex
中存在 Bug,如果原始频率为None
,则频率会被设置(GH 22150) -
在
DatetimeIndex
的四舍五入方法中存在 Bug(round()
、ceil()
、floor()
)以及Timestamp
的四舍五入方法中存在 Bug(round()
、ceil()
、floor()
),可能会导致精度损失(GH 22591) -
在
to_datetime()
中存在 Bug,使用Index
参数时会丢弃结果中的name
(GH 21697) -
在
PeriodIndex
中存在 Bug,添加或减去timedelta
或Tick
对象会产生不正确的结果(GH 22988) -
在具有周期数据的
Series
repr 中存在 Bug,数据前缺少空格(GH 23601) -
在
date_range()
中存在 Bug,通过负频率将开始日期减到过去的结束日期时(GH 23270) -
在
Series.min()
中存在 Bug,当在NaT
的 series 上调用时会返回NaN
而不是NaT
(GH 23282) -
Bug in
Series.combine_first()
,未正确对齐分类值,导致self
中的缺失值未被other
中的有效值填充(GH 24147) -
Bug in
DataFrame.combine()
,具有 datetimelike 值时引发 TypeError 错误(GH 23079) -
Bug in
date_range()
,当频率为Day
或更高时,未来足够远的日期可能会回到过去,而不是引发OutOfBoundsDatetime
错误(GH 14187) -
Bug in
period_range()
,当提供start
和end
作为Period
对象时,忽略了频率(GH 20535) -
Bug in
PeriodIndex
,当属性freq.n
大于 1 时,添加DateOffset
对象会返回不正确的结果(GH 23215) -
Bug in
Series
,在设置 datetimelike 值时,将字符串索引解释为字符列表(GH 23451) -
Bug in
DataFrame
,当从带有时区的Timestamp
对象的 ndarray 创建新列时,会创建一个对象 dtype 列,而不是带有时区的 datetime 列(GH 23932) -
Bug in
Timestamp
构造函数,会丢弃输入Timestamp
的频率(GH 22311) -
Bug in
DatetimeIndex
,调用np.array(dtindex, dtype=object)
会错误地返回一个long
对象数组(GH 23524) -
Index
中的错误,当传递一个带有时区信息的DatetimeIndex
和dtype=object
时,会不正确地引发ValueError
(GH 23524) -
Index
中的错误,对于时区无关的DatetimeIndex
调用np.array(dtindex, dtype=object)
会返回datetime
对象的���组而不是Timestamp
对象,可能会丢失时间戳的纳秒部分(GH 23524) -
Categorical.__setitem__
中的错误,当两者都是无序的并且具有相同类别但顺序不同的Categorical
时,不允许使用另一个Categorical
进行设置(GH 24142) -
date_range()
中的错误,使用毫秒分辨率或更高分辨率的日期可能会返回不正确的值或索引中的值数量不正确(GH 24110) -
DatetimeIndex
中的错误,从Categorical
或CategoricalIndex
构造DatetimeIndex
会不正确地丢弃时区信息(GH 18664) -
DatetimeIndex
和TimedeltaIndex
中的错误,使用Ellipsis
进行索引会不正确地丢失索引的freq
属性(GH 21282) -
当向
DatetimeIndex
传递一个不正确的freq
参数,并且传递数据的第一个条目为NaT
时,澄清了产生的错误消息(GH 11587) -
to_datetime()
中的错误,当传递一个DataFrame
或单位映射的dict
时,会忽略box
和utc
参数(GH 23760) -
Bug 在
Series.dt
函数中,进行原地操作后,缓存未能正确更新(GH 24408) -
Bug 在
PeriodIndex
中,与长度为 1 的类数组对象进行比较时未能引发ValueError
(GH 23078) -
Bug 在
DatetimeIndex.astype()
、PeriodIndex.astype()
和TimedeltaIndex.astype()
函数中,对于无符号整数数据类型,忽略了dtype
的符号,导致错误(GH 24405) -
修复了
Series.max()
函数中的 bug,当存在空值且传入skipna=False
时,datetime64[ns]
数据类型未能返回NaT
(GH 24265) -
Bug 在
to_datetime()
函数中,包含既有时区感知又有时区无关的datetime
对象数组的情况下,会失败地引发ValueError
(GH 24569) -
Bug in
to_datetime()
函数中,当传入无效的日期时间格式时,即使设置errors='coerce'
也不会将输入强制转换为NaT
(GH 24763)
时间差
-
Bug 在具有
timedelta64[ns]
数据类型的DataFrame
中,通过Timedelta
类型的标量进行除法运算时,错误地返回timedelta64[ns]
数据类型而不是float64
数据类型(GH 20088, GH 22163) -
Bug 在将具有对象数据类型的
Index
添加到具有timedelta64[ns]
数据类型的Series
时,错误地引发异常(GH 22390) -
Bug 在将具有数值数据类型的
Series
与timedelta
对象相乘时出现错误(GH 22390) -
Bug 在具有数值数据类型的
Series
中,当与具有timedelta64
数据类型的数组或Series
相加或相减时,会出现错误(GH 22390) -
Bug 在具有数值数据类型的
Index
中,当与具有timedelta64
数据类型的数组相乘或相除时出现错误(GH 22390) -
TimedeltaIndex
中的错误,错误地允许使用Timestamp
对象进行索引(GH 20464) -
修复了从对象数据类型数组中减去
Timedelta
会引发TypeError
的错误(GH 21980) -
修复了向具有所有整数数据类型的
DataFrame
中添加具有全部时间增量 64[ns]数据类型的DataFrame
时返回不正确结果的错误,而不是引发TypeError
(GH 22696) -
TimedeltaIndex
中的错误,在添加时区感知的日期时间标量时,错误地返回了一个时区无关的DatetimeIndex
(GH 23215) -
TimedeltaIndex
中的错误,在添加np.timedelta64('NaT')
时,错误地返回了全部为NaT
的DatetimeIndex
而不是全部为NaT
的TimedeltaIndex
(GH 23215) -
Timedelta
和to_timedelta()
中的错误在支持的单位字符串上存在不一致性(GH 21762) -
TimedeltaIndex
中的错误,在除以另一个TimedeltaIndex
时,引发TypeError
而不是返回一个Float64Index
(GH 23829, GH 22631) -
TimedeltaIndex
中的错误,在与非Timedelta
类对象进行比较操作时,会引发TypeError
而不是返回__eq__
时全部为False
和__ne__
时全部为True
(GH 24056) -
在与
Tick
对象比较时,Timedelta
比较出现错误,错误地引发TypeError
(GH 24710)
时区
-
Index.shift()
中的一个错误,当跨越夏令时时会引发AssertionError
(GH 8616) -
在
Timestamp
构造函数中,传递无效的时区偏移标识符(Z
)不会引发ValueError
(GH 8910) -
在替换夏令时边界时,
Timestamp.replace()
会保留不正确的偏移量(GH 7825) -
在替换
NaT
时,使用datetime64[ns, tz]
数据的Series.replace()
中的一个错误(GH 11792) -
在传递不同的字符串日期格式和时区偏移时,
Timestamp
中的一个错误会产生不同的时区偏移(GH 12064) -
当比较不带时区的
Timestamp
和带时区的DatetimeIndex
时,会将DatetimeIndex
强制转换为不带时区的(GH 12601) -
在带时区的
DatetimeIndex
上使用Series.truncate()
会导致核心转储(GH 9243) -
Series
构造函数中的一个错误,会将带时区和不带时区的Timestamp
强制转换为带时区的(GH 13051) -
Index
中的一个错误,datetime64[ns, tz]
数据类型未正确本地化整数数据(GH 20964) -
在使用整数和时区构建时,
DatetimeIndex
存在错误,无法正确本地化(GH 12619) -
修复了在时区感知日期上使用
DataFrame.describe()
和Series.describe()
时未显示first
和last
结果的错误(GH 21328) -
在比较时区感知的
DatetimeIndex
和np.datetime64
时,DatetimeIndex
比较未能引发TypeError
错误(GH 22074) -
使用时区感知标量进行
DataFrame
赋值时存在错误(GH 19843) -
在尝试比较时区感知和非时区感知时间戳时,
DataFrame.asof()
存在引发TypeError
的错误(GH 21194) -
在跨 DST 构建时,使用
replace
方法构建的Timestamp
时存在DatetimeIndex
构建错误(GH 18785) -
当使用带有 DST 转换的
DatetimeIndex
进行新值设置时存在错误,使用DataFrame.loc()
(GH 18308, GH 20724) -
Index.unique()
中存在错误,未能正确重新本地化时区感知日期(GH 21737) -
在带有 DST 转换的情况下索引
Series
时存在错误(GH 21846) -
在时区感知时间序列以 DST 转换结束时,
DataFrame.resample()
和Series.resample()
存在引发AmbiguousTimeError
或NonExistentTimeError
的错误(GH 19375, GH 10117) -
在
DataFrame.drop()
和Series.drop()
中的错误,当指定一个带有时区信息的 Timestamp 键从一个带有 DST 转换的DatetimeIndex
中删除时(GH 21761) -
DatetimeIndex
构造函数中的错误,当NaT
和dateutil.tz.tzlocal
会引发OutOfBoundsDatetime
错误(GH 23807) -
在
DatetimeIndex.tz_localize()
和Timestamp.tz_localize()
中的错误,当在 DST 转换附近使用dateutil.tz.tzlocal
会返回一个错误的本地化日期时间(GH 23807) -
Timestamp
构造函数中的错误,当传递一个带有datetime.datetime
参数的dateutil.tz.tzutc
时,会被转换为pytz.UTC
时区(GH 23807) -
在
to_datetime()
中的错误,当指定unit
和errors='ignore'
时,utc=True
没有被尊重(GH 23758) -
在
to_datetime()
中的错误,当传递一个Timestamp
时,utc=True
没有被尊重(GH 24415) -
DataFrame.any()
中的错误,在axis=1
且数据为日期时间类型时返回错误的值(GH 23070) -
在
DatetimeIndex.to_period()
中的错误,当一个带有时区信息的索引首先被转换为 UTC,然后再创建PeriodIndex
时(GH 22905) -
在
DataFrame.tz_localize()
、DataFrame.tz_convert()
、Series.tz_localize()
和Series.tz_convert()
中的一个 bug,copy=False
会在原始参数上进行原地修改(GH 6326) -
在
DataFrame.max()
和DataFrame.min()
中的一个 bug,使用axis=1
时,当所有列都包含相同的时区时,会返回一个带有NaN
的Series
(GH 10390)
偏移量
-
在
FY5253
中的一个 bug,日期偏移可能会在算术操作中错误地引发AssertionError
(GH 14774) -
在
DateOffset
中的一个 bug,接受并忽略关键字参数week
和milliseconds
。现在传递这些参数将引发ValueError
(GH 19398) -
在添加
DateOffset
与DataFrame
或PeriodIndex
时的一个 bug,错误地引发TypeError
(GH 23215) -
在比较
DateOffset
对象与非DateOffset
对象(特别是字符串)时的一个 bug,引发ValueError
而不是在相等检查时返回False
,在不相等检查时返回True
(GH 23524)
数值
-
在
Series
中的一个 bug,__rmatmul__
不支持矩阵向量乘法(GH 21530) -
在
factorize()
中的一个 bug,无法处理只读数组(GH 12813) -
修复了
unique()
中的一个 bug,处理带符号零不一致:对于某些输入,0.0 和 -0.0 被视为相等,而对于某些输入则被视为不同。现在它们对所有输入都被视为相等(GH 21866) -
当提供函数列表和
axis=1
(例如df.apply(['sum', 'mean'], axis=1)
)时,DataFrame.agg()
、DataFrame.transform()
和DataFrame.apply()
中的错误引发了TypeError
。对于这三种方法,现在这样的计算已经正确执行。(GH 16679) -
Series
与类似日期时间的标量和数组进行比较的错误(GH 22074) -
布尔类型与整数进行乘法运算时,
DataFrame
返回的是object
类型而不是整数类型 (GH 22047, GH 22163) -
DataFrame.apply()
中的错误,当提供字符串参数和额外的位置参数或关键字参数时(例如df.apply('sum', min_count=1)
),错误地引发了TypeError
(GH 22376) -
DataFrame.astype()
中的错误可能会引发AttributeError
(GH 22578) -
使用
timedelta64[ns]
类型的DataFrame
进行与整数类型的ndarray
的算术运算时出现的错误,错误地将 narray 错误地视为timedelta64[ns]
类型 (GH 23114) -
使用对象类型的
Series.rpow()
进行NaN
的1 ** NA
运算时返回的结果是1
而不是NaN
(GH 22922). -
Series.agg()
现在可以处理像numpy.nansum()
这样的 numpy NaN-aware 方法了(GH 19629) -
当
pct=True
且存在超过 2²⁴ 行时,Series.rank()
和DataFrame.rank()
中的错误导致百分比大于 1.0(GH 18271) -
例如,调用
DataFrame.round()
时,具有非唯一CategoricalIndex()
现在会返回预期的数据。以前,数据会被错误地复制(GH 21809)。 -
在
DataFrame.eval()
中,将log10
、floor
和ceil
添加到支持的函数列表中(GH 24139,GH 24353)。 -
逻辑操作
&, |, ^
在Series
和Index
之间将不再引发ValueError
(GH 22092)。 -
在
is_scalar()
函数中检查 PEP 3141 数字将返回True
(GH 22903)。 -
像
Series.sum()
这样的缩减方法现在在从 NumPy ufunc 调用时接受keepdims=False
的默认值,而不是引发TypeError
。尚未实现对keepdims
的完全支持(GH 24356)。
转换
-
在
DataFrame.combine_first()
中存在错误,列类型意外地转换为浮点数(GH 20699)。 -
在
DataFrame.clip()
中存在错误,列类型未被保留并转换为浮点数(GH 24162)。 -
当数据框的列顺序不匹配时,
DataFrame.clip()
中存在错误,观察到的结果在数值上是错误的(GH 20911)。 -
在
DataFrame.astype()
中存在错误,当存在重复列名时转换为扩展数据类型会导致RecursionError
(GH 24704)。
字符串
-
Index.str.partition()
中的错误不是 nan 安全的(GH 23558)。 -
Index.str.split()
中的错误不是 nan 安全的(GH 23677)。 -
Series.str.contains()
中存在的一个错误,对于Categorical
dtype 的Series
,未能遵守na
参数 (GH 22158) -
当结果只包含
NaN
时,Index.str.cat()
中存在的一个错误 (GH 24044)
区间
-
在
IntervalIndex
构造函数中存在的一个错误,其中closed
参数并不总是覆盖推断的closed
(GH 19370) -
在
IntervalIndex
repr 中存在的一个错误,列表中的间隔后缺少一个尾随逗号 (GH 20611) -
Interval
中的一个错误,标量算术运算没有保留closed
值 (GH 22313) -
IntervalIndex
中存在的一个错误,在使用类似日期时间的值进行索引时会引发KeyError
(GH 20636) -
IntervalTree
中的一个错误,其中包含NaN
的数据会触发警告,并导致使用IntervalIndex
进行不正确的索引查询 (GH 23352)
索引
-
DataFrame.ne()
中的一个错误,如果列包含列名“dtype”,则会失败 (GH 22383) -
当使用
.loc
请求单个缺失标签时,KeyError
的回溯现在更短更清晰了 (GH 21557) -
当查找到一个格式错误的字符串时,
PeriodIndex
现在会引发KeyError
,这与DatetimeIndex
的行为一致 (GH 22803) -
当在具有整数类型的第一级的
MultiIndex
中请求缺失的整数标签时,.ix
现在会引发KeyError
,与具有平坦的Int64Index
情况一致,而不是退回到位置索引 (GH 21593) -
修复了重新索引时的 tz-naive 和 tz-aware
DatetimeIndex
的Index.reindex()
中的错误(GH 8306) -
修复了在使用
datetime64[ns, tz]
dtype 重新索引空系列时的Series.reindex()
中的错误(GH 20869) -
修复了使用
.loc
设置值时带有时区信息的DatetimeIndex
的DataFrame
中的问题(GH 11365) -
DataFrame.__getitem__
现在与Series.__getitem__
一致地接受字典和字典键作为标签的列表(GH 21294) -
修复了当列不唯一时
DataFrame[np.nan]
的问题(GH 21428) -
修复了使用纳秒分辨率日期和时区时对
DatetimeIndex
进行索引时的错误(GH 11679) -
修复了使用包含负值的 Numpy 数组进行索引时会更改索引器的错误(GH 21867)
-
修复了混合索引不允许整数使用
.at
的问题(GH 19860) -
当传递布尔键时,
Float64Index.get_loc
现在会引发KeyError
。(GH 19087) -
修复了使用
IntervalIndex
进行索引时的DataFrame.loc()
中的错误(GH 19977) -
Index
不再混淆None
、NaN
和NaT
,即它们被视为三个不同的键。然而,对于数值索引,这三者仍然被强制转换为NaN
(GH 22332) -
修复了当
Index
是整数类型而标量是浮点数时的scalar in Index
中的错误(GH 22085) -
修复了当 levels 值不可索引时
MultiIndex.set_levels()
中的错误(GH 23273) -
设置时间差列时,如果使用
Index
,会将其转换为 double,从而失去精度的错误(GH 23511) -
Index.union()
和Index.intersection()
中的错误,结果的Index
名称未针对某些情况正确计算(GH 9943, GH 9862) -
Index
布尔Index
切片中的错误可能会引发TypeError
(GH 22533) -
在接受切片和类似列表值时,
PeriodArray.__setitem__
中的错误(GH 23978) -
在使用
Ellipsis
进行索引时,DatetimeIndex
、TimedeltaIndex
会丢失它们的freq
属性 (GH 21282) -
在使用
iat
进行分配不兼容值时,存在错误会创建一个新列 (GH 23236)
丢失
-
在一个列包含
datetime64[ns, tz]
dtype 时,DataFrame.fillna()
中会引发ValueError
错误(GH 15522) -
Series.hasnans()
中的错误可能会被错误地缓存,并且在初始调用之后引入 null 元素后返回不正确的答案(GH 19700) -
Series.isin()
现在也将所有 NaN 浮点数视为np.object_
-dtype 相等。此行为与 float64 的行为一致(GH 22119) -
unique()
不再破坏 NaN 浮点数和np.object_
-dtype 的NaT
对象,即NaT
不再被强制转换为 NaN 值,并且被视为一个不同的实体。 (GH 22295) -
DataFrame
和Series
现在正确处理了带有硬化掩码的 numpy 掩码数组。以前,从带有硬掩码的掩码数组构造 DataFrame 或 Series 会创建一个包含底层值而不是预期 NaN 的 pandas 对象。(GH 24574) -
在
DataFrame
构造函数中的一个错误,当处理 numpy 掩码记录数组时未遵循dtype
参数。(GH 24874)
MultiIndex
-
在
io.formats.style.Styler.applymap()
中的一个错误,subset=
与MultiIndex
切片会缩减为Series
(GH 19861) -
移除了对版本 0.8.0 之前的
MultiIndex
pickles 的兼容性;与版本 0.13 以后的MultiIndex
pickles 的兼容性得以保持 (GH 21654) -
MultiIndex.get_loc_level()
(以及作为一个结果,对具有MultiIndex
索引的Series
或DataFrame
的.loc
)现在会引发KeyError
,而不是返回一个空的slice
,如果请求的标签存在于levels
中但未使用(GH 22221) -
MultiIndex
现在具有MultiIndex.from_frame()
,它允许从DataFrame
构造一个MultiIndex
对象 (GH 22420) -
修复了在 Python 3 中创建
MultiIndex
时出现的TypeError
,其中一些级别具有混合类型,例如当一些标签为元组时(GH 15457)
IO
-
Bug in
read_csv()
中存在一个问题,即未能正确将指定为布尔类别的CategoricalDtype
列从字符串值正确转换为布尔值 (GH 20498) -
Bug in
read_csv()
中存在一个问题,即在 Python 2.x 中未能正确识别 Unicode 列名(GH 13253) -
Bug in
DataFrame.to_sql()
中存在一个问题,即在写入带有时区信息的数据(datetime64[ns, tz]
类型)时会引发TypeError
(GH 9086) -
Bug in
DataFrame.to_sql()
中存在一个问题,即在支持的数据库中,例如 PostgreSQL,一个简单的DatetimeIndex
会被写入为TIMESTAMP WITH TIMEZONE
类型(GH 23510) -
Bug in
read_excel()
中存在一个问题,即当使用空数据集指定parse_cols
时出现问题 (GH 9208) -
read_html()
在考虑skiprows
和header
参数时不再忽略<thead>
中所有空白<tr>
。以前,用户必须减少这些表格的header
和skiprows
值以解决此问题。 (GH 21641) -
read_excel()
将正确显示先前已弃用的sheetname
的弃用警告 (GH 17994) -
read_csv()
和read_table()
在遇到编码错误的字符串时将抛出UnicodeError
而不是崩溃 (GH 22748) -
read_csv()
将正确解析带有时区信息的日期时间数据 (GH 22256) -
Bug in
read_csv()
中存在一个问题,即在以块读取数据时,内存管理过早地针对 C 引擎进行了优化(GH 23509) -
在提取多索引时,
read_csv()
中存在错误,未命名列被错误地识别为索引列(GH 23687)。 -
read_sas()
能够正确解析宽度小于 8 字节的 sas7bdat 文件中的数字(GH 21616)。 -
read_sas()
能够正确解析具有许多列的 sas7bdat 文件(GH 22628)。 -
read_sas()
能够正确解析具有数据页类型且位 7 设置的 sas7bdat 文件(因此页面类型为 128 + 256 = 384)(GH 16615)。 -
在无效文件格式上引发错误时,
read_sas()
存在错误,抛出了不正确的错误(GH 24548)。 -
在
detect_client_encoding()
中存在错误,导致在 mod_wsgi 进程中导入时潜在的IOError
未经处理,因为对 stdout 的访问受到限制。(GH 21552) -
在
index=False
时,DataFrame.to_html()
中存在错误,截断的 DataFrame 上缺少截断指示符(…)(GH 15019, GH 22783)。 -
在同时使用
index=False
时,当列和行索引都是MultiIndex
时,DataFrame.to_html()
存在错误(GH 22579)。 -
在使用
index_names=False
时,DataFrame.to_html()
存在错误,显示索引名称(GH 22747)。 -
在使用
header=False
时,DataFrame.to_html()
存在错误,不显示行索引名称(GH 23788)。 -
在使用
sparsify=False
时,DataFrame.to_html()
存在错误,导致引发TypeError
(GH 22887)。 -
在
DataFrame.to_string()
中存在一个 bug,当index=False
且第一列值的宽度大于第一列标题的宽度时,会破坏列对齐 (GH 16839, GH 13032) -
在
DataFrame.to_string()
中存在一个 bug,导致DataFrame
的表示未占满整个窗口 (GH 22984) -
在
DataFrame.to_csv()
中存在一个 bug,单层 MultiIndex 错误地写入了一个元组。现在只写入索引的值 (GH 19589). -
当向
HDFStore
构造函数传递format
kwarg 时,将引发ValueError
(GH 13291) -
在使用
HDFStore.append()
时存在一个 bug,当向其中追加一个带有空字符串列且min_itemsize
< 8 的DataFrame
时 (GH 12242) -
在
read_csv()
中存在一个 bug,当由于完成或错误时未进行足够的清理而导致 C 引擎在解析NaN
值时发生内存泄漏 (GH 21353) -
在
read_csv()
中存在一个 bug,当skipfooter
与nrows
、iterator
或chunksize
一起传入时,会引发不正确的错误消息 (GH 23711) -
在
read_csv()
中存在一个 bug,当未提供MultiIndex
索引名称时,处理不当 (GH 23484) -
在
read_csv()
中存在一个 bug,当方言的值与默认参数冲突时,会引发不必要的警告 (GH 23761) -
在
read_html()
中存在一个 bug,当提供无效的 flavor 时,错误消息未显示有效的 flavors (GH 23549) -
Bug in
read_excel()
中提取了多余的表头名称,即使没有指定任何表头名称(GH 11733) -
Bug in
read_excel()
中有时列名在 Python 2.x 中未被正确转换为字符串(GH 23874) -
Bug in
read_excel()
中index_col=None
未被尊重,仍然解析索引列(GH 18792, GH 20480) -
Bug in
read_excel()
中当作字符串传递时,usecols
未被验证为正确的列名(GH 20480) -
Bug in
DataFrame.to_dict()
当结果字典包含非 Python 标量时出现问题,例如数值数据(GH 23753) -
DataFrame.to_string()
,DataFrame.to_html()
,DataFrame.to_latex()
当作为float_format
参数传递字符串时,将正确格式化输出(GH 21625, GH 22270) -
Bug in
read_csv()
导致在尝试使用‘inf’作为整数索引列的na_value
时引发OverflowError
(GH 17128) -
Bug in
read_csv()
导致 Python 3.6+上的 C 引擎在 Windows 上不正确地读取带有重音或特殊字符的 CSV 文件名(GH 15086) -
Bug in
read_fwf()
中未正确推断文件的压缩类型(GH 22199) -
pandas.io.json.json_normalize()
中的 Bug 导致在record_path
的两个连续元素为字典时引发TypeError
(GH 22706) -
在
DataFrame.to_stata()
、pandas.io.stata.StataWriter
和pandas.io.stata.StataWriter117
中的一个 bug 会导致异常,留下部分写入的无效 dta 文件 (GH 23573)。 -
当使用带有非 ASCII 字符的 strLs 时,
DataFrame.to_stata()
和pandas.io.stata.StataWriter117
会产生无效文件的一个 bug (GH 23573)。 -
在 Python 3 中读取 Python 2 中写入的固定格式的 Dataframe 时,
HDFStore
中的一个 bug 导致它引发ValueError
(GH 24510)。 -
在
DataFrame.to_string()
和浮点repr
格式化器中的一个 bug。如果在列中存在inf
,而且 NA 值的情况下,零不会被修剪。现在在存在 NA 的情况下,零被修剪了 (GH 24861)。 -
在
repr
中的一个 bug,当截断列数并且最后一列很宽时 (GH 24849)。
绘图
-
在 IPython 内联后端中,当 colorbar 打开时,
DataFrame.plot.scatter()
和DataFrame.plot.hexbin()
中的一个 bug 导致 x 轴标签和刻度标签消失 (GH 10611,GH 10678 和 GH 20455)。 -
使用
matplotlib.axes.Axes.scatter()
绘制具有日期时间的 Series 时的一个 bug (GH 22039)。 -
在
DataFrame.plot.bar()
中的一个 bug 导致柱使用多种颜色而不是单一颜色 (GH 20585)。 -
验证颜色参数中的错误导致额外的颜色被附加到给定的颜色数组中。这发生在使用 matplotlib 的多个绘图函数中。 (GH 20726)
GroupBy/resample/rolling
-
在使用
closed='left'
、日期时间索引和系列中只有一个条目时,Rolling.min()
和Rolling.max()
中的一个 bug 导致 segfault (GH 24718)。 -
GroupBy.first()
和GroupBy.last()
中的错误,as_index=False
导致时区信息的丢失(GH 15884) -
DateFrame.resample()
中的错误,当跨越夏令时转换时出现降采样错误(GH 8531) -
DataFrame.resample()
中日期锚定的错误,使用偏移量Day
时,n > 1(GH 24127) -
当分组变量仅包含 NaNs 且 numpy 版本<1.13 时,调用
SeriesGroupBy.count()
方法时错误地引发ValueError
(GH 21956)。 -
Rolling.min()
中的多个错误,使用closed='left'
和 datetime 样式索引导致结果不正确并且可能导致段错误。(GH 21704) -
Resampler.apply()
中的错误,当将位置参数传递给应用的函数时(GH 14615)。 -
Series.resample()
中的错误,当将numpy.timedelta64
传递给loffset
参数时出现问题(GH 7687)。 -
Resampler.asfreq()
中的错误,当TimedeltaIndex
的频率是新频率的子周期时出现问题(GH 13022)。 -
SeriesGroupBy.mean()
中的错误,当值为整数但无法适应 int64 时,会溢出。(GH 22487) -
RollingGroupby.agg()
和ExpandingGroupby.agg()
现在支持多个聚合函数作为参数(GH 15072) -
DataFrame.resample()
和Series.resample()
中的错误,当通过周偏移('W'
)跨越夏令时转换时(GH 9119, GH 21459) -
DataFrame.expanding()
中的错误,聚合期间未尊重axis
参数(GH 23372) -
当输入函数可以接受
DataFrame
但重命名时,GroupBy.transform()
中存在缺失值的问题 (GH 23455). -
GroupBy.nth()
中未始终保留列顺序的问题 (GH 20760) -
当一个组仅有一个成员时,使用
method='dense'
和pct=True
的GroupBy.rank()
会引发ZeroDivisionError
(GH 23666). -
使用空组和
pct=True
调用GroupBy.rank()
会引发ZeroDivisionError
(GH 22519) -
在
TimeDeltaIndex
中重新采样NaT
时,DataFrame.resample()
存在的问题 (GH 13223). -
在选择列时,
DataFrame.groupby()
存在的问题是未遵守observed
参数,并始终使用observed=False
(GH 23970) -
在计算百分比变化时,
SeriesGroupBy.pct_change()
或DataFrameGroupBy.pct_change()
先前跨组工作,现在正确地每组工作 (GH 21200, GH 21235). -
阻止使用非常大的行数(2³²)创建哈希表 (GH 22805)
-
当以分类变量进行分组时,引发
ValueError
和错误分组的 groupby 中的错误 (GH 24740, GH 21151).
重塑
-
在具有时区感知索引的重新采样 DataFrame 中连接时,
pandas.concat()
存在的问题 (GH 13783) -
在仅连接
Series
时,pandas.concat()
存在的问题是concat
的names
参数不再被忽略 (GH 23490) -
在具有
datetime64[ns, tz]
数据类型的情况下,Series.combine_first()
存在的问题是返回的结果不含时区信息 (GH 21469) -
Series.where()
和DataFrame.where()
中存在的datetime64[ns, tz]
dtype 错误(GH 21546) -
当 DataFrame 为空且空的
cond
具有非布尔 dtype 时,DataFrame.where()
中存在的错误(GH 21947) -
使用
list
条件时,Series.mask()
和DataFrame.mask()
中存在的错误(GH 21891) -
在转换
datetime64[ns, tz]
时,DataFrame.replace()
会引发RecursionError
错误(GH 20380) -
当参数
na_option
的值无效时,GroupBy.rank()
现在会引发ValueError
错误(GH 22124) -
在 Python 2 中具有 Unicode 属性的情况下,
get_dummies()
中存在的错误(GH 22084) -
当替换空列表时,
DataFrame.replace()
会引发RecursionError
错误(GH 22083) -
当将 dict 用作
to_replace
值并且字典中的一个键是另一个键的值时,使用整数键和使用字符串键之间的结果不一致,Series.replace()
和DataFrame.replace()
中存在的错误(GH 20656) -
对于空
DataFrame
,DataFrame.drop_duplicates()
错误地引发错误(GH 20516) -
当将字符串传递给 stubnames 参数且列名是该 stubname 的子串时,
pandas.wide_to_long()
中存在的错误(GH 22468) -
在使用
merge()
时,当合并包含夏令时转换的datetime64[ns, tz]
数据时存在错误(GH 18885)。 -
在使用
merge_asof()
时,当在定义的容差范围内合并浮点值时存在错误(GH 22981)。 -
在使用
pandas.concat()
时,当连接一个具有 tz-aware 数据的多列 DataFrame 与一个列数不同的 DataFrame 时存在错误(GH 22796)。 -
在使用
merge_asof()
时,当尝试与缺失值合并时,会引发混淆的错误消息(GH 23189)。 -
在使用
DataFrame.nsmallest()
和DataFrame.nlargest()
对具有MultiIndex
列的数据框进行操作时存在错误(GH 23033)。 -
在使用
pandas.melt()
时,如果传入的列名在DataFrame
中不存在时存在错误(GH 23575)。 -
在使用
DataFrame.append()
时,如果使用带有 dateutil 时区的Series
会引发TypeError
错误(GH 23682)。 -
在使用
Series
构造时,如果传入的数据为空且dtype=str
时存在错误(GH 22477)。 -
在使用
cut()
时,如果bins
是重叠的IntervalIndex
,则会返回每个项目的多个区间而不是引发ValueError
错误(GH 23980)。 -
在使用
pandas.concat()
时,当将Series
datetimetz 与Series
category 连接时,会丢失时区信息(GH 23816)。 -
在使用
DataFrame.join()
时,当在部分 MultiIndex 上进行连接时,会丢失列名(GH 20452)。 -
DataFrame.nlargest()
和DataFrame.nsmallest()
现在在keep != 'all'
时返回正确的 n 值,同时在第一列上打结时也返回正确的值(GH 22752)。 -
使用未在构造函数中指定索引参数的 DataFrame 构造函数破损了(GH 22227)。
-
DataFrame
中的一个 bug 阻止了列表子类的使用(GH 21226)。 -
在
DataFrame.unstack()
和DataFrame.pivot_table()
中存在一个 bug,当生成的 DataFrame 比 int32 能处理的元素多时返回一个误导性的错误消息。现在,错误消息得到了改进,指向了实际问题(GH 20601)。 -
DataFrame.unstack()
存在一个 bug,当解除堆叠时,解除堆叠时区感知的值时引发ValueError
(GH 18338)。 -
DataFrame.stack()
中存在一个 bug,将时区感知的值转换为时区无关的值(GH 19420)。 -
merge_asof()
存在一个 bug,当by_col
是时区感知的值时,引发TypeError
(GH 21184)。 -
在
DataFrame
构造过程中抛出错误时,显示一个不正确的形状。 (GH 20742)
Sparse
-
更新布尔值、日期时间或时间间隔列以稀疏形式现在可以正常工作(GH 22367)。
-
Series.to_sparse()
中存在一个 bug,已经持有稀疏数据的 Series 无法正确构造(GH 22389)。 -
给 SparseArray 构造函数提供
sparse_index
不再将所有数据类型的 na-value 默认为np.nan
。现在使用了data.dtype
的正确 na_value。 -
SparseArray.nbytes
存在一个 bug,通过不包括其稀疏索引的大小来低估其内存使用量。 -
改进了非 NA
fill_value
的Series.shift()
的性能,因为值不再转换为密集数组。 -
在对稀疏列进行分组时,
DataFrame.groupby
中存在一个错误,即当通过稀疏列分组时,非 NAfill_value
不包括在组中 (GH 5078) -
在具有布尔值的
SparseSeries
上存在一元反转运算符(~
)的错误。这方面的性能也得到了改进 (GH 22835) -
在
SparseArray.unique()
中存在一个错误,未返回唯一值 (GH 19595) -
在
SparseArray.nonzero()
和SparseDataFrame.dropna()
中存在一个错误,返回了偏移/不正确的结果 (GH 21172) -
在
DataFrame.apply()
中存在一个错误,即 dtype 会丢失稀疏性 (GH 23744) -
在对所有稀疏值进行连接且更改
fill_value
并转换为密集 Series 时,concat()
存在一个错误 (GH 24371)
样式
-
background_gradient()
现在接受一个text_color_threshold
参数,根据背景颜色的亮度自动调节文本颜色。这可以在不限制背景色彩映射范围的情况下改善在深色背景下的可读性。 (GH 21258) -
background_gradient()
现在还支持表格级应用(除了行级和列级)通过axis=None
(GH 15204) -
bar()
现在还支持表格级应用(除了行级和列级),通过axis=None
设置剪裁范围并使用vmin
和vmax
(GH 21548 和 GH 21526)。NaN
值也得到了正确处理。
构建更改
-
为了开发,构建 pandas 现在需要
cython >= 0.28.2
(GH 21688) -
测试 pandas 现在需要
hypothesis>=3.58
。您可以在这里找到 Hypothesis 文档,以及贡献指南中的 pandas 特定介绍。(GH 22280) -
现在,在 macOS 上构建 pandas 的最低版本为 macOS 10.9,如果在 macOS 10.9 或更高版本上运行,则是这样。(GH 23424)
其他
- Bug where C variables were declared with external linkage causing import errors if certain other C libraries were imported before pandas. (GH 24113) ## 贡献者
本次发布的补丁共有 337 人参与贡献。名字后带有“+”的人是首次贡献补丁的。
-
AJ Dyka +
-
AJ Pryor, Ph.D +
-
Aaron Critchley
-
Adam Hooper
-
Adam J. Stewart
-
金亚当
-
Adam Klimont +
-
Addison Lynch +
-
Alan Hogue +
-
Alex Radu +
-
Alex Rychyk
-
Alex Strick van Linschoten +
-
Alex Volkov +
-
Alexander Buchkovsky
-
Alexander Hess +
-
Alexander Ponomaroff +
-
Allison Browne +
-
Aly Sivji
-
Andrew
-
Andrew Gross +
-
Andrew Spott +
-
Andy +
-
Aniket uttam +
-
Anjali2019 +
-
安娟 +
-
安蒂·凯霍拉 +
-
Anudeep Tubati +
-
Arjun Sharma +
-
Armin Varshokar
-
Artem Bogachev
-
ArtinSarraf +
-
巴里·菲茨杰拉德 +
-
Bart Aelterman +
-
Ben James +
-
Ben Nelson +
-
Benjamin Grove +
-
Benjamin Rowell +
-
Benoit Paquet +
-
Boris Lau +
-
Brett Naul
-
Brian Choi +
-
C.A.M. Gerlach +
-
Carl Johan +
-
Chalmer Lowe
-
Chang She
-
Charles David +
-
Cheuk Ting Ho
-
Chris
-
Chris Roberts +
-
Christopher Whelan
-
朱庆浩 +
-
Da Cheezy Mobsta +
-
Damini Satya
-
Daniel Himmelstein
-
Daniel Saxton +
-
Darcy Meyer +
-
DataOmbudsman
-
David Arcos
-
David Krych
-
Dean Langsam +
-
Diego Argueta +
-
Diego Torres +
-
Dobatymo +
-
Doug Latornell +
-
Dr. Irv
-
Dylan Dmitri Gray +
-
Eric Boxer +
-
Eric Chea
-
Erik +
-
Erik Nilsson +
-
Fabian Haase +
-
Fabian Retkowski
-
Fabien Aulaire +
-
Fakabbir Amin +
-
Fei Phoon +
-
Fernando Margueirat +
-
Florian Müller +
-
Fábio Rosado +
-
盖布·费尔南多
-
加布里埃尔·雷德 +
-
Giftlin Rajaiah
-
Gioia Ballin +
-
Gjelt
-
Gosuke Shibahara +
-
Graham Inggs
-
Guillaume Gay
-
Guillaume Lemaitre +
-
汉娜·费尔克兰德
-
Haochen Wu
-
Hubert +
-
HubertKl +
-
HyunTruth +
-
Iain Barr
-
Ignacio Vergara Kausel +
-
Irv Lustig +
-
IsvenC +
-
Jacopo Rota
-
Jakob Jarmar +
-
James Bourbeau +
-
James Myatt +
-
James Winegar +
-
Jan Rudolph
-
Jared Groves +
-
Jason Kiley +
-
Javad Noorbakhsh +
-
Jay Offerdahl +
-
Jeff Reback
-
俞正民 +
-
Jeremy Schendel
-
Jerod Estapa +
-
Jesper Dramsch +
-
Jim Jeon +
-
Joe Jevnik
-
Joel Nothman
-
Joel Ostblom +
-
Jordi Contestí
-
胡尔赫·洛佩斯富耶奥 +
-
Joris Van den Bossche
-
Jose Quinones +
-
Jose Rivera-Rubio +
-
Josh
-
军 +
-
Justin Zheng +
-
董凯琪 +
-
Kalyan Gokhale
-
康友三 +
-
Karl Dunkle Werner +
-
Karmanya Aggarwal +
-
凯文·马克汉姆 +
-
Kevin Sheppard
-
Kimi Li +
-
Koustav Samaddar +
-
Krishna +
-
Kristian Holsheimer +
-
Ksenia Gueletina +
-
Kyle Prestel +
-
LJ +
-
LeakedMemory +
-
李进 +
-
Licht Takeuchi
-
Luca Donini +
-
Luciano Viola +
-
麦思俊 +
-
Marc Garcia
-
Marius Potgieter +
-
Mark Sikora +
-
Markus Meier +
-
Marlene Silva Marchena +
-
Martin Babka +
-
MatanCohe +
-
Mateusz Woś +
-
Mathew Topper +
-
Matt Boggess +
-
Matt Cooper +
-
Matt Williams +
-
Matthew Gilbert
-
Matthew Roeschke
-
Max Kanter
-
Michael Odintsov
-
Michael Silverstein +
-
Michael-J-Ward +
-
Mickaël Schoentgen +
-
Miguel Sánchez de León Peque +
-
Ming Li
-
Mitar
-
Mitch Negus
-
Monson Shao +
-
Moonsoo Kim +
-
Mortada Mehyar
-
Myles Braithwaite
-
Nehil Jain +
-
Nicholas Musolino +
-
Nicolas Dickreuter +
-
Nikhil Kumar Mengani +
-
Nikoleta Glynatsi +
-
Ondrej Kokes
-
Pablo Ambrosio +
-
Pamela Wu +
-
Parfait G +
-
Patrick Park +
-
Paul
-
Paul Ganssle
-
Paul Reidy
-
Paul van Mulbregt +
-
Phillip Cloud
-
Pietro Battiston
-
Piyush Aggarwal +
-
Prabakaran Kumaresshan +
-
Pulkit Maloo
-
Pyry Kovanen
-
Rajib Mitra +
-
Redonnet Louis +
-
Rhys Parry +
-
Rick +
-
Robin
-
Roei.r +
-
RomainSa +
-
Roman Imankulov +
-
Roman Yurchak +
-
Ruijing Li +
-
Ryan +
-
Ryan Nazareth +
-
Rüdiger Busche +
-
SEUNG HOON, SHIN +
-
Sandrine Pataut +
-
Sangwoong Yoon
-
Santosh Kumar +
-
Saurav Chakravorty +
-
Scott McAllister +
-
Sean Chan +
-
Shadi Akiki +
-
Shengpu Tang +
-
Shirish Kadam +
-
Simon Hawkins +
-
Simon Riddell +
-
Simone Basso
-
Sinhrks
-
Soyoun(Rose) Kim +
-
Srinivas Reddy Thatiparthy (శ్రీనివాస్ రెడ్డి తాటిపర్తి) +
-
Stefaan Lippens +
-
Stefano Cianciulli
-
Stefano Miccoli +
-
Stephen Childs
-
Stephen Pascoe
-
Steve Baker +
-
Steve Cook +
-
Steve Dower +
-
Stéphan Taljaard +
-
Sumin Byeon +
-
Sören +
-
Tamas Nagy +
-
Tanya Jain +
-
Tarbo Fukazawa
-
Thein Oo +
-
Thiago Cordeiro da Fonseca +
-
Thierry Moisan
-
Thiviyan Thanapalasingam +
-
Thomas Lentali +
-
Tim D. Smith +
-
Tim Swast
-
Tom Augspurger
-
Tomasz Kluczkowski +
-
Tony Tao +
-
Triple0 +
-
Troels Nielsen +
-
Tuhin Mahmud +
-
Tyler Reddy +
-
Uddeshya Singh
-
Uwe L. Korn +
-
Vadym Barda +
-
Varad Gunjal +
-
Victor Maryama +
-
Victor Villas
-
Vincent La
-
Vitória Helena +
-
Vu Le
-
Vyom Jain +
-
Weiwen Gu +
-
Wenhuan
-
Wes Turner
-
Wil Tan +
-
William Ayd
-
Yeojin Kim +
-
Yitzhak Andrade +
-
Yuecheng Wu +
-
Yuliya Dovzhenko +
-
Yury Bayda +
-
Zac Hatfield-Dodds +
-
aberres +
-
aeltanawy +
-
ailchau +
-
alimcmaster1
-
alphaCTzo7G +
-
amphy +
-
araraonline +
-
azure-pipelines[bot] +
-
benarthur91 +
-
bk521234 +
-
cgangwar11 +
-
chris-b1
-
cxl923cc +
-
dahlbaek +
-
dannyhyunkim +
-
darke-spirits +
-
david-liu-brattle-1
-
davidmvalente +
-
deflatSOCO
-
doosik_bae +
-
dylanchase +
-
eduardo naufel schettino +
-
euri10 +
-
evangelineliu +
-
fengyqf +
-
fjdiod
-
fl4p +
-
fleimgruber +
-
gfyoung
-
h-vetinari
-
harisbal +
-
henriqueribeiro +
-
himanshu awasthi
-
hongshaoyang +
-
igorfassen +
-
jalazbe +
-
jbrockmendel
-
jh-wu +
-
justinchan23 +
-
louispotok
-
marcosrullan +
-
miker985
-
nicolab100 +
-
nprad
-
nsuresh +
-
ottiP
-
pajachiet +
-
raguiar2 +
-
ratijas +
-
realead +
-
robbuckley +
-
saurav2608 +
-
sideeye +
-
ssikdar1
-
svenharris +
-
syutbai +
-
testvinder +
-
thatneat
-
tmnhat2001
-
tomascassidy +
-
tomneep
-
topper-123
-
vkk800 +
-
winlu +
-
ym-pett +
-
yrhooke +
-
ywpark1 +
-
zertrin
-
zhezherun +
Enhancements
可选整数 NA 支持
pandas 已经具备了保持带有缺失值的整数数据类型的能力。这个长期请求的功能是通过使用扩展类型来实现的。
Note
IntegerArray 目前是实验性的。其 API 或实现可能会在没有警告的情况下发生更改。
我们可以构造一个具有指定数据类型的 Series
。数据类型字符串 Int64
是 pandas 的 ExtensionDtype
。使用传统的缺失值标记 np.nan
来指定列表或数组将推断为整数数据类型。Series
的显示也将使用 NaN
来指示字符串输出中的缺失值。 (GH 20700, GH 20747, GH 22441, GH 21789, GH 22346)
In [1]: s = pd.Series([1, 2, np.nan], dtype='Int64')
In [2]: s
Out[2]:
0 1
1 2
2 <NA>
Length: 3, dtype: Int64
对这些数据类型的操作将像其他 pandas 操作一样传播 NaN
。
# arithmetic
In [3]: s + 1
Out[3]:
0 2
1 3
2 <NA>
Length: 3, dtype: Int64
# comparison
In [4]: s == 1
Out[4]:
0 True
1 False
2 <NA>
Length: 3, dtype: boolean
# indexing
In [5]: s.iloc[1:3]
Out[5]:
1 2
2 <NA>
Length: 2, dtype: Int64
# operate with other dtypes
In [6]: s + s.iloc[1:3].astype('Int8')
Out[6]:
0 <NA>
1 4
2 <NA>
Length: 3, dtype: Int64
# coerce when needed
In [7]: s + 0.01
Out[7]:
0 1.01
1 2.01
2 <NA>
Length: 3, dtype: Float64
这些数据类型可以作为 DataFrame
的一部分运行。
In [8]: df = pd.DataFrame({'A': s, 'B': [1, 1, 3], 'C': list('aab')})
In [9]: df
Out[9]:
A B C
0 1 1 a
1 2 1 a
2 <NA> 3 b
[3 rows x 3 columns]
In [10]: df.dtypes
Out[10]:
A Int64
B int64
C object
Length: 3, dtype: object
这些数据类型可以合并、重塑和转换。
In [11]: pd.concat([df[['A']], df[['B', 'C']]], axis=1).dtypes
Out[11]:
A Int64
B int64
C object
Length: 3, dtype: object
In [12]: df['A'].astype(float)
Out[12]:
0 1.0
1 2.0
2 NaN
Name: A, Length: 3, dtype: float64
缩减和分组操作如 sum
可以工作。
In [13]: df.sum()
Out[13]:
A 3
B 5
C aab
Length: 3, dtype: object
In [14]: df.groupby('B').A.sum()
Out[14]:
B
1 3
3 0
Name: A, Length: 2, dtype: Int64
警告
整数 NA 支持当前使用大写的数据类型版本,例如 Int8
,与传统的 int8
相比。这可能会在未来的某个日期更改。
有关更多信息,请参阅可空整数数据类型。 ### 访问系列或索引中的值
已添加 Series.array
和 Index.array
用于提取 Series
或 Index
的支持数组。 (GH 19954, GH 23623)
In [15]: idx = pd.period_range('2000', periods=4)
In [16]: idx.array
Out[16]:
<PeriodArray>
['2000-01-01', '2000-01-02', '2000-01-03', '2000-01-04']
Length: 4, dtype: period[D]
In [17]: pd.Series(idx).array
Out[17]:
<PeriodArray>
['2000-01-01', '2000-01-02', '2000-01-03', '2000-01-04']
Length: 4, dtype: period[D]
历史上,这通常通过 series.values
来完成,但是使用 .values
时不清楚返回的值是实际数组、它的某种转换,还是 pandas 自定义数组之一(如 Categorical
)。 例如,对于 PeriodIndex
,.values
每次都会生成一个新的 period 对象的 ndarray。
In [18]: idx.values
Out[18]:
array([Period('2000-01-01', 'D'), Period('2000-01-02', 'D'),
Period('2000-01-03', 'D'), Period('2000-01-04', 'D')], dtype=object)
In [19]: id(idx.values)
Out[19]: 140678188264656
In [20]: id(idx.values)
Out[20]: 140678188258896
如果需要实际的 NumPy 数组,请使用 Series.to_numpy()
或 Index.to_numpy()
。
In [21]: idx.to_numpy()
Out[21]:
array([Period('2000-01-01', 'D'), Period('2000-01-02', 'D'),
Period('2000-01-03', 'D'), Period('2000-01-04', 'D')], dtype=object)
In [22]: pd.Series(idx).to_numpy()
Out[22]:
array([Period('2000-01-01', 'D'), Period('2000-01-02', 'D'),
Period('2000-01-03', 'D'), Period('2000-01-04', 'D')], dtype=object)
对于由普通 NumPy 数组支持的 Series 和 Index,Series.array
将返回一个新的 arrays.PandasArray
,它是一个薄(无复制)的包装器,封装了一个 numpy.ndarray
. PandasArray
本身并不特别有用,但它确实提供了与 pandas 中定义的任何扩展数组或第三方库相同的接口。
In [23]: ser = pd.Series([1, 2, 3])
In [24]: ser.array
Out[24]:
<NumpyExtensionArray>
[1, 2, 3]
Length: 3, dtype: int64
In [25]: ser.to_numpy()
Out[25]: array([1, 2, 3])
我们没有移除或弃用 Series.values
或 DataFrame.values
,但我们强烈建议使用 .array
或 .to_numpy()
。
更多信息请参见 Dtypes 和 Attributes and Underlying Data。 ### pandas.array
: 用于创建数组的新顶级方法
新的顶级方法 array()
已添加用于创建 1 维数组(GH 22860)。这可以用于创建任何 扩展数组,包括由 第三方库 注册的扩展数组。有关扩展数组的更多信息,请参见 dtypes 文档。
In [26]: pd.array([1, 2, np.nan], dtype='Int64')
Out[26]:
<IntegerArray>
[1, 2, <NA>]
Length: 3, dtype: Int64
In [27]: pd.array(['a', 'b', 'c'], dtype='category')
Out[27]:
['a', 'b', 'c']
Categories (3, object): ['a', 'b', 'c']
传递没有专用扩展类型的数据(例如浮点数、整数等)将返回一个新的 arrays.PandasArray
,它只是一个围绕满足 pandas 扩展数组接口的 numpy.ndarray
的薄包装(无复制)。
In [28]: pd.array([1, 2, 3])
Out[28]:
<IntegerArray>
[1, 2, 3]
Length: 3, dtype: Int64
单独来看,PandasArray
不是一个非常有用的对象。但是,如果您需要编写适用于任何 ExtensionArray
的低级代码,PandasArray
可以满足这个需求。
请注意,默认情况下,如果未指定 dtype
,则返回数组的 dtype 将从数据中推断出来。特别要注意的是,注意第一个示例 [1, 2, np.nan]
将返回一个浮点数数组,���为 NaN
是一个浮点数。
In [29]: pd.array([1, 2, np.nan])
Out[29]:
<IntegerArray>
[1, 2, <NA>]
Length: 3, dtype: Int64
``` ### 在 Series 和 DataFrame 中存储区间和周期数据
`Interval` 和 `Period` 数据现在可以存储在 `Series` 或 `DataFrame` 中,除了之前只能存储在 `IntervalIndex` 和 `PeriodIndex` 中([GH 19453](https://github.com/pandas-dev/pandas/issues/19453), [GH 22862](https://github.com/pandas-dev/pandas/issues/22862))。
```py
In [30]: ser = pd.Series(pd.interval_range(0, 5))
In [31]: ser
Out[31]:
0 (0, 1]
1 (1, 2]
2 (2, 3]
3 (3, 4]
4 (4, 5]
Length: 5, dtype: interval
In [32]: ser.dtype
Out[32]: interval[int64, right]
对于周期数据:
In [33]: pser = pd.Series(pd.period_range("2000", freq="D", periods=5))
In [34]: pser
Out[34]:
0 2000-01-01
1 2000-01-02
2 2000-01-03
3 2000-01-04
4 2000-01-05
Length: 5, dtype: period[D]
In [35]: pser.dtype
Out[35]: period[D]
以前,这些将被转换为具有对象 dtype 的 NumPy 数组。一般来说,当在Series
中存储区间或周期数组时,这应该会导致更好的性能,或者在DataFrame
的列中存储区间或周期数组时。
使用Series.array
从Series
中提取区间或周期的基础数组:
In [36]: ser.array
Out[36]:
<IntervalArray>
[(0, 1], (1, 2], (2, 3], (3, 4], (4, 5]]
Length: 5, dtype: interval[int64, right]
In [37]: pser.array
Out[37]:
<PeriodArray>
['2000-01-01', '2000-01-02', '2000-01-03', '2000-01-04', '2000-01-05']
Length: 5, dtype: period[D]
这些返回arrays.IntervalArray
或arrays.PeriodArray
的实例,这是支持区间和周期数据的新扩展数组。
警告
为了向后兼容,Series.values
继续返回一个对象的 NumPy 数组,用于区间和周期数据。我们建议在需要存储在Series
中的数据数组时使用Series.array
,在需要 NumPy 数组时使用Series.to_numpy()
。
有关更多信息,请参阅 Dtypes 和属性和底层数据。 ### 与两个多索引连接
DataFrame.merge()
和DataFrame.join()
现在可以用于在重叠的索引级别上连接多索引的Dataframe
实例(GH 6360)
请参阅合并、连接和连接文档部分。
In [38]: index_left = pd.MultiIndex.from_tuples([('K0', 'X0'), ('K0', 'X1'),
....: ('K1', 'X2')],
....: names=['key', 'X'])
....:
In [39]: left = pd.DataFrame({'A': ['A0', 'A1', 'A2'],
....: 'B': ['B0', 'B1', 'B2']}, index=index_left)
....:
In [40]: index_right = pd.MultiIndex.from_tuples([('K0', 'Y0'), ('K1', 'Y1'),
....: ('K2', 'Y2'), ('K2', 'Y3')],
....: names=['key', 'Y'])
....:
In [41]: right = pd.DataFrame({'C': ['C0', 'C1', 'C2', 'C3'],
....: 'D': ['D0', 'D1', 'D2', 'D3']}, index=index_right)
....:
In [42]: left.join(right)
Out[42]:
A B C D
key X Y
K0 X0 Y0 A0 B0 C0 D0
X1 Y0 A1 B1 C0 D0
K1 X2 Y1 A2 B2 C1 D1
[3 rows x 4 columns]
对于早期版本,可以通过以下方式实现。
In [43]: pd.merge(left.reset_index(), right.reset_index(),
....: on=['key'], how='inner').set_index(['key', 'X', 'Y'])
....:
Out[43]:
A B C D
key X Y
K0 X0 Y0 A0 B0 C0 D0
X1 Y0 A1 B1 C0 D0
K1 X2 Y1 A2 B2 C1 D1
[3 rows x 4 columns]
``` ### 函数`read_html`增强
`read_html()`以前忽略`colspan`和`rowspan`属性。现在它理解它们,将它们视为具有相同值的单元格序列。([GH 17054](https://github.com/pandas-dev/pandas/issues/17054))
```py
In [44]: from io import StringIO
In [45]: result = pd.read_html(StringIO("""
....: <table>
....: <thead>
....: <tr>
....: <th>A</th><th>B</th><th>C</th>
....: </tr>
....: </thead>
....: <tbody>
....: <tr>
....: <td colspan="2">1</td><td>2</td>
....: </tr>
....: </tbody>
....: </table>"""))
....:
先前的行为:
In [13]: result
Out [13]:
[ A B C
0 1 2 NaN]
新行为:
In [46]: result
Out[46]:
[ A B C
0 1 1 2
[1 rows x 3 columns]]
新的Styler.pipe()
方法
Styler
类新增了一个 pipe()
方法。这提供了一种方便的方式来应用用户预定义的样式函数,并且可以帮助减少在笔记本中重复使用 DataFrame 样式功能时的“样板代码”。(GH 23229)
In [47]: df = pd.DataFrame({'N': [1250, 1500, 1750], 'X': [0.25, 0.35, 0.50]})
In [48]: def format_and_align(styler):
....: return (styler.format({'N': '{:,}', 'X': '{:.1%}'})
....: .set_properties(**{'text-align': 'right'}))
....:
In [49]: df.style.pipe(format_and_align).set_caption('Summary of results.')
Out[49]: <pandas.io.formats.style.Styler at 0x7ff231a272e0>
pandas 中其他类已经存在类似的方法,包括 DataFrame.pipe()
, GroupBy.pipe()
, 和 Resampler.pipe()
.
在 MultiIndex 中重命名名称
DataFrame.rename_axis()
现在支持 index
和 columns
参数,Series.rename_axis()
支持 index
参数 (GH 19978).
这个改变允许传递一个字典,以便更改 MultiIndex
的一些名称。
示例:
In [50]: mi = pd.MultiIndex.from_product([list('AB'), list('CD'), list('EF')],
....: names=['AB', 'CD', 'EF'])
....:
In [51]: df = pd.DataFrame(list(range(len(mi))), index=mi, columns=['N'])
In [52]: df
Out[52]:
N
AB CD EF
A C E 0
F 1
D E 2
F 3
B C E 4
F 5
D E 6
F 7
[8 rows x 1 columns]
In [53]: df.rename_axis(index={'CD': 'New'})
Out[53]:
N
AB New EF
A C E 0
F 1
D E 2
F 3
B C E 4
F 5
D E 6
F 7
[8 rows x 1 columns]
查看高级文档中的重命名获取更多细节。 ### 其他增强功能
-
merge()
现在直接允许在DataFrame
和命名Series
类型对象之间进行合并,无需事先将Series
对象转换为DataFrame
(GH 21220) -
ExcelWriter
现在接受mode
作为关键字参数,使用openpyxl
引擎时可以追加到现有工作簿中 (GH 3441) -
FrozenList
新增了.union()
和.difference()
方法。这个功能极大地简化了依赖明确排除某些列的 groupby 操作。查看将对象拆分为组获取更多信息 (GH 15475, GH 15506). -
DataFrame.to_parquet()
现在接受index
作为参数,允许用户覆盖引擎的默认行为,包括或排除数据框的索引从生成的 Parquet 文件中。(GH 20768) -
read_feather()
现在接受columns
作为参数,允许用户指定应读取哪些列。(GH 24025) -
DataFrame.corr()
和Series.corr()
现在接受一个可调用的通用相关性计算方法,例如直方图交集。(GH 22684) -
DataFrame.to_string()
现在接受decimal
作为参数,允许用户指定输出中应使用的十进制分隔符。(GH 23614) -
DataFrame.to_html()
现在接受render_links
作为参数,允许用户生成带有链接到 DataFrame 中任何 URL 的 HTML。请参阅 IO 文档中关于写入 HTML 的部分以查看示例用法。(GH 2679) -
pandas.read_csv()
现在支持将 pandas 扩展类型作为dtype
参数,允许用户在读取 CSV 时使用 pandas 扩展类型。(GH 23228) -
shift()
方法现在接受fill_value
作为参数,允许用户指定一个值,该值将在空期间代替 NA/NaT。(GH 15486) -
to_datetime()
现在在传递到format
中时支持%Z
和%z
指令。(GH 13486) -
Series.mode()
和DataFrame.mode()
现在支持dropna
参数,该参数可用于指定是否应考虑NaN
/NaT
值。(GH 17534) -
DataFrame.to_csv()
和Series.to_csv()
现在支持在传递文件句柄时使用compression
关键字。(GH 21227) -
Index.droplevel()
现在也适用于平级索引,以与MultiIndex
兼容(GH 21115) -
Series.droplevel()
和DataFrame.droplevel()
现已实现(GH 20342) -
增加了通过
gcsfs
库从/向 Google Cloud Storage 读取/写入的支持(GH 19454, GH 23094) -
DataFrame.to_gbq()
和read_gbq()
签名和文档已更新以反映来自 pandas-gbq library version 0.8.0 的更改。添加了一个credentials
参数,可以使用任何类型的 google-auth credentials。(GH 21627, GH 22557, GH 23662) -
新方法
HDFStore.walk()
将递归遍历 HDF5 文件的组层次结构(GH 10932) -
read_html()
跨越colspan
和rowspan
复制单元格数据,并且如果没有给出header
kwarg 并且没有thead
,则将所有th
表行视为标题(GH 17054) -
Series.nlargest()
,Series.nsmallest()
,DataFrame.nlargest()
, 和DataFrame.nsmallest()
现在接受值"all"
作为keep
参数。这将保留所有第 n 大/小值的并列项(GH 16818) -
IntervalIndex
新增了set_closed()
方法来更改现有的closed
值 (GH 21670)。 -
to_csv()
、to_csv()
、to_json()
和to_json()
现在支持compression='infer'
,以根据文件扩展名推断压缩格式 (GH 15008)。to_csv
、to_json
和to_pickle
方法的默认压缩格式已更新为'infer'
(GH 22004)。 -
DataFrame.to_sql()
现在支持在支持的数据库中写入TIMESTAMP WITH TIME ZONE
类型。对于不支持时区的数据库,日期时间数据将存储为不带时区信息的本地时间戳。参见 Datetime data types 以了解相关影响 (GH 9086)。 -
to_timedelta()
现在支持 ISO 格式化的 timedelta 字符串 (GH 21877)。 -
Series
和DataFrame
现在在构造函数中支持Iterable
对象 (GH 2193)。 -
DatetimeIndex
新增了DatetimeIndex.timetz
属性。此属性返回带有时区信息的本地时间。(GH 21358)。 -
round()
,ceil()
, 和floor()
对于DatetimeIndex
和Timestamp
现在支持一个ambiguous
参数来处理舍入为模糊时间的日期时间 (GH 18946) 和一个nonexistent
参数来处理舍入为不存在时间的日期时间。参见 本地化时不存在的时间 (GH 22647) -
resample()
的结果现在类似于groupby()
可迭代 (GH 15314). -
Series.resample()
和DataFrame.resample()
现在增加了Resampler.quantile()
(GH 15023). -
DataFrame.resample()
和Series.resample()
现在会像DatetimeIndex
一样尊重base
参数。(GH 23882) -
pandas.api.types.is_list_like()
现在增加了一个关键字allow_sets
,默认为True
;如果为False
,所有set
的实例将不再被视为“类似列表” (GH 23061) -
Index.to_frame()
现在支持覆盖列名 (GH 22580). -
Categorical.from_codes()
现在可以接受dtype
参数,作为传递categories
和ordered
的替代方式(GH 24398)。 -
新属性
__git_version__
将返回当前构建的 git 提交 sha(GH 21295)。 -
与 Matplotlib 3.0 的兼容性(GH 22790)。
-
添加了
Interval.overlaps()
、arrays.IntervalArray.overlaps()
和IntervalIndex.overlaps()
,用于确定区间对象之间的重叠情况(GH 21998)。 -
read_fwf()
现在接受关键字infer_nrows
(GH 15138)。 -
to_parquet()
现在在engine = 'pyarrow'
时支持将DataFrame
写入分区列的 Parquet 文件目录中(GH 23283)。 -
Timestamp.tz_localize()
、DatetimeIndex.tz_localize()
和Series.tz_localize()
现在增加了nonexistent
参数,用于对不存在的时间进行替代处理。参见本地化时不存在的时间(GH 8917、GH 24466)。 -
Index.difference()
、Index.intersection()
、Index.union()
和Index.symmetric_difference()
现在具有可选的sort
参数,用于控制是否应尽可能对结果进行排序 (GH 17839, GH 24471) -
read_excel()
现在接受usecols
作为列名或可调用对象的列表 (GH 18273) -
MultiIndex.to_flat_index()
已添加,将多个级别压平为单级Index
对象。 -
DataFrame.to_stata()
和pandas.io.stata.StataWriter117
可以将混合字符串列写入 Stata strl 格式 (GH 23633) -
DataFrame.between_time()
和DataFrame.at_time()
现已获得axis
参数 (GH 8839) -
DataFrame.to_records()
现在接受index_dtypes
和column_dtypes
参数,允许在存储的列和索引记录中使用不同的数据类型 (GH 18146) -
IntervalIndex
已添加is_overlapping
属性,指示IntervalIndex
是否包含任何重叠区间 (GH 23309) -
pandas.DataFrame.to_sql()
已添加method
参数,用于控制 SQL 插入语句。请参阅文档中的 插入方法 部分。 (GH 8953) -
DataFrame.corrwith()
现在支持 Spearman 秩相关、Kendall's tau 以及可调用的相关方法。(GH 21925) -
DataFrame.to_json()
,DataFrame.to_csv()
,DataFrame.to_pickle()
,以及其他导出方法现在支持路径参数中的波浪号(~)。(GH 23473) ### 可选整数 NA 支持
pandas 已经具备了保存带有缺失值的整数数据类型的能力。这个长期请求的功能是通过使用 扩展类型 实现的。
注意
IntegerArray 目前处于实验阶段。其 API 或实现可能会在没有警告的情况下更改。
我们可以构建指定数据类型的 Series
。数据类型字符串 Int64
是 pandas 的 ExtensionDtype
。使用传统缺失值标记 np.nan
指定列表或数组将推断为整数数据类型。Series
的显示也将使用 NaN
来指示字符串输出中的缺失值。(GH 20700, GH 20747, GH 22441, GH 21789, GH 22346)
In [1]: s = pd.Series([1, 2, np.nan], dtype='Int64')
In [2]: s
Out[2]:
0 1
1 2
2 <NA>
Length: 3, dtype: Int64
这些数据类型的操作将像其他 pandas 操作一样传播 NaN
。
# arithmetic
In [3]: s + 1
Out[3]:
0 2
1 3
2 <NA>
Length: 3, dtype: Int64
# comparison
In [4]: s == 1
Out[4]:
0 True
1 False
2 <NA>
Length: 3, dtype: boolean
# indexing
In [5]: s.iloc[1:3]
Out[5]:
1 2
2 <NA>
Length: 2, dtype: Int64
# operate with other dtypes
In [6]: s + s.iloc[1:3].astype('Int8')
Out[6]:
0 <NA>
1 4
2 <NA>
Length: 3, dtype: Int64
# coerce when needed
In [7]: s + 0.01
Out[7]:
0 1.01
1 2.01
2 <NA>
Length: 3, dtype: Float64
这些数据类型可以作为 DataFrame
的一部分操作。
In [8]: df = pd.DataFrame({'A': s, 'B': [1, 1, 3], 'C': list('aab')})
In [9]: df
Out[9]:
A B C
0 1 1 a
1 2 1 a
2 <NA> 3 b
[3 rows x 3 columns]
In [10]: df.dtypes
Out[10]:
A Int64
B int64
C object
Length: 3, dtype: object
这些数据类型可以合并、重塑和转换。
In [11]: pd.concat([df[['A']], df[['B', 'C']]], axis=1).dtypes
Out[11]:
A Int64
B int64
C object
Length: 3, dtype: object
In [12]: df['A'].astype(float)
Out[12]:
0 1.0
1 2.0
2 NaN
Name: A, Length: 3, dtype: float64
缩减和分组操作如 sum
可以正常工作。
In [13]: df.sum()
Out[13]:
A 3
B 5
C aab
Length: 3, dtype: object
In [14]: df.groupby('B').A.sum()
Out[14]:
B
1 3
3 0
Name: A, Length: 2, dtype: Int64
警告
目前整数 NA 支持使用大写的数据类型版本,例如 Int8
,而不是传统的 int8
。这可能在将来的某个日期更改。
更多信息请参阅 可空整数数据类型。
访问 Series 或 Index 中的值
Series.array
和 Index.array
已添加用于提取支持 Series
或 Index
的数组。(GH 19954, GH 23623)
In [15]: idx = pd.period_range('2000', periods=4)
In [16]: idx.array
Out[16]:
<PeriodArray>
['2000-01-01', '2000-01-02', '2000-01-03', '2000-01-04']
Length: 4, dtype: period[D]
In [17]: pd.Series(idx).array
Out[17]:
<PeriodArray>
['2000-01-01', '2000-01-02', '2000-01-03', '2000-01-04']
Length: 4, dtype: period[D]
在历史上,这将使用series.values
完成,但是使用.values
时不清楚返回的值是否为实际数组,其某些变换,或者是 pandas 自定义数组之一(例如Categorical
)。例如,对于PeriodIndex
,.values
每次生成一个新的周期对象的 ndarray。
In [18]: idx.values
Out[18]:
array([Period('2000-01-01', 'D'), Period('2000-01-02', 'D'),
Period('2000-01-03', 'D'), Period('2000-01-04', 'D')], dtype=object)
In [19]: id(idx.values)
Out[19]: 140678188264656
In [20]: id(idx.values)
Out[20]: 140678188258896
如果您需要一个实际的 NumPy 数组,请使用Series.to_numpy()
或Index.to_numpy()
。
In [21]: idx.to_numpy()
Out[21]:
array([Period('2000-01-01', 'D'), Period('2000-01-02', 'D'),
Period('2000-01-03', 'D'), Period('2000-01-04', 'D')], dtype=object)
In [22]: pd.Series(idx).to_numpy()
Out[22]:
array([Period('2000-01-01', 'D'), Period('2000-01-02', 'D'),
Period('2000-01-03', 'D'), Period('2000-01-04', 'D')], dtype=object)
对于由普通 NumPy 数组支持的 Series 和索引,Series.array
将返回一个新的arrays.PandasArray
,它是一个薄的(不复制)包装器,包装了一个numpy.ndarray
。PandasArray
本身并不特别有用,但它提供了与 pandas 中定义的任何扩展数组或第三方库相同的接口。
In [23]: ser = pd.Series([1, 2, 3])
In [24]: ser.array
Out[24]:
<NumpyExtensionArray>
[1, 2, 3]
Length: 3, dtype: int64
In [25]: ser.to_numpy()
Out[25]: array([1, 2, 3])
我们没有删除或弃用Series.values
或DataFrame.values
,但我们强烈建议使用.array
或.to_numpy()
。
更多信息请参见 Dtypes 和 Attributes and Underlying Data。
pandas.array
:一个用于创建数组的新顶级方法
一个新的顶级方法array()
已添加用于创建 1 维数组(GH 22860)。这可以用于创建任何扩展数组,包括由第三方库注册的扩展数组。有关扩展数组的更多信息,请参阅 dtypes 文档。
In [26]: pd.array([1, 2, np.nan], dtype='Int64')
Out[26]:
<IntegerArray>
[1, 2, <NA>]
Length: 3, dtype: Int64
In [27]: pd.array(['a', 'b', 'c'], dtype='category')
Out[27]:
['a', 'b', 'c']
Categories (3, object): ['a', 'b', 'c']
传递没有专用扩展类型的数据(例如,浮点数,整数等)将返回一个新的arrays.PandasArray
,它只是一个薄的(不复制)包装器,包装了一个numpy.ndarray
,满足 pandas 扩展数组接口。
In [28]: pd.array([1, 2, 3])
Out[28]:
<IntegerArray>
[1, 2, 3]
Length: 3, dtype: Int64
单独一个PandasArray
并不是一个非常有用的对象。但是,如果您需要编写对任何ExtensionArray
都适用的低级代码,那么PandasArray
就满足了这个需求。
请注意,默认情况下,如果未指定 dtype
,则从数据中推断出返回数组的 dtype。特别要注意的是,[1, 2, np.nan]
的第一个示例将返回一个浮点数组,因为 NaN
是一个浮点数。
In [29]: pd.array([1, 2, np.nan])
Out[29]:
<IntegerArray>
[1, 2, <NA>]
Length: 3, dtype: Int64
在 Series 和 DataFrame 中存储间隔和周期数据
Interval
和 Period
数据现在可以存储在 Series
或 DataFrame
中,除了以前的 IntervalIndex
和 PeriodIndex
(GH 19453,GH 22862)。
In [30]: ser = pd.Series(pd.interval_range(0, 5))
In [31]: ser
Out[31]:
0 (0, 1]
1 (1, 2]
2 (2, 3]
3 (3, 4]
4 (4, 5]
Length: 5, dtype: interval
In [32]: ser.dtype
Out[32]: interval[int64, right]
对于周期:
In [33]: pser = pd.Series(pd.period_range("2000", freq="D", periods=5))
In [34]: pser
Out[34]:
0 2000-01-01
1 2000-01-02
2 2000-01-03
3 2000-01-04
4 2000-01-05
Length: 5, dtype: period[D]
In [35]: pser.dtype
Out[35]: period[D]
以前,这些数据将被转换为具有对象 dtype 的 NumPy 数组。一般来说,当在 Series
或 DataFrame
中存储一组间隔或周期时,这应该会导致更好的性能。
使用 Series.array
从 Series
中提取间隔或周期的基础数组:
In [36]: ser.array
Out[36]:
<IntervalArray>
[(0, 1], (1, 2], (2, 3], (3, 4], (4, 5]]
Length: 5, dtype: interval[int64, right]
In [37]: pser.array
Out[37]:
<PeriodArray>
['2000-01-01', '2000-01-02', '2000-01-03', '2000-01-04', '2000-01-05']
Length: 5, dtype: period[D]
这些返回一个 arrays.IntervalArray
或 arrays.PeriodArray
实例,这些实例支持间隔和周期数据。
警告
为了向后兼容,Series.values
仍然返回一个对象的 NumPy 数组,用于间隔和周期数据。我们建议在需要 Series
中存储的数据数组时使用 Series.array
,并在知道需要 NumPy 数组时使用 Series.to_numpy()
。
有关更多信息,请参见 Dtypes 和 Attributes and Underlying Data。
与两个多重索引合并
DataFrame.merge()
和 DataFrame.join()
现在可以用于将具有重叠索引级别的多重索引 DataFrame
实例进行连接(GH 6360)
查看 Merge, join, and concatenate 文档部分。
In [38]: index_left = pd.MultiIndex.from_tuples([('K0', 'X0'), ('K0', 'X1'),
....: ('K1', 'X2')],
....: names=['key', 'X'])
....:
In [39]: left = pd.DataFrame({'A': ['A0', 'A1', 'A2'],
....: 'B': ['B0', 'B1', 'B2']}, index=index_left)
....:
In [40]: index_right = pd.MultiIndex.from_tuples([('K0', 'Y0'), ('K1', 'Y1'),
....: ('K2', 'Y2'), ('K2', 'Y3')],
....: names=['key', 'Y'])
....:
In [41]: right = pd.DataFrame({'C': ['C0', 'C1', 'C2', 'C3'],
....: 'D': ['D0', 'D1', 'D2', 'D3']}, index=index_right)
....:
In [42]: left.join(right)
Out[42]:
A B C D
key X Y
K0 X0 Y0 A0 B0 C0 D0
X1 Y0 A1 B1 C0 D0
K1 X2 Y1 A2 B2 C1 D1
[3 rows x 4 columns]
对于早期版本,可以使用以下方式进行操作。
In [43]: pd.merge(left.reset_index(), right.reset_index(),
....: on=['key'], how='inner').set_index(['key', 'X', 'Y'])
....:
Out[43]:
A B C D
key X Y
K0 X0 Y0 A0 B0 C0 D0
X1 Y0 A1 B1 C0 D0
K1 X2 Y1 A2 B2 C1 D1
[3 rows x 4 columns]
函数 read_html
增强
read_html()
之前忽略了 colspan
和 rowspan
属性。现在它能够理解它们,将它们视为具有相同值的单元格序列。 (GH 17054)
In [44]: from io import StringIO
In [45]: result = pd.read_html(StringIO("""
....: <table>
....: <thead>
....: <tr>
....: <th>A</th><th>B</th><th>C</th>
....: </tr>
....: </thead>
....: <tbody>
....: <tr>
....: <td colspan="2">1</td><td>2</td>
....: </tr>
....: </tbody>
....: </table>"""))
....:
先前的行为:
In [13]: result
Out [13]:
[ A B C
0 1 2 NaN]
新行为:
In [46]: result
Out[46]:
[ A B C
0 1 1 2
[1 rows x 3 columns]]
新的 Styler.pipe()
方法
Styler
类增加了一个 pipe()
方法。这提供了一种方便的方式来应用用户预定义的样式化函数,并且可以在笔记本中重复使用 DataFrame 样式功能时减少“样板代码”。 (GH 23229)
In [47]: df = pd.DataFrame({'N': [1250, 1500, 1750], 'X': [0.25, 0.35, 0.50]})
In [48]: def format_and_align(styler):
....: return (styler.format({'N': '{:,}', 'X': '{:.1%}'})
....: .set_properties(**{'text-align': 'right'}))
....:
In [49]: df.style.pipe(format_and_align).set_caption('Summary of results.')
Out[49]: <pandas.io.formats.style.Styler at 0x7ff231a272e0>
pandas 中已经存在其他类的类似方法,包括 DataFrame.pipe()
、GroupBy.pipe()
和 Resampler.pipe()
。
在多重索引中重命名名称
DataFrame.rename_axis()
现在支持 index
和 columns
参数,而 Series.rename_axis()
支持 index
参数 (GH 19978).
此更改允许传递字典,以便更改 MultiIndex
的一些名称。
示例:
In [50]: mi = pd.MultiIndex.from_product([list('AB'), list('CD'), list('EF')],
....: names=['AB', 'CD', 'EF'])
....:
In [51]: df = pd.DataFrame(list(range(len(mi))), index=mi, columns=['N'])
In [52]: df
Out[52]:
N
AB CD EF
A C E 0
F 1
D E 2
F 3
B C E 4
F 5
D E 6
F 7
[8 rows x 1 columns]
In [53]: df.rename_axis(index={'CD': 'New'})
Out[53]:
N
AB New EF
A C E 0
F 1
D E 2
F 3
B C E 4
F 5
D E 6
F 7
[8 rows x 1 columns]
查看 高级重命名文档 以获取更多详细信息。
其他增强功能
-
merge()
现在直接允许在类型为DataFrame
和命名Series
的对象之间进行合并,无需事先将Series
对象转换为DataFrame
(GH 21220) -
ExcelWriter
现在接受mode
作为关键字参数,使用openpyxl
引擎时可以追加到现有工作簿中(GH 3441) -
FrozenList
现在具有.union()
和.difference()
方法。此功能极大地简化了依赖明确排除某些列的 groupby 操作。有关更多信息,请参见将对象拆分为组(GH 15475, GH 15506)。 -
DataFrame.to_parquet()
现在接受index
作为参数,允许用户覆盖引擎的默认行为,包括或排除结果 Parquet 文件中的数据框索引。(GH 20768) -
read_feather()
现在接受columns
作为参数,允许用户指定应读取哪些列。(GH 24025) -
DataFrame.corr()
和Series.corr()
现在接受可调用对象作为通用相关性计算方法,例如直方图交集(GH 22684) -
DataFrame.to_string()
现在接受decimal
作为参数,允许用户指定输出中应使用哪个小数分隔符。(GH 23614) -
DataFrame.to_html()
现在接受render_links
作为参数,允许用户生成带有指向数据框中任何 URL 的链接的 HTML。请参阅 IO 文档中有关写入 HTML 的部分(../user_guide/io.html#io-html)以获取示例用法。(GH 2679) -
pandas.read_csv()
现在支持将 pandas 扩展类型作为dtype
参数的参数,允许用户在读取 CSV 时使用 pandas 扩展类型。(GH 23228) -
shift()
方法现在接受fill_value
作为参数,允许用户指定在空周期中使用的值,而不是 NA/NaT。(GH 15486) -
to_datetime()
现在在传递给format
时支持%Z
和%z
指令(GH 13486) -
Series.mode()
和DataFrame.mode()
现在支持dropna
参数,该参数可用于指定是否应考虑NaN
/NaT
值(GH 17534) -
当传递文件句柄时,
DataFrame.to_csv()
和Series.to_csv()
现在支持compression
关键字。(GH 21227) -
Index.droplevel()
现在也为平坦索引实现了,以便与MultiIndex
兼容(GH 21115) -
Series.droplevel()
和DataFrame.droplevel()
现已实现(GH 20342) -
增加了通过
gcsfs
库从/向 Google Cloud Storage 读取/写入的支持(GH 19454,GH 23094) -
DataFrame.to_gbq()
和read_gbq()
签名和文档已更新,以反映pandas-gbq 库版本 0.8.0的更改。增加了一个credentials
参数,允许使用任何类型的google-auth 凭据。(GH 21627,GH 22557,GH 23662) -
新方法
HDFStore.walk()
将递归遍历 HDF5 文件的组层次结构(GH 10932) -
read_html()
现在支持跨越colspan
和rowspan
的单元格数据复制,并且如果未给出header
关键字参数且没有thead
,则将所有的th
表行视为标题 (GH 17054) -
Series.nlargest()
,Series.nsmallest()
,DataFrame.nlargest()
, 和DataFrame.nsmallest()
现在接受值为"all"
的keep
参数。这会保留第 n 个最大/最小值的所有关联项 (GH 16818) -
IntervalIndex
增加了set_closed()
方法,用于更改现有的closed
值 (GH 21670) -
to_csv()
,to_csv()
,to_json()
, 和to_json()
现在支持compression='infer'
,以根据文件扩展名推断压缩方式 (GH 15008)。to_csv
、to_json
和to_pickle
方法的默认压缩方式已更新为'infer'
(GH 22004). -
DataFrame.to_sql()
现在支持在支持的数据库中写入TIMESTAMP WITH TIME ZONE
类型。对于不支持时区的数据库,日期时间数据将以不带时区的本地时间戳形式存储。请参阅 Datetime data types 获取相关影响信息 (GH 9086). -
to_timedelta()
现在支持 ISO 格式的时间增量字符串 (GH 21877) -
Series
和DataFrame
现在在构造函数中支持Iterable
对象(GH 2193) -
DatetimeIndex
现在具有DatetimeIndex.timetz
属性。这将返回带有时区信息的本地时间。(GH 21358) -
round()
,ceil()
, 和floor()
用于DatetimeIndex
和Timestamp
现在支持一个ambiguous
参数,用于处理舍入到模糊时间的日期时间(GH 18946),以及一个nonexistent
参数,用于处理舍入到不存在时间的日期时间。参见 本地化时不存在的时间(GH 22647) -
resample()
的结果现在类似于groupby()
可迭代(GH 15314). -
Series.resample()
和DataFrame.resample()
现在具有Resampler.quantile()
(GH 15023). -
DataFrame.resample()
和Series.resample()
与PeriodIndex
现在将像与DatetimeIndex
一样尊重base
参数。(GH 23882) -
pandas.api.types.is_list_like()
现在增加了一个默认为True
的关键词allow_sets
;如果为False
,则不再将所有set
实例视为“类似列表” (GH 23061)。 -
Index.to_frame()
现在支持覆盖列名 (GH 22580)。 -
Categorical.from_codes()
现在可以使用dtype
参数代替传递categories
和ordered
参数 (GH 24398)。 -
新属性
__git_version__
将返回当前构建的 git 提交 sha (GH 21295)。 -
兼容性与 Matplotlib 3.0 (GH 22790)。
-
增加了用于确定区间对象之间重叠的
Interval.overlaps()
、arrays.IntervalArray.overlaps()
和IntervalIndex.overlaps()
(GH 21998)。 -
read_fwf()
现在接受关键词infer_nrows
(GH 15138)。 -
to_parquet()
现在在engine = 'pyarrow'
时支持将DataFrame
写入按列子集分区的 Parquet 文件目录 (GH 23283)。 -
Timestamp.tz_localize()
、DatetimeIndex.tz_localize()
和Series.tz_localize()
现在具有nonexistent
参数,用于替代处理不存在的时间。参见在本地化时的不存在时间 (GH 8917, GH 24466)。 -
Index.difference()
,Index.intersection()
,Index.union()
, 和Index.symmetric_difference()
现在具有可选的sort
参数,用于控制结果是否应在可能的情况下进行排序 (GH 17839, GH 24471) -
read_excel()
现在接受usecols
作为列名列表或可调用对象 (GH 18273) -
MultiIndex.to_flat_index()
已添加以将多个级别展平为单级Index
对象。 -
DataFrame.to_stata()
和pandas.io.stata.StataWriter117
可以将混合字符串列写入 Stata strl 格式 (GH 23633) -
DataFrame.between_time()
和DataFrame.at_time()
增加了axis
参数 (GH 8839) -
DataFrame.to_records()
现在接受index_dtypes
和column_dtypes
参数,允许在存储的列和索引记录中使用不同的数据类型 (GH 18146) -
IntervalIndex
增加了is_overlapping
属性,指示IntervalIndex
是否包含任何重叠区间 (GH 23309) -
pandas.DataFrame.to_sql()
增加了method
参数以控制 SQL 插入子句。请参阅文档中的 插入方法 部分。 (GH 8953) -
DataFrame.corrwith()
现在支持斯皮尔曼秩相关、肯德尔 tau 相关以及可调用的相关方法。(GH 21925) -
DataFrame.to_json()
、DataFrame.to_csv()
、DataFrame.to_pickle()
和其他导出方法现在支持路径参数中的波浪号(~)。 (GH 23473)
向后不兼容的 API 更改
pandas 0.24.0 包含一些破坏 API 的更改。
增加了依赖项的最低版本
我们已更新了我们支持的依赖项的最低版本 (GH 21242, GH 18742, GH 23774, GH 24767)。如果已安装,我们现在要求:
包 | 最低版本 | 必需 |
---|---|---|
numpy | 1.12.0 | X |
bottleneck | 1.2.0 | |
fastparquet | 0.2.1 | |
matplotlib | 2.0.0 | |
numexpr | 2.6.1 | |
pandas-gbq | 0.8.0 | |
pyarrow | 0.9.0 | |
pytables | 3.4.2 | |
scipy | 0.18.1 | |
xlrd | 1.0.0 | |
pytest (dev) | 3.6 |
另外,我们不再依赖于 feather-format
进行基于 feather 的存储,并用对 pyarrow
的引用替换了它 (GH 21639 和 GH 23053)。### DataFrame.to_csv
的 line_terminator
使用 os.linesep
DataFrame.to_csv()
现在使用 os.linesep()
而不是 '\n'
作为默认行终止符 (GH 20353)。这个更改仅影响在 Windows 上运行时,即使 '\n'
被传递给 line_terminator
,也仍然使用 '\r\n'
作为行终止符。
在 Windows 上的先前行为:
In [1]: data = pd.DataFrame({"string_with_lf": ["a\nbc"],
...: "string_with_crlf": ["a\r\nbc"]})
In [2]: # When passing file PATH to to_csv,
...: # line_terminator does not work, and csv is saved with '\r\n'.
...: # Also, this converts all '\n's in the data to '\r\n'.
...: data.to_csv("test.csv", index=False, line_terminator='\n')
In [3]: with open("test.csv", mode='rb') as f:
...: print(f.read())
Out[3]: b'string_with_lf,string_with_crlf\r\n"a\r\nbc","a\r\r\nbc"\r\n'
In [4]: # When passing file OBJECT with newline option to
...: # to_csv, line_terminator works.
...: with open("test2.csv", mode='w', newline='\n') as f:
...: data.to_csv(f, index=False, line_terminator='\n')
In [5]: with open("test2.csv", mode='rb') as f:
...: print(f.read())
Out[5]: b'string_with_lf,string_with_crlf\n"a\nbc","a\r\nbc"\n'
在 Windows 上的新行为:
显式传递 line_terminator
,将 line terminator
设置为该字符。
In [1]: data = pd.DataFrame({"string_with_lf": ["a\nbc"],
...: "string_with_crlf": ["a\r\nbc"]})
In [2]: data.to_csv("test.csv", index=False, line_terminator='\n')
In [3]: with open("test.csv", mode='rb') as f:
...: print(f.read())
Out[3]: b'string_with_lf,string_with_crlf\n"a\nbc","a\r\nbc"\n'
在 Windows 上,os.linesep
的值为 '\r\n'
,所以如果未设置 line_terminator
,则使用 '\r\n'
作为行终止符。
In [1]: data = pd.DataFrame({"string_with_lf": ["a\nbc"],
...: "string_with_crlf": ["a\r\nbc"]})
In [2]: data.to_csv("test.csv", index=False)
In [3]: with open("test.csv", mode='rb') as f:
...: print(f.read())
Out[3]: b'string_with_lf,string_with_crlf\r\n"a\nbc","a\r\nbc"\r\n'
对于文件对象,指定 newline
不足以设置行终止符。即使在这种情况下,您也必须显式传递 line_terminator
。
In [1]: data = pd.DataFrame({"string_with_lf": ["a\nbc"],
...: "string_with_crlf": ["a\r\nbc"]})
In [2]: with open("test2.csv", mode='w', newline='\n') as f:
...: data.to_csv(f, index=False)
In [3]: with open("test2.csv", mode='rb') as f:
...: print(f.read())
Out[3]: b'string_with_lf,string_with_crlf\r\n"a\nbc","a\r\nbc"\r\n'
``` ### 正确处理带有 Python 引擎的字符串数据类型列中的 `np.nan`
在具有 Python 引擎的 `read_excel()` 和 `read_csv()` 中存在错误,在 `dtype=str` 和 `na_filter=True` 的情况下,缺失值会转换为 `'nan'`。现在,这些缺失值将转换为字符串缺失指示器 `np.nan`。 ([GH 20377](https://github.com/pandas-dev/pandas/issues/20377))
*先前的行为*:
```py
In [5]: data = 'a,b,c\n1,,3\n4,5,6'
In [6]: df = pd.read_csv(StringIO(data), engine='python', dtype=str, na_filter=True)
In [7]: df.loc[0, 'b']
Out[7]:
'nan'
新行为:
In [54]: data = 'a,b,c\n1,,3\n4,5,6'
In [55]: df = pd.read_csv(StringIO(data), engine='python', dtype=str, na_filter=True)
In [56]: df.loc[0, 'b']
Out[56]: nan
请注意,我们现在输出 np.nan
本身而不是它的字符串形式。 ### 使用时区偏移解析日期时间字符串
以前,使用 to_datetime()
或 DatetimeIndex
解析具有 UTC 偏移的日期时间字符串会自动将日期时间转换为 UTC 而不进行时区本地化。这与使用 Timestamp
解析相同日期时间字符串时不一致,后者会在 tz
属性中保留 UTC 偏移。现在,当所有日期时间字符串具有相同的 UTC 偏移时,to_datetime()
会保留 tz
属性中的 UTC 偏移 (GH 17697, GH 11736, GH 22457)
先前的行为:
In [2]: pd.to_datetime("2015-11-18 15:30:00+05:30")
Out[2]: Timestamp('2015-11-18 10:00:00')
In [3]: pd.Timestamp("2015-11-18 15:30:00+05:30")
Out[3]: Timestamp('2015-11-18 15:30:00+0530', tz='pytz.FixedOffset(330)')
# Different UTC offsets would automatically convert the datetimes to UTC (without a UTC timezone)
In [4]: pd.to_datetime(["2015-11-18 15:30:00+05:30", "2015-11-18 16:30:00+06:30"])
Out[4]: DatetimeIndex(['2015-11-18 10:00:00', '2015-11-18 10:00:00'], dtype='datetime64[ns]', freq=None)
新行为:
In [57]: pd.to_datetime("2015-11-18 15:30:00+05:30")
Out[57]: Timestamp('2015-11-18 15:30:00+0530', tz='UTC+05:30')
In [58]: pd.Timestamp("2015-11-18 15:30:00+05:30")
Out[58]: Timestamp('2015-11-18 15:30:00+0530', tz='UTC+05:30')
解析具有相同 UTC 偏移的日期时间字符串将保留 tz
中的 UTC 偏移
In [59]: pd.to_datetime(["2015-11-18 15:30:00+05:30"] * 2)
Out[59]: DatetimeIndex(['2015-11-18 15:30:00+05:30', '2015-11-18 15:30:00+05:30'], dtype='datetime64[ns, UTC+05:30]', freq=None)
解析具有不同 UTC 偏移的日期时间字符串现在会创建具有不同 UTC 偏移的 datetime.datetime
对象的索引
In [59]: idx = pd.to_datetime(["2015-11-18 15:30:00+05:30",
"2015-11-18 16:30:00+06:30"])
In[60]: idx
Out[60]: Index([2015-11-18 15:30:00+05:30, 2015-11-18 16:30:00+06:30], dtype='object')
In[61]: idx[0]
Out[61]: Timestamp('2015-11-18 15:30:00+0530', tz='UTC+05:30')
In[62]: idx[1]
Out[62]: Timestamp('2015-11-18 16:30:00+0630', tz='UTC+06:30')
传递 utc=True
将模仿先前的行为,但将正确指示日期已转换为 UTC
In [60]: pd.to_datetime(["2015-11-18 15:30:00+05:30",
....: "2015-11-18 16:30:00+06:30"], utc=True)
....:
Out[60]: DatetimeIndex(['2015-11-18 10:00:00+00:00', '2015-11-18 10:00:00+00:00'], dtype='datetime64[ns, UTC]', freq=None)
``` ### 使用 `read_csv()` 解析混合时区
`read_csv()` 不再将混合时区列悄悄转换为 UTC ([GH 24987](https://github.com/pandas-dev/pandas/issues/24987)).
*先前的行为*
```py
>>> import io
>>> content = """\
... a
... 2000-01-01T00:00:00+05:00
... 2000-01-01T00:00:00+06:00"""
>>> df = pd.read_csv(io.StringIO(content), parse_dates=['a'])
>>> df.a
0 1999-12-31 19:00:00
1 1999-12-31 18:00:00
Name: a, dtype: datetime64[ns]
新行为
In[64]: import io
In[65]: content = """\
...: a
...: 2000-01-01T00:00:00+05:00
...: 2000-01-01T00:00:00+06:00"""
In[66]: df = pd.read_csv(io.StringIO(content), parse_dates=['a'])
In[67]: df.a
Out[67]:
0 2000-01-01 00:00:00+05:00
1 2000-01-01 00:00:00+06:00
Name: a, Length: 2, dtype: object
正如可以看到的,dtype
是对象;列中的每个值都是一个字符串。要将字符串转换为日期时间数组,可以使用 date_parser
参数
In [3]: df = pd.read_csv(
...: io.StringIO(content),
...: parse_dates=['a'],
...: date_parser=lambda col: pd.to_datetime(col, utc=True),
...: )
In [4]: df.a
Out[4]:
0 1999-12-31 19:00:00+00:00
1 1999-12-31 18:00:00+00:00
Name: a, dtype: datetime64[ns, UTC]
更多信息,请参阅使用时区偏移解析日期时间字符串 ### dt.end_time
和 to_timestamp(how='end')
中的时间值
当调用Series.dt.end_time
、Period.end_time
、PeriodIndex.end_time
、Period.to_timestamp()
以及how='end'
参数调用时,PeriodIndex.to_timestamp()
的时间值现在设置为‘23:59:59.999999999’(GH 17157)。
先前的行为:
In [2]: p = pd.Period('2017-01-01', 'D')
In [3]: pi = pd.PeriodIndex([p])
In [4]: pd.Series(pi).dt.end_time[0]
Out[4]: Timestamp(2017-01-01 00:00:00)
In [5]: p.end_time
Out[5]: Timestamp(2017-01-01 23:59:59.999999999)
新行为:
调用Series.dt.end_time
现在将导致时间为‘23:59:59.999999999’,就像Period.end_time
的情况一样,例如
In [61]: p = pd.Period('2017-01-01', 'D')
In [62]: pi = pd.PeriodIndex([p])
In [63]: pd.Series(pi).dt.end_time[0]
Out[63]: Timestamp('2017-01-01 23:59:59.999999999')
In [64]: p.end_time
Out[64]: Timestamp('2017-01-01 23:59:59.999999999')
``` ### 用于时区感知数据的 Series.unique
`Series.unique()` 的返回类型对于带有时区值的日期时间已经从[`numpy.ndarray`](https://numpy.org/doc/stable/reference/generated/numpy.ndarray.html#numpy.ndarray "(in NumPy v1.26)")中的`Timestamp`对象更改为`arrays.DatetimeArray`([GH 24024](https://github.com/pandas-dev/pandas/issues/24024))。
```py
In [65]: ser = pd.Series([pd.Timestamp('2000', tz='UTC'),
....: pd.Timestamp('2000', tz='UTC')])
....:
先前的行为:
In [3]: ser.unique()
Out[3]: array([Timestamp('2000-01-01 00:00:00+0000', tz='UTC')], dtype=object)
新行为:
In [66]: ser.unique()
Out[66]:
<DatetimeArray>
['2000-01-01 00:00:00+00:00']
Length: 1, dtype: datetime64[ns, UTC]
``` ### 稀疏数据结构重构
`SparseArray`,即`SparseSeries`的支持数组和`SparseDataFrame`中的列,现在是一个扩展数组([GH 21978](https://github.com/pandas-dev/pandas/issues/21978),[GH 19056](https://github.com/pandas-dev/pandas/issues/19056),[GH 22835](https://github.com/pandas-dev/pandas/issues/22835))。为了符合这个接口和与 pandas 的其余部分保持一致,进行了一些 API 的破坏性更改:
+ `SparseArray` 不再是[`numpy.ndarray`](https://numpy.org/doc/stable/reference/generated/numpy.ndarray.html#numpy.ndarray "(in NumPy v1.26)")的子类。要将`SparseArray`转换为 NumPy 数组,请使用[`numpy.asarray()`](https://numpy.org/doc/stable/reference/generated/numpy.asarray.html#numpy.asarray "(in NumPy v1.26)")。
+ `SparseArray.dtype` 和 `SparseSeries.dtype` 现在是 `SparseDtype` 的实例,而不是 `np.dtype`。可以使用 `SparseDtype.subtype` 访问底层的 dtype。
+ `numpy.asarray(sparse_array)` 现在返回一个包含所有值的密集数组,而不仅仅是非填充值的值([GH 14167](https://github.com/pandas-dev/pandas/issues/14167))
+ `SparseArray.take` 现在与 `pandas.api.extensions.ExtensionArray.take()` 的 API 匹配([GH 19506](https://github.com/pandas-dev/pandas/issues/19506)):
+ `allow_fill` 的默认值已从 `False` 更改为 `True`。
+ 不再接受 `out` 和 `mode` 参数(先前,如果指定了这些参数,会引发错误)。
+ 不再允许为`indices`传递标量。
+ `concat()` 结果为混合稀疏和密集 Series 的 Series,而不再是 `SparseSeries`。
+ `SparseDataFrame.combine` 和 `DataFrame.combine_first` 不再支持将稀疏列与密集列组合并保留稀疏子类型。结果将是对象类型的 SparseArray。
+ 允许将 `SparseArray.fill_value` 设置为具有不同 dtype 的填充值。
+ 当对具有稀疏值的单个列进行切片时,`DataFrame[column]`现在是一个`Series`,而不再是`SparseSeries`([GH 23559](https://github.com/pandas-dev/pandas/issues/23559))。
+ `Series.where()` 的结果现在是具有稀疏值的 `Series`,与其他扩展数组一样([GH 24077](https://github.com/pandas-dev/pandas/issues/24077))
对于需要或可能导致大型密集数组材料化的操作,现在会发出一些新的警告:
+ 当使用 `method` 进行填充时,会发出 `errors.PerformanceWarning`,因为会构建密集数组来创建填充数组。使用 `value` 进行填充是填充稀疏数组的有效方法。
+ 当连接具有不同填充值的稀疏 Series 时,会发出 `errors.PerformanceWarning`。继续使用第一个稀疏数组的填充值。
除了这些 API 破坏性变化之外,还进行了许多性能改进和错误修复。
最后,添加了`Series.sparse`访问器,提供了类似`Series.sparse.from_coo()`的稀疏特定方法。
```py
In [67]: s = pd.Series([0, 0, 1, 1, 1], dtype='Sparse[int]')
In [68]: s.sparse.density
Out[68]: 0.6
``` ### `get_dummies()`始终返回 DataFrame
以前,当将`sparse=True`传递给`get_dummies()`时,返回值可以是`DataFrame`或`SparseDataFrame`,取决于是所有列还是仅一部分列进行了虚拟编码。现在,始终返回`DataFrame`([GH 24284](https://github.com/pandas-dev/pandas/issues/24284))。
*先前行为*
第一个`get_dummies()`返回一个`DataFrame`,因为列`A`没有进行虚拟编码。当仅传递`["B", "C"]`给`get_dummies`时,然后所有列都进行了虚拟编码,并返回了一个`SparseDataFrame`。
```py
In [2]: df = pd.DataFrame({"A": [1, 2], "B": ['a', 'b'], "C": ['a', 'a']})
In [3]: type(pd.get_dummies(df, sparse=True))
Out[3]: pandas.core.frame.DataFrame
In [4]: type(pd.get_dummies(df[['B', 'C']], sparse=True))
Out[4]: pandas.core.sparse.frame.SparseDataFrame
新行为
现在,返回类型始终是DataFrame
。
In [69]: type(pd.get_dummies(df, sparse=True))
Out[69]: pandas.core.frame.DataFrame
In [70]: type(pd.get_dummies(df[['B', 'C']], sparse=True))
Out[70]: pandas.core.frame.DataFrame
注意
在SparseDataFrame
和具有稀疏值的DataFrame
之间的内存使用没有区别。内存使用量与 pandas 的先前版本相同。 ### 在DataFrame.to_dict(orient='index')
中引发 ValueError
在使用orient='index'
和非唯一索引时,DataFrame.to_dict()
中的错误会引发ValueError
,而不是丢失数据(GH 22801)
In [71]: df = pd.DataFrame({'a': [1, 2], 'b': [0.5, 0.75]}, index=['A', 'A'])
In [72]: df
Out[72]:
a b
A 1 0.50
A 2 0.75
[2 rows x 2 columns]
In [73]: df.to_dict(orient='index')
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
Cell In[73], line 1
----> 1 df.to_dict(orient='index')
File ~/work/pandas/pandas/pandas/util/_decorators.py:333, in deprecate_nonkeyword_arguments.<locals>.decorate.<locals>.wrapper(*args, **kwargs)
327 if len(args) > num_allow_args:
328 warnings.warn(
329 msg.format(arguments=_format_argument_list(allow_args)),
330 FutureWarning,
331 stacklevel=find_stack_level(),
332 )
--> 333 return func(*args, **kwargs)
File ~/work/pandas/pandas/pandas/core/frame.py:2178, in DataFrame.to_dict(self, orient, into, index)
2075 """
2076 Convert the DataFrame to a dictionary.
2077
(...)
2174 defaultdict(<class 'list'>, {'col1': 2, 'col2': 0.75})]
2175 """
2176 from pandas.core.methods.to_dict import to_dict
-> 2178 return to_dict(self, orient, into=into, index=index)
File ~/work/pandas/pandas/pandas/core/methods/to_dict.py:242, in to_dict(df, orient, into, index)
240 elif orient == "index":
241 if not df.index.is_unique:
--> 242 raise ValueError("DataFrame index must be unique for orient='index'.")
243 columns = df.columns.tolist()
244 if are_all_object_dtype_cols:
ValueError: DataFrame index must be unique for orient='index'.
``` ### Tick DateOffset normalize restrictions
使用`normalize=True`创建`Tick`对象(`Day`、`Hour`、`Minute`、`Second`、`Milli`、`Micro`、`Nano`)不再受支持。这可以防止加法无法保持单调性或结合性的意外行为。([GH 21427](https://github.com/pandas-dev/pandas/issues/21427))
*先前行为*:
```py
In [2]: ts = pd.Timestamp('2018-06-11 18:01:14')
In [3]: ts
Out[3]: Timestamp('2018-06-11 18:01:14')
In [4]: tic = pd.offsets.Hour(n=2, normalize=True)
...:
In [5]: tic
Out[5]: <2 * Hours>
In [6]: ts + tic
Out[6]: Timestamp('2018-06-11 00:00:00')
In [7]: ts + tic + tic + tic == ts + (tic + tic + tic)
Out[7]: False
新行为:
In [74]: ts = pd.Timestamp('2018-06-11 18:01:14')
In [75]: tic = pd.offsets.Hour(n=2)
In [76]: ts + tic + tic + tic == ts + (tic + tic + tic)
Out[76]: True
``` ### 期间减法
从另一个`Period`中减去`Period`将给出一个`DateOffset`,而不是一个整数([GH 21314](https://github.com/pandas-dev/pandas/issues/21314))
*先前行为*:
```py
In [2]: june = pd.Period('June 2018')
In [3]: april = pd.Period('April 2018')
In [4]: june - april
Out [4]: 2
新行为:
In [77]: june = pd.Period('June 2018')
In [78]: april = pd.Period('April 2018')
In [79]: june - april
Out[79]: <2 * MonthEnds>
类似地,从PeriodIndex
中减去Period
现在将返回一个DateOffset
对象的Index
,而不是Int64Index
先前行为:
In [2]: pi = pd.period_range('June 2018', freq='M', periods=3)
In [3]: pi - pi[0]
Out[3]: Int64Index([0, 1, 2], dtype='int64')
新行为:
In [80]: pi = pd.period_range('June 2018', freq='M', periods=3)
In [81]: pi - pi[0]
Out[81]: Index([<0 * MonthEnds>, <MonthEnd>, <2 * MonthEnds>], dtype='object')
``` ### 从`DataFrame`中加减`NaN`
从具有`timedelta64[ns]` dtype 的`DataFrame`列中添加或减去`NaN`现在会引发`TypeError`,而不是返回全部`NaT`。这是为了与`TimedeltaIndex`和`Series`的行为兼容([GH 22163](https://github.com/pandas-dev/pandas/issues/22163))
```py
In [82]: df = pd.DataFrame([pd.Timedelta(days=1)])
In [83]: df
Out[83]:
0
0 1 days
[1 rows x 1 columns]
之前的行为:
In [4]: df = pd.DataFrame([pd.Timedelta(days=1)])
In [5]: df - np.nan
Out[5]:
0
0 NaT
新行为:
In [2]: df - np.nan
...
TypeError: unsupported operand type(s) for -: 'TimedeltaIndex' and 'float'
``` ### DataFrame 比较操作广播更改
以前,`DataFrame`比较操作(`==`,`!=`,…)的广播行为与算术操作(`+`,`-`,…)的行为不一致。在这些情况下,比较操作的行为已更改以匹配算术操作的行为。 ([GH 22880](https://github.com/pandas-dev/pandas/issues/22880))
受影响的情况包括:
+ 对于只有 1 行或 1 列的 2 维`np.ndarray`进行操作现在会像`np.ndarray`一样进行广播([GH 23000](https://github.com/pandas-dev/pandas/issues/23000))。
+ 一个与`DataFrame`中行数匹配长度的列表或元组现在会引发`ValueError`,而不是按列操作([GH 22880](https://github.com/pandas-dev/pandas/issues/22880)。
+ 一个与`DataFrame`中列数匹配长度的列表或元组现在会按行操作,而不是引发`ValueError`([GH 22880](https://github.com/pandas-dev/pandas/issues/22880))。
```py
In [84]: arr = np.arange(6).reshape(3, 2)
In [85]: df = pd.DataFrame(arr)
In [86]: df
Out[86]:
0 1
0 0 1
1 2 3
2 4 5
[3 rows x 2 columns]
之前的行为:
In [5]: df == arr[[0], :]
...: # comparison previously broadcast where arithmetic would raise
Out[5]:
0 1
0 True True
1 False False
2 False False
In [6]: df + arr[[0], :]
...
ValueError: Unable to coerce to DataFrame, shape must be (3, 2): given (1, 2)
In [7]: df == (1, 2)
...: # length matches number of columns;
...: # comparison previously raised where arithmetic would broadcast
...
ValueError: Invalid broadcasting comparison [(1, 2)] with block values
In [8]: df + (1, 2)
Out[8]:
0 1
0 1 3
1 3 5
2 5 7
In [9]: df == (1, 2, 3)
...: # length matches number of rows
...: # comparison previously broadcast where arithmetic would raise
Out[9]:
0 1
0 False True
1 True False
2 False False
In [10]: df + (1, 2, 3)
...
ValueError: Unable to coerce to Series, length must be 2: given 3
新行为:
# Comparison operations and arithmetic operations both broadcast.
In [87]: df == arr[[0], :]
Out[87]:
0 1
0 True True
1 False False
2 False False
[3 rows x 2 columns]
In [88]: df + arr[[0], :]
Out[88]:
0 1
0 0 2
1 2 4
2 4 6
[3 rows x 2 columns]
# Comparison operations and arithmetic operations both broadcast.
In [89]: df == (1, 2)
Out[89]:
0 1
0 False False
1 False False
2 False False
[3 rows x 2 columns]
In [90]: df + (1, 2)
Out[90]:
0 1
0 1 3
1 3 5
2 5 7
[3 rows x 2 columns]
# Comparison operations and arithmetic operations both raise ValueError.
In [6]: df == (1, 2, 3)
...
ValueError: Unable to coerce to Series, length must be 2: given 3
In [7]: df + (1, 2, 3)
...
ValueError: Unable to coerce to Series, length must be 2: given 3
``` ### DataFrame 算术操作广播更改
当与 2 维`np.ndarray`对象一起操作时,`DataFrame`算术操作现在会像`np.ndarray`广播一样进行广播。 ([GH 23000](https://github.com/pandas-dev/pandas/issues/23000))
```py
In [91]: arr = np.arange(6).reshape(3, 2)
In [92]: df = pd.DataFrame(arr)
In [93]: df
Out[93]:
0 1
0 0 1
1 2 3
2 4 5
[3 rows x 2 columns]
之前��行为:
In [5]: df + arr[[0], :] # 1 row, 2 columns
...
ValueError: Unable to coerce to DataFrame, shape must be (3, 2): given (1, 2)
In [6]: df + arr[:, [1]] # 1 column, 3 rows
...
ValueError: Unable to coerce to DataFrame, shape must be (3, 2): given (3, 1)
新行为:
In [94]: df + arr[[0], :] # 1 row, 2 columns
Out[94]:
0 1
0 0 2
1 2 4
2 4 6
[3 rows x 2 columns]
In [95]: df + arr[:, [1]] # 1 column, 3 rows
Out[95]:
0 1
0 1 2
1 5 6
2 9 10
[3 rows x 2 columns]
``` ### Series 和 Index 数据-dtype 不兼容性
当数据与传递的`dtype=`不兼容时,`Series`和`Index`构造函数现在会引发异常([GH 15832](https://github.com/pandas-dev/pandas/issues/15832))
*之前的行为*:
```py
In [4]: pd.Series([-1], dtype="uint64")
Out [4]:
0 18446744073709551615
dtype: uint64
新行为:
In [4]: pd.Series([-1], dtype="uint64")
Out [4]:
...
OverflowError: Trying to coerce negative values to unsigned integers
``` ### 连接更改
在具有 NA 值的`Categorical`上调用`pandas.concat()`现在会导致在与除了另一个具有 NA 值的`Categorical`之外的任何东西连接时将它们处理为对象([GH 19214](https://github.com/pandas-dev/pandas/issues/19214))
```py
In [96]: s = pd.Series([0, 1, np.nan])
In [97]: c = pd.Series([0, 1, np.nan], dtype="category")
之前的行为:
In [3]: pd.concat([s, c])
Out[3]:
0 0.0
1 1.0
2 NaN
0 0.0
1 1.0
2 NaN
dtype: float64
新行为
In [98]: pd.concat([s, c])
Out[98]:
0 0.0
1 1.0
2 NaN
0 0.0
1 1.0
2 NaN
Length: 6, dtype: float64
Datetimelike API 更改
-
对于具有非
None
freq
属性的DatetimeIndex
和TimedeltaIndex
,整数类型数组或Index
的加减运算将返回相同类的对象(GH 19959)。 -
DateOffset
对象现在是不可变的。尝试修改其中一个将引发AttributeError
(GH 21341)。 -
PeriodIndex
减去另一个PeriodIndex
现在将返回一个DateOffset
对象的对象数据类型Index
,而不是引发TypeError
(GH 20049)。 -
调用
cut()
和qcut()
现在在输入为 datetime 或 timedelta 数据类型且retbins=True
时会返回一个DatetimeIndex
或TimedeltaIndex
的区间(GH 19891)。 -
当时区信息将丢失时,
DatetimeIndex.to_period()
和Timestamp.to_period()
将发出警告(GH 21333)。 -
PeriodIndex.tz_convert()
和PeriodIndex.tz_localize()
已被移除(GH 21781)。
其他 API 变更
-
现在,若
dtype
为整数的新构建的空DataFrame
只有在指定了index
时才会转换为float64
(GH 22858)。 -
现在,若
others
是一个set
,则Series.str.cat()
会引发错误(GH 23009)。 -
现在,向
DatetimeIndex
或TimedeltaIndex
传递标量值将引发TypeError
而不是ValueError
(GH 23539)。 -
由于截断由
DataFrameFormatter
处理,因此从HTMLFormatter
中删除了max_rows
和max_cols
参数(GH 23818) -
如果声明具有
bool
类型的 dtype 的列存在缺失值,read_csv()
现在会引发ValueError
(GH 20591) -
从
MultiIndex.to_frame()
生成的结果DataFrame
的列顺序现在保证与MultiIndex.names
的顺序相匹配。 (GH 22420) -
错误地将
DatetimeIndex
错误地传递给MultiIndex.from_tuples()
,而不是元组序列,现在会引发TypeError
而不是ValueError
(GH 24024) -
pd.offsets.generate_range()
参数time_rule
已删除;改用offset
代替(GH 24157) -
在 0.23.x 版本中,pandas 在数字列(例如
int
dtyped 列)和object
dtyped 列的合并上引发ValueError
(GH 9780)。我们已重新启用了合并object
和其他 dtype 的功能; pandas 仍然会在数字和仅由字符串组成的object
dtyped 列之间的合并上引发异常(GH 21681) -
使用重复名称访问
MultiIndex
的级别(例如在get_level_values()
中)现在引发ValueError
而不是KeyError
(GH 21678)。 -
构造
IntervalDtype
时如果子类型无效,现在将始终引发TypeError
而不是ValueError
(GH 21185) -
尝试使用非唯一
MultiIndex
重新索引DataFrame
现在会引发ValueError
而不是Exception
(GH 21770) -
Index
减法将尝试按元素操作,而不是引发TypeError
(GH 19369) -
pandas.io.formats.style.Styler
在使用to_excel()
时支持number-format
属性(GH 22015)。 -
DataFrame.corr()
和Series.corr()
现在在提供无效方法时引发ValueError
并提供有用的错误消息,而不是KeyError
(GH 22298)。 -
shift()
现在始终返回一个副本,而不是以前的行为,即当通过 0 进行移位时返回自身(GH 22397)。 -
DataFrame.set_index()
现在在错误类型时提供更好(且更不频繁)的 KeyError,对于重复列名使用drop=True
时不会失败,并且对于不正确类型会引发ValueError
。 (GH 22484) -
对多个相同类型的 ExtensionArrays 的 DataFrame 进行单行切片现在保留 dtype,而不是强制转换为对象(GH 22784)。
-
DateOffset
属性_cacheable
和方法_should_cache
已被移除(GH 23118)。 -
Series.searchsorted()
,当提供标量值进行搜索时,现在返回标量而不是数组(GH 23801)。 -
Categorical.searchsorted()
当提供标量值进行搜索时,现在返回标量而不是数组(GH 23466)。 -
Categorical.searchsorted()
现在在其类别中未找到搜索的键时引发KeyError
而不是ValueError
(GH 23466)。 -
Index.hasnans()
和Series.hasnans()
现在始终返回一个 Python 布尔值。以前,根据情况可能返回 Python 或 NumPy 布尔值(GH 23294)。 -
DataFrame.to_html()
和DataFrame.to_string()
的参数顺序重新排列,使其与彼此一致。 (GH 23614) -
如果目标索引是非唯一且不等于当前索引,则
CategoricalIndex.reindex()
现在会引发ValueError
。之前,它仅在目标索引不是分类 dtype 时引发异常 (GH 23963)。 -
Series.to_list()
和Index.to_list()
现在分别是Series.tolist
和Index.tolist
的别名 (GH 8826) -
SparseSeries.unstack
的结果现在是一个具有稀疏值的DataFrame
,而不是SparseDataFrame
(GH 24372)。 -
DatetimeIndex
和TimedeltaIndex
现在不再忽略 dtype 的精度。传递非纳秒分辨率的 dtype 将引发ValueError
(GH 24753) ### 增加了依赖项的最小版本
我们已经更新了我们支持的依赖项的最低版本 (GH 21242, GH 18742, GH 23774, GH 24767)。如果已安装,我们现在要求:
Package | 最低版本 | 是否必需 |
---|---|---|
numpy | 1.12.0 | X |
bottleneck | 1.2.0 | |
fastparquet | 0.2.1 | |
matplotlib | 2.0.0 | |
numexpr | 2.6.1 | |
pandas-gbq | 0.8.0 | |
pyarrow | 0.9.0 | |
pytables | 3.4.2 | |
scipy | 0.18.1 | |
xlrd | 1.0.0 | |
pytest (dev) | 3.6 |
另外,我们不再依赖 feather-format
用于基于 feather 的存储,并用对 pyarrow
的引用替换它 (GH 21639 和 GH 23053)。
os.linesep
用于 DataFrame.to_csv
的 line_terminator
DataFrame.to_csv()
现在使用 os.linesep()
而不是 '\n'
作为默认的行终止符 (GH 20353)。此更改仅影响在 Windows 上运行时,即使在 line_terminator
中传递了 '\n'
,也会使用 '\r\n'
作为行终止符。
Windows 上的之前行为:
In [1]: data = pd.DataFrame({"string_with_lf": ["a\nbc"],
...: "string_with_crlf": ["a\r\nbc"]})
In [2]: # When passing file PATH to to_csv,
...: # line_terminator does not work, and csv is saved with '\r\n'.
...: # Also, this converts all '\n's in the data to '\r\n'.
...: data.to_csv("test.csv", index=False, line_terminator='\n')
In [3]: with open("test.csv", mode='rb') as f:
...: print(f.read())
Out[3]: b'string_with_lf,string_with_crlf\r\n"a\r\nbc","a\r\r\nbc"\r\n'
In [4]: # When passing file OBJECT with newline option to
...: # to_csv, line_terminator works.
...: with open("test2.csv", mode='w', newline='\n') as f:
...: data.to_csv(f, index=False, line_terminator='\n')
In [5]: with open("test2.csv", mode='rb') as f:
...: print(f.read())
Out[5]: b'string_with_lf,string_with_crlf\n"a\nbc","a\r\nbc"\n'
Windows 上的新行为:
显式传递 line_terminator
,将 line terminator
设置为该字符。
In [1]: data = pd.DataFrame({"string_with_lf": ["a\nbc"],
...: "string_with_crlf": ["a\r\nbc"]})
In [2]: data.to_csv("test.csv", index=False, line_terminator='\n')
In [3]: with open("test.csv", mode='rb') as f:
...: print(f.read())
Out[3]: b'string_with_lf,string_with_crlf\n"a\nbc","a\r\nbc"\n'
在 Windows 上,os.linesep
的值为 '\r\n'
,因此如果未设置 line_terminator
,则使用 '\r\n'
作为行终止符。
In [1]: data = pd.DataFrame({"string_with_lf": ["a\nbc"],
...: "string_with_crlf": ["a\r\nbc"]})
In [2]: data.to_csv("test.csv", index=False)
In [3]: with open("test.csv", mode='rb') as f:
...: print(f.read())
Out[3]: b'string_with_lf,string_with_crlf\r\n"a\nbc","a\r\nbc"\r\n'
对于文件对象,仅指定 newline
不足以设置行终止符。即使在这种情况下,也必须显式传递 line_terminator
。
In [1]: data = pd.DataFrame({"string_with_lf": ["a\nbc"],
...: "string_with_crlf": ["a\r\nbc"]})
In [2]: with open("test2.csv", mode='w', newline='\n') as f:
...: data.to_csv(f, index=False)
In [3]: with open("test2.csv", mode='rb') as f:
...: print(f.read())
Out[3]: b'string_with_lf,string_with_crlf\r\n"a\nbc","a\r\nbc"\r\n'
使用 Python 引擎正确处理字符串数据类型列中的 np.nan
在 Python 引擎中存在 bug,read_excel()
和 read_csv()
中,缺失值转换为 'nan'
,使用 dtype=str
和 na_filter=True
。现在,这些缺失值被转换为字符串缺失指示符 np.nan
。 (GH 20377)
之前的行为:
In [5]: data = 'a,b,c\n1,,3\n4,5,6'
In [6]: df = pd.read_csv(StringIO(data), engine='python', dtype=str, na_filter=True)
In [7]: df.loc[0, 'b']
Out[7]:
'nan'
新的行为:
In [54]: data = 'a,b,c\n1,,3\n4,5,6'
In [55]: df = pd.read_csv(StringIO(data), engine='python', dtype=str, na_filter=True)
In [56]: df.loc[0, 'b']
Out[56]: nan
请注意,我们现在输出 np.nan
本身,而不是其字符串形式。
使用带有时区偏移的日期时间字符串进行解析
以前,使用 to_datetime()
或 DatetimeIndex
解析带有 UTC 偏移的日期时间字符串会自动将日期时间转换为 UTC 而不进行时区本地化。这与使用 Timestamp
解析相同日期时间字符串的不一致,后者将保留 tz
属性中的 UTC 偏移。现在,当所有日期时间字符串具有相同 UTC 偏移时,to_datetime()
会保留 tz
属性中的 UTC 偏移 (GH 17697, GH 11736, GH 22457)
之前的行为:
In [2]: pd.to_datetime("2015-11-18 15:30:00+05:30")
Out[2]: Timestamp('2015-11-18 10:00:00')
In [3]: pd.Timestamp("2015-11-18 15:30:00+05:30")
Out[3]: Timestamp('2015-11-18 15:30:00+0530', tz='pytz.FixedOffset(330)')
# Different UTC offsets would automatically convert the datetimes to UTC (without a UTC timezone)
In [4]: pd.to_datetime(["2015-11-18 15:30:00+05:30", "2015-11-18 16:30:00+06:30"])
Out[4]: DatetimeIndex(['2015-11-18 10:00:00', '2015-11-18 10:00:00'], dtype='datetime64[ns]', freq=None)
新的行为:
In [57]: pd.to_datetime("2015-11-18 15:30:00+05:30")
Out[57]: Timestamp('2015-11-18 15:30:00+0530', tz='UTC+05:30')
In [58]: pd.Timestamp("2015-11-18 15:30:00+05:30")
Out[58]: Timestamp('2015-11-18 15:30:00+0530', tz='UTC+05:30')
使用相同 UTC 偏移解析日期时间字符串将保留 tz
中的 UTC 偏移
In [59]: pd.to_datetime(["2015-11-18 15:30:00+05:30"] * 2)
Out[59]: DatetimeIndex(['2015-11-18 15:30:00+05:30', '2015-11-18 15:30:00+05:30'], dtype='datetime64[ns, UTC+05:30]', freq=None)
使用不同 UTC 偏移解析日期时间字符串现在将创建具有不同 UTC 偏移的 datetime.datetime
对象的索引
In [59]: idx = pd.to_datetime(["2015-11-18 15:30:00+05:30",
"2015-11-18 16:30:00+06:30"])
In[60]: idx
Out[60]: Index([2015-11-18 15:30:00+05:30, 2015-11-18 16:30:00+06:30], dtype='object')
In[61]: idx[0]
Out[61]: Timestamp('2015-11-18 15:30:00+0530', tz='UTC+05:30')
In[62]: idx[1]
Out[62]: Timestamp('2015-11-18 16:30:00+0630', tz='UTC+06:30')
传递 utc=True
将模仿以前的行为,但将正确指示日期已转换为 UTC
In [60]: pd.to_datetime(["2015-11-18 15:30:00+05:30",
....: "2015-11-18 16:30:00+06:30"], utc=True)
....:
Out[60]: DatetimeIndex(['2015-11-18 10:00:00+00:00', '2015-11-18 10:00:00+00:00'], dtype='datetime64[ns, UTC]', freq=None)
使用 read_csv()
解析混合时区的日期时间
read_csv()
不再将混合时区列悄悄地转换为 UTC(GH 24987)。
以前的行为
>>> import io
>>> content = """\
... a
... 2000-01-01T00:00:00+05:00
... 2000-01-01T00:00:00+06:00"""
>>> df = pd.read_csv(io.StringIO(content), parse_dates=['a'])
>>> df.a
0 1999-12-31 19:00:00
1 1999-12-31 18:00:00
Name: a, dtype: datetime64[ns]
新行为
In[64]: import io
In[65]: content = """\
...: a
...: 2000-01-01T00:00:00+05:00
...: 2000-01-01T00:00:00+06:00"""
In[66]: df = pd.read_csv(io.StringIO(content), parse_dates=['a'])
In[67]: df.a
Out[67]:
0 2000-01-01 00:00:00+05:00
1 2000-01-01 00:00:00+06:00
Name: a, Length: 2, dtype: object
如图所示,dtype
为对象;列中的每个值都是一个字符串。要将字符串转换为日期时间数组,可以使用date_parser
参数。
In [3]: df = pd.read_csv(
...: io.StringIO(content),
...: parse_dates=['a'],
...: date_parser=lambda col: pd.to_datetime(col, utc=True),
...: )
In [4]: df.a
Out[4]:
0 1999-12-31 19:00:00+00:00
1 1999-12-31 18:00:00+00:00
Name: a, dtype: datetime64[ns, UTC]
查看使用时区偏移解析日期时间字符串获取更多信息。
dt.end_time
和 to_timestamp(how='end')
中的时间值
Period
和 PeriodIndex
对象中的时间值现在在调用 Series.dt.end_time
、Period.end_time
、PeriodIndex.end_time
、使用 how='end'
的 Period.to_timestamp()
或使用 how='end'
的 PeriodIndex.to_timestamp()
时被设置为‘23:59:59.999999999’(GH 17157)
以前的行为:
In [2]: p = pd.Period('2017-01-01', 'D')
In [3]: pi = pd.PeriodIndex([p])
In [4]: pd.Series(pi).dt.end_time[0]
Out[4]: Timestamp(2017-01-01 00:00:00)
In [5]: p.end_time
Out[5]: Timestamp(2017-01-01 23:59:59.999999999)
新行为:
调用 Series.dt.end_time
现在会导致时间为‘23:59:59.999999999’,就像 Period.end_time
的情况一样,例如
In [61]: p = pd.Period('2017-01-01', 'D')
In [62]: pi = pd.PeriodIndex([p])
In [63]: pd.Series(pi).dt.end_time[0]
Out[63]: Timestamp('2017-01-01 23:59:59.999999999')
In [64]: p.end_time
Out[64]: Timestamp('2017-01-01 23:59:59.999999999')
时区感知数据的 Series.unique
对于带有时区值的日期时间,Series.unique()
的返回类型已从numpy.ndarray
的 Timestamp
对象更改为 arrays.DatetimeArray
(GH 24024)。
In [65]: ser = pd.Series([pd.Timestamp('2000', tz='UTC'),
....: pd.Timestamp('2000', tz='UTC')])
....:
以前的行为:
In [3]: ser.unique()
Out[3]: array([Timestamp('2000-01-01 00:00:00+0000', tz='UTC')], dtype=object)
新行为:
In [66]: ser.unique()
Out[66]:
<DatetimeArray>
['2000-01-01 00:00:00+00:00']
Length: 1, dtype: datetime64[ns, UTC]
稀疏数据结构重构
SparseArray
,支持SparseSeries
和SparseDataFrame
列的数组,现在是一个扩展数组(GH 21978,GH 19056,GH 22835)。为了符合此接口并与 pandas 的其他部分保持一致,进行了一些 API 破坏性变更:
-
SparseArray
不再是numpy.ndarray
的子类。要将SparseArray
转换为 NumPy 数组,请使用numpy.asarray()
。 -
SparseArray.dtype
和SparseSeries.dtype
现在是SparseDtype
的实例,而不是np.dtype
。通过SparseDtype.subtype
访问底层 dtype。 -
numpy.asarray(sparse_array)
现在返回一个具有所有值的密集数组,而不仅仅是非填充值的值(GH 14167)。 -
SparseArray.take
现在匹配了pandas.api.extensions.ExtensionArray.take()
的 API(GH 19506):-
allow_fill
的默认值已从False
更改为True
。 -
不再接受
out
和mode
参数(以前,如果指定了这些参数,则会引发错误)。 -
不再允许将标量用作
indices
。
-
-
concat()
的结果中包含了稀疏和密集 Series 的混合时,结果是一个具有稀疏值的 Series,而不是一个SparseSeries
。 -
SparseDataFrame.combine
和DataFrame.combine_first
不再支持将稀疏列与密集列合并并保留稀疏子类型。结果将是一个对象 dtype 的 SparseArray。 -
现在允许将
SparseArray.fill_value
设置为具有不同 dtype 的填充值。 -
在用稀疏值切片单个列时,
DataFrame[column]
现在是具有稀疏值的Series
,而不是SparseSeries
(GH 23559)。 -
Series.where()
的结果现在是一个具有稀疏值的Series
,与其他扩展数组类似(GH 24077)
对于需要或可能实现大型密集数组的操作,现在会发出一些新的警告:
-
当使用
fillna
与method
时,会发出一个errors.PerformanceWarning
,因为会构建一个稠密数组来创建填充后的数组。用value
进行填充是填充稀疏数组的有效方式。 -
当连接具有不同填充值的稀疏 Series 时,现在会发出一个
errors.PerformanceWarning
。继续使用来自第一个稀疏数组的填充值。
除了这些 API 破坏性变更之外,还进行了许多性能改进和 Bug 修复。
最后,添加了一个Series.sparse
访问器,以提供稀疏特定的方法,例如Series.sparse.from_coo()
。
In [67]: s = pd.Series([0, 0, 1, 1, 1], dtype='Sparse[int]')
In [68]: s.sparse.density
Out[68]: 0.6
get_dummies()
总是返回一个 DataFrame
以前,当传递sparse=True
给get_dummies()
时,返回值可以是一个DataFrame
或一个SparseDataFrame
,这取决于是否对所有列或仅对列的子集进行了虚拟编码。现在,始终返回一个DataFrame
(GH 24284)。
先前行为
第一个get_dummies()
返回一个DataFrame
,因为列A
没有被虚拟编码。当只传递["B", "C"]
给get_dummies
时,所有列都被虚拟编码,并返回一个SparseDataFrame
。
In [2]: df = pd.DataFrame({"A": [1, 2], "B": ['a', 'b'], "C": ['a', 'a']})
In [3]: type(pd.get_dummies(df, sparse=True))
Out[3]: pandas.core.frame.DataFrame
In [4]: type(pd.get_dummies(df[['B', 'C']], sparse=True))
Out[4]: pandas.core.sparse.frame.SparseDataFrame
新行为
现在,返回类型始终是一个DataFrame
。
In [69]: type(pd.get_dummies(df, sparse=True))
Out[69]: pandas.core.frame.DataFrame
In [70]: type(pd.get_dummies(df[['B', 'C']], sparse=True))
Out[70]: pandas.core.frame.DataFrame
注意
在 SparseDataFrame
和具有稀疏值的DataFrame
之间的内存使用没有区别。内存使用量与 pandas 的先前版本相同。
在 DataFrame.to_dict(orient='index')
中引发 ValueError
DataFrame.to_dict()
中的 Bug 在使用 orient='index'
和非唯一索引时会引发 ValueError
,而不是丢失数据(GH 22801)
In [71]: df = pd.DataFrame({'a': [1, 2], 'b': [0.5, 0.75]}, index=['A', 'A'])
In [72]: df
Out[72]:
a b
A 1 0.50
A 2 0.75
[2 rows x 2 columns]
In [73]: df.to_dict(orient='index')
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
Cell In[73], line 1
----> 1 df.to_dict(orient='index')
File ~/work/pandas/pandas/pandas/util/_decorators.py:333, in deprecate_nonkeyword_arguments.<locals>.decorate.<locals>.wrapper(*args, **kwargs)
327 if len(args) > num_allow_args:
328 warnings.warn(
329 msg.format(arguments=_format_argument_list(allow_args)),
330 FutureWarning,
331 stacklevel=find_stack_level(),
332 )
--> 333 return func(*args, **kwargs)
File ~/work/pandas/pandas/pandas/core/frame.py:2178, in DataFrame.to_dict(self, orient, into, index)
2075 """
2076 Convert the DataFrame to a dictionary.
2077
(...)
2174 defaultdict(<class 'list'>, {'col1': 2, 'col2': 0.75})]
2175 """
2176 from pandas.core.methods.to_dict import to_dict
-> 2178 return to_dict(self, orient, into=into, index=index)
File ~/work/pandas/pandas/pandas/core/methods/to_dict.py:242, in to_dict(df, orient, into, index)
240 elif orient == "index":
241 if not df.index.is_unique:
--> 242 raise ValueError("DataFrame index must be unique for orient='index'.")
243 columns = df.columns.tolist()
244 if are_all_object_dtype_cols:
ValueError: DataFrame index must be unique for orient='index'.
Tick DateOffset 规范化限制
使用normalize=True
创建Tick
对象(Day
,Hour
,Minute
,Second
,Milli
,Micro
,Nano
)不再受支持。这可以防止出现添加操作无法保持单调或结合的意外行为。(GH 21427)
之前的行为:
In [2]: ts = pd.Timestamp('2018-06-11 18:01:14')
In [3]: ts
Out[3]: Timestamp('2018-06-11 18:01:14')
In [4]: tic = pd.offsets.Hour(n=2, normalize=True)
...:
In [5]: tic
Out[5]: <2 * Hours>
In [6]: ts + tic
Out[6]: Timestamp('2018-06-11 00:00:00')
In [7]: ts + tic + tic + tic == ts + (tic + tic + tic)
Out[7]: False
新行为:
In [74]: ts = pd.Timestamp('2018-06-11 18:01:14')
In [75]: tic = pd.offsets.Hour(n=2)
In [76]: ts + tic + tic + tic == ts + (tic + tic + tic)
Out[76]: True
期间减法
从另一个Period
中减去一个Period
将得到一个DateOffset
,而不是一个整数(GH 21314)
之前的行为:
In [2]: june = pd.Period('June 2018')
In [3]: april = pd.Period('April 2018')
In [4]: june - april
Out [4]: 2
新行为:
In [77]: june = pd.Period('June 2018')
In [78]: april = pd.Period('April 2018')
In [79]: june - april
Out[79]: <2 * MonthEnds>
类似地,从PeriodIndex
减去Period
现在将返回一个由DateOffset
对象组成的Index
,而不是一个Int64Index
之前的行为:
In [2]: pi = pd.period_range('June 2018', freq='M', periods=3)
In [3]: pi - pi[0]
Out[3]: Int64Index([0, 1, 2], dtype='int64')
新行为:
In [80]: pi = pd.period_range('June 2018', freq='M', periods=3)
In [81]: pi - pi[0]
Out[81]: Index([<0 * MonthEnds>, <MonthEnd>, <2 * MonthEnds>], dtype='object')
从DataFrame
中加减NaN
从具有timedelta64[ns]
dtype 的DataFrame
列中添加或减去NaN
现在将引发TypeError
,而不是返回全部NaT
。这是为了与TimedeltaIndex
和Series
的行为兼容(GH 22163)
In [82]: df = pd.DataFrame([pd.Timedelta(days=1)])
In [83]: df
Out[83]:
0
0 1 days
[1 rows x 1 columns]
之前的行为:
In [4]: df = pd.DataFrame([pd.Timedelta(days=1)])
In [5]: df - np.nan
Out[5]:
0
0 NaT
新行为:
In [2]: df - np.nan
...
TypeError: unsupported operand type(s) for -: 'TimedeltaIndex' and 'float'
DataFrame 比较操作广播变化
以前,DataFrame
比较操作(==
,!=
,…)的广播行为与算术操作(+
,-
,…)的行为不一致。在这些情况下,已更改比较操作的行为以匹配算术操作的行为。(GH 22880)
受影响的情况是:
-
与具有 1 行或 1 列的二维
np.ndarray
进行广播操作将以与np.ndarray
相同的方式进行广播(GH 23000)。 -
与
DataFrame
中行数匹配长度的列表或元组现在将引发ValueError
,而不是逐列操作(GH 22880)。 -
与
DataFrame
中列数匹配的长度的列表或元组现在将逐行操作,而不是引发ValueError
(GH 22880)。
In [84]: arr = np.arange(6).reshape(3, 2)
In [85]: df = pd.DataFrame(arr)
In [86]: df
Out[86]:
0 1
0 0 1
1 2 3
2 4 5
[3 rows x 2 columns]
之前的行为:
In [5]: df == arr[[0], :]
...: # comparison previously broadcast where arithmetic would raise
Out[5]:
0 1
0 True True
1 False False
2 False False
In [6]: df + arr[[0], :]
...
ValueError: Unable to coerce to DataFrame, shape must be (3, 2): given (1, 2)
In [7]: df == (1, 2)
...: # length matches number of columns;
...: # comparison previously raised where arithmetic would broadcast
...
ValueError: Invalid broadcasting comparison [(1, 2)] with block values
In [8]: df + (1, 2)
Out[8]:
0 1
0 1 3
1 3 5
2 5 7
In [9]: df == (1, 2, 3)
...: # length matches number of rows
...: # comparison previously broadcast where arithmetic would raise
Out[9]:
0 1
0 False True
1 True False
2 False False
In [10]: df + (1, 2, 3)
...
ValueError: Unable to coerce to Series, length must be 2: given 3
新行为:
# Comparison operations and arithmetic operations both broadcast.
In [87]: df == arr[[0], :]
Out[87]:
0 1
0 True True
1 False False
2 False False
[3 rows x 2 columns]
In [88]: df + arr[[0], :]
Out[88]:
0 1
0 0 2
1 2 4
2 4 6
[3 rows x 2 columns]
# Comparison operations and arithmetic operations both broadcast.
In [89]: df == (1, 2)
Out[89]:
0 1
0 False False
1 False False
2 False False
[3 rows x 2 columns]
In [90]: df + (1, 2)
Out[90]:
0 1
0 1 3
1 3 5
2 5 7
[3 rows x 2 columns]
# Comparison operations and arithmetic operations both raise ValueError.
In [6]: df == (1, 2, 3)
...
ValueError: Unable to coerce to Series, length must be 2: given 3
In [7]: df + (1, 2, 3)
...
ValueError: Unable to coerce to Series, length must be 2: given 3
DataFrame 算术操作广播变化
当与二维np.ndarray
对象一起进行DataFrame
算术操作时,现在会以与np.ndarray
广播相同的方式进行广播。(GH 23000)
In [91]: arr = np.arange(6).reshape(3, 2)
In [92]: df = pd.DataFrame(arr)
In [93]: df
Out[93]:
0 1
0 0 1
1 2 3
2 4 5
[3 rows x 2 columns]
之前的行为:
In [5]: df + arr[[0], :] # 1 row, 2 columns
...
ValueError: Unable to coerce to DataFrame, shape must be (3, 2): given (1, 2)
In [6]: df + arr[:, [1]] # 1 column, 3 rows
...
ValueError: Unable to coerce to DataFrame, shape must be (3, 2): given (3, 1)
新行为:
In [94]: df + arr[[0], :] # 1 row, 2 columns
Out[94]:
0 1
0 0 2
1 2 4
2 4 6
[3 rows x 2 columns]
In [95]: df + arr[:, [1]] # 1 column, 3 rows
Out[95]:
0 1
0 1 2
1 5 6
2 9 10
[3 rows x 2 columns]
Series 和 Index 数据类型不兼容
当数据与传递的dtype=
不兼容时,Series
和 Index
构造函数现在会引发错误 (GH 15832)
以前的行为:
In [4]: pd.Series([-1], dtype="uint64")
Out [4]:
0 18446744073709551615
dtype: uint64
新行为:
In [4]: pd.Series([-1], dtype="uint64")
Out [4]:
...
OverflowError: Trying to coerce negative values to unsigned integers
连接变更
在带有 NA 值的整数Categorical
上调用pandas.concat()
现在会在与除了另一个整数Categorical
以外的任何东西连接时将其处理为对象 (GH 19214)
In [96]: s = pd.Series([0, 1, np.nan])
In [97]: c = pd.Series([0, 1, np.nan], dtype="category")
以前的行为
In [3]: pd.concat([s, c])
Out[3]:
0 0.0
1 1.0
2 NaN
0 0.0
1 1.0
2 NaN
dtype: float64
新行为
In [98]: pd.concat([s, c])
Out[98]:
0 0.0
1 1.0
2 NaN
0 0.0
1 1.0
2 NaN
Length: 6, dtype: float64
Datetimelike API 更改
-
对于具有非
None
freq
属性的DatetimeIndex
和TimedeltaIndex
,整数 dtype 数组或Index
的加法或减法将返回相同类的对象 (GH 19959) -
DateOffset
对象现在是不可变的。尝试修改其中一个将引发AttributeError
(GH 21341) -
对另一个
PeriodIndex
的减法现在将返回一个DateOffset
对象的对象 dtypeIndex
,而不是引发TypeError
(GH 20049) -
当输入为 datetime 或 timedelta dtype 并且
retbins=True
时,cut()
和qcut()
现在返回一个DatetimeIndex
或TimedeltaIndex
bins (GH 19891) -
当时区信息将丢失时,
DatetimeIndex.to_period()
和Timestamp.to_period()
将发出警告 (GH 21333) -
PeriodIndex.tz_convert()
和PeriodIndex.tz_localize()
已删除 (GH 21781)
其他 API 更改
-
如果指定了
index
,则以整数为dtype
的新构造的空DataFrame
现在只会被转换为float64
(GH 22858) -
如果
others
是一个set
,Series.str.cat()
现在会引发异常 (GH 23009) -
现在向
DatetimeIndex
或TimedeltaIndex
传递标量值将引发TypeError
而不是ValueError
(GH 23539) -
从
HTMLFormatter
中移除了max_rows
和max_cols
参数,因为截断由DataFrameFormatter
处理(GH 23818) -
如果声明具有
bool
类型的列存在缺失值,read_csv()
现在会引发ValueError
(GH 20591) -
从
MultiIndex.to_frame()
得到的结果DataFrame
的列顺序现在保证与MultiIndex.names
的顺序匹配。(GH 22420) -
错误地将
DatetimeIndex
传递给MultiIndex.from_tuples()
,而不是元组序列,现在会引发TypeError
而不是ValueError
(GH 24024) -
pd.offsets.generate_range()
函数的time_rule
参数已被移除;请使用offset
代替(GH 24157) -
在 0.23.x 版本中,pandas 在合并数值列(例如
int
类型列)和object
类型列时会引发ValueError
(GH 9780)。我们已重新启用了合并object
和其他数据类型的功能;pandas 仍会在数值列和仅由字符串组成的object
类型列之间的合并时引发异常 (GH 21681) -
使用重复名称访问
MultiIndex
的层级(例如在get_level_values()
中)现在会引发ValueError
而不是KeyError
(GH 21678) -
无效构造
IntervalDtype
现在总是会引发TypeError
而不是ValueError
,如果子数据类型无效 (GH 21185) -
尝试对具有非唯一
MultiIndex
的DataFrame
重新索引现在会引发ValueError
,而不是引发Exception
(GH 21770) -
Index
的减法将尝试按元素操作,而不是引发TypeError
(GH 19369) -
当使用
to_excel()
时,pandas.io.formats.style.Styler
支持number-format
属性 (GH 22015) -
当提供无效方法时,
DataFrame.corr()
和Series.corr()
现在会引发ValueError
以及有用的错误消息,而不是KeyError
(GH 22298) -
shift()
现在总是返回一个副本,而不是以前当移动0
时返回自身的行为 (GH 22397) -
DataFrame.set_index()
现在提供更好(并且更少见)的KeyError
,对于不正确的类型引发ValueError
,并且在drop=True
时不会因重复列名而失败。 (GH 22484) -
对具有相同类型的多个 ExtensionArrays 的 DataFrame 的单行进行切片现在会保留 dtype,而不是强制转换为 object (GH 22784)
-
DateOffset
属性_cacheable
和方法_should_cache
已删除 (GH 23118) -
当提供一个标量值进行搜索时,
Series.searchsorted()
现在会返回一个标量而不是一个数组 (GH 23801). -
Categorical.searchsorted()
当提供一个标量值进行搜索时,现在会返回一个标量而不是一个数组 (GH 23466). -
Categorical.searchsorted()
现在在其类别中找不到搜索到的键时会引发KeyError
而不是ValueError
(GH 23466). -
Index.hasnans()
和Series.hasnans()
现在总是返回 Python 布尔值。以前,根据情况可能返回 Python 或 NumPy 布尔值 (GH 23294)。 -
DataFrame.to_html()
和DataFrame.to_string()
的参数顺序已重新排列,以使它们相互一致 (GH 23614)。 -
CategoricalIndex.reindex()
现在在目标索引非唯一且不等于当前索引时会引发ValueError
。以前只有在目标索引不是分类类型时才会引发 (GH 23963)。 -
Series.to_list()
和Index.to_list()
现在分别是Series.tolist
和Index.tolist
的别名 (GH 8826)。 -
SparseSeries.unstack
的结果现在是具有稀疏值的DataFrame
,而不是SparseDataFrame
(GH 24372)。 -
DatetimeIndex
和TimedeltaIndex
现在不再忽略 dtype 的精度。传递非纳秒分辨率的 dtype 将引发ValueError
(GH 24753)。
扩展类型更改
相等性和可哈希性
pandas 现在要求扩展 dtype 可哈希(即相应的 ExtensionDtype
对象;相应的 ExtensionArray
的值不需要可哈希)。基类实现了默认的 __eq__
和 __hash__
。如果您有一个参数化的 dtype,应该更新 ExtensionDtype._metadata
元组以匹配您的 __init__
方法的签名。请参阅 pandas.api.extensions.ExtensionDtype
了解更多信息 (GH 22476)。
新的和更改的方法
-
已添加
dropna()
(GH 21185)。 -
已添加
repeat()
(GH 24349)。 -
ExtensionArray
构造函数_from_sequence
现在接受关键字参数copy=False
(GH 21185) -
pandas.api.extensions.ExtensionArray.shift()
作为基本ExtensionArray
接口的一部分被添加(GH 22387)。 -
已添加
searchsorted()
(GH 24350) -
通过基类方法重写,支持
sum
、mean
等缩减操作(GH 22762) -
ExtensionArray.isna()
允许返回一个ExtensionArray
(GH 22325)。
Dtype 变更
-
ExtensionDtype
现在能够从字符串 dtype 实例化,例如,decimal
会实例化一个已注册的DecimalDtype
;此外,ExtensionDtype
还获得了方法construct_array_type
(GH 21185) -
添加了
ExtensionDtype._is_numeric
以控制扩展 dtype 是否被视为数值型(GH 22290)。 -
添加了
pandas.api.types.register_extension_dtype()
来向 pandas 注册扩展类型(GH 22664) -
更新了
PeriodDtype
、DatetimeTZDtype
和IntervalDtype
的.type
属性,使其成为 dtype 实例(分别为Period
、Timestamp
和Interval
)(GH 22938)
运算符支持
基于ExtensionArray
的Series
现在支持算术和比较运算符(GH 19577)。提供ExtensionArray
运算符支持的两种方法:
-
在你的
ExtensionArray
子类上定义每个运算符。 -
使用 pandas 中依赖于已在
ExtensionArray
底层元素(标量)上定义的运算符的运算符实现。
详细信息请参阅 ExtensionArray 运算符支持文档部分。
其他变更
-
为
pandas.api.extensions.ExtensionArray
提供了默认的 repr(GH 23601)。 -
ExtensionArray._formatting_values()
已弃用。请改用ExtensionArray._formatter
(GH 23601) -
具有布尔 dtype 的
ExtensionArray
现在作为布尔索引器正常工作。pandas.api.types.is_bool_dtype()
现在正确地将它们视为布尔值(GH 22326)。
错误修复
-
在使用
ExtensionArray
和整数索引的系列中修复了Series.get()
的错误(GH 21257)。 -
shift()
现在分派到ExtensionArray.shift()
(GH 22386) -
在
Series
内部,Series.combine()
现在与ExtensionArray
正确工作(GH 20825)。 -
现在,带有标量参数的
Series.combine()
对任何函数类型都有效(GH 21248)。 -
Series.astype()
和DataFrame.astype()
现在分派到ExtensionArray.astype()
(GH 21185)。 -
使用相同类型的多个 ExtensionArrays 对 DataFrame 的单个行进行切片现在保留 dtype,而不是强制转换为对象 dtype(GH 22784)。
-
在连接多个具有不同扩展 dtype 的
Series
时出现错误,未转换为对象 dtype(GH 22994)。 -
支持
ExtensionArray
的系列现在可以使用util.hash_pandas_object()
(GH 23066)。 -
DataFrame.stack()
不再对每列具有相同扩展 dtype 的 DataFrame 转换为对象 dtype。输出的 Series 将具有与列相同的 dtype(GH 23077)。 -
Series.unstack()
和DataFrame.unstack()
不再将扩展数组转换为 object-dtype 的 ndarrays。输出DataFrame
中的每一列现在都将具有与输入相同的 dtype (GH 23077). -
在
Dataframe.groupby()
分组和在ExtensionArray
上聚合时存在 bug,它没有返回实际的ExtensionArray
dtype (GH 23227). -
当在扩展数组支持的列上进行合并时,在
pandas.merge()
中存在 bug (GH 23020).
废弃功能
-
MultiIndex.labels
已经废弃,并被MultiIndex.codes
替换。功能保持不变。新名称更好地反映了这些代码的性质,并使MultiIndex
API 更类似于CategoricalIndex
的 API (GH 13443). 因此,MultiIndex
中其他使用labels
名称的功能也已被废弃,并替换为codes
:-
使用名为
codes
而不是labels
的参数来初始化一个MultiIndex
实例。 -
MultiIndex.set_labels
已经废弃,建议使用MultiIndex.set_codes()
。 -
对于方法
MultiIndex.copy()
,labels
参数已经废弃,替换为codes
参数。
-
-
DataFrame.to_stata()
,read_stata()
,StataReader
和StataWriter
已经废弃了encoding
参数。Stata dta 文件的编码由文件类型确定,不能更改(GH 21244) -
MultiIndex.to_hierarchical()
已经废弃,并将在将来的版本中删除(GH 21613) -
Series.ptp()
已经废弃。请使用numpy.ptp
代替(GH 21614) -
Series.compress()
已经废弃。请使用Series[condition]
代替(GH 18262) -
Series.to_csv()
的签名已经统一为DataFrame.to_csv()
:第一个参数的名称现在是path_or_buf
,后续参数的顺序已更改,header
参数现在默认为True
(GH 19715)。 -
Categorical.from_codes()
已弃用为codes
参数提供浮点值。(GH 21767) -
pandas.read_table()
已弃用。请改用read_csv()
,必要时传递sep='\t'
。此弃用已在 0.25.0 版中移除。(GH 21948) -
Series.str.cat()
已弃用在列表类中使用任意列表类内部。列表类容器仍然可以包含许多Series
、Index
或一维np.ndarray
,或者仅包含标量值。(GH 21950) -
FrozenNDArray.searchsorted()
已弃用v
参数,改用value
(GH 14645) -
DatetimeIndex.shift()
和PeriodIndex.shift()
现在接受periods
参数,而不是n
,以保持与Index.shift()
和Series.shift()
的一致性。使用n
会引发弃用警告 (GH 22458, GH 22912) -
不同的索引构造函数中的
fastpath
关键字已被弃用(GH 23110)。 -
Timestamp.tz_localize()
,DatetimeIndex.tz_localize()
和Series.tz_localize()
已弃用errors
参数,改为使用nonexistent
参数(GH 8917) -
类
FrozenNDArray
已经被弃用。当反序列化时,一旦删除此类,FrozenNDArray
将被反序列化为np.ndarray
(GH 9031) -
方法
DataFrame.update()
和Panel.update()
已经弃用raise_conflict=False|True
关键字,而是使用errors='ignore'|'raise'
(GH 23585) -
方法
Series.str.partition()
和Series.str.rpartition()
已经弃用pat
关键字,而是使用sep
(GH 22676) -
弃用了
pandas.read_feather()
的nthreads
关键字,改用use_threads
以反映pyarrow>=0.11.0
中的更改(GH 23053) -
pandas.read_excel()
已经弃用接受usecols
作为整数。请传入一个从 0 到usecols
的整数列表(包括usecols
)代替(GH 23527) -
从带有
datetime64
数据类型的数据构建TimedeltaIndex
已经被弃用,在将来的版本中会引发TypeError
(GH 23539) -
从带有
timedelta64
数据类型的数据构建DatetimeIndex
已经被弃用,在将来的版本中会引发TypeError
(GH 23675) -
keep_tz=False
选项(默认值)的DatetimeIndex.to_series()
的keep_tz
关键字已经被弃用(GH 17832) -
时区转换一个带有时区信息的
datetime.datetime
或Timestamp
与Timestamp
和tz
参数现在已经被弃用。请使用Timestamp.tz_convert()
代替(GH 23579) -
pandas.api.types.is_period()
已被弃用,建议使用pandas.api.types.is_period_dtype
(GH 23917) -
pandas.api.types.is_datetimetz()
已被弃用,建议使用pandas.api.types.is_datetime64tz
(GH 23917) -
通过传递范围参数
start
、end
和periods
来创建TimedeltaIndex
、DatetimeIndex
或PeriodIndex
已被弃用,建议使用timedelta_range()
、date_range()
或period_range()
(GH 23919) -
将类似
'datetime64[ns, UTC]'
的字符串别名作为unit
参数传递给DatetimeTZDtype
已被弃用。请改用DatetimeTZDtype.construct_from_string
(GH 23990)。 -
infer_dtype()
的skipna
参数在 pandas 的将来版本中将默认切换为True
(GH 17066, GH 24050) -
在带有分类数据的
Series.where()
中,提供一个不在类别中的other
已被弃用。请先将分类转换为不同的 dtype 或首先将other
添加到类别中(GH 24077)。 -
Series.clip_lower()
、Series.clip_upper()
、DataFrame.clip_lower()
和DataFrame.clip_upper()
已被弃用,将在未来版本中移除。请使用Series.clip(lower=threshold)
、Series.clip(upper=threshold)
及其等效的DataFrame
方法(GH 24203) -
Series.nonzero()
已被弃用,将在未来版本中移除(GH 18262) -
将
timedelta64[ns]
dtypes 传递给Series.fillna()
和DataFrame.fillna()
已被弃用,将在未来版本中引发TypeError
。请改用obj.fillna(pd.Timedelta(...))
代替(GH 24694) -
Series.cat.categorical
、Series.cat.name
和Series.cat.index
已被弃用。请直接使用Series.cat
或Series
上的属性。(GH 24751)。 -
将没有精度的 dtype(如
np.dtype('datetime64')
或timedelta64
)传递给Index
、DatetimeIndex
和TimedeltaIndex
现已被弃用。请改用纳秒精度 dtype 代替(GH 24753)。
整数与日期时间和时间增量的加减法已被弃用
在过去,用户可以在某些情况下从Timestamp
、DatetimeIndex
和TimedeltaIndex
中添加或减去整数或整数类型的数组。
此用法现已被弃用。而是添加或减去对象的freq
属性的整数倍数(GH 21939,GH 23878)。
先前行为:
In [5]: ts = pd.Timestamp('1994-05-06 12:15:16', freq=pd.offsets.Hour())
In [6]: ts + 2
Out[6]: Timestamp('1994-05-06 14:15:16', freq='H')
In [7]: tdi = pd.timedelta_range('1D', periods=2)
In [8]: tdi - np.array([2, 1])
Out[8]: TimedeltaIndex(['-1 days', '1 days'], dtype='timedelta64[ns]', freq=None)
In [9]: dti = pd.date_range('2001-01-01', periods=2, freq='7D')
In [10]: dti + pd.Index([1, 2])
Out[10]: DatetimeIndex(['2001-01-08', '2001-01-22'], dtype='datetime64[ns]', freq=None)
新行为:
In [108]: ts = pd.Timestamp('1994-05-06 12:15:16', freq=pd.offsets.Hour())
In[109]: ts + 2 * ts.freq
Out[109]: Timestamp('1994-05-06 14:15:16', freq='H')
In [110]: tdi = pd.timedelta_range('1D', periods=2)
In [111]: tdi - np.array([2 * tdi.freq, 1 * tdi.freq])
Out[111]: TimedeltaIndex(['-1 days', '1 days'], dtype='timedelta64[ns]', freq=None)
In [112]: dti = pd.date_range('2001-01-01', periods=2, freq='7D')
In [113]: dti + pd.Index([1 * dti.freq, 2 * dti.freq])
Out[113]: DatetimeIndex(['2001-01-08', '2001-01-22'], dtype='datetime64[ns]', freq=None)
``` ### 将整数数据和时区传递给 DatetimeIndex
当传递整数数据和时区给`DatetimeIndex`时,pandas 未来版本中的行为将发生变化。以前,这些被解释为所需时区的墙上时间。未来,这些将被解释为 UTC 中的墙上时间,然后转换为所需时区([GH 24559](https://github.com/pandas-dev/pandas/issues/24559))。
默认行为保持不变,但会发出警告:
```py
In [3]: pd.DatetimeIndex([946684800000000000], tz="US/Central")
/bin/ipython:1: FutureWarning:
Passing integer-dtype data and a timezone to DatetimeIndex. Integer values
will be interpreted differently in a future version of pandas. Previously,
these were viewed as datetime64[ns] values representing the wall time
*in the specified timezone*. In the future, these will be viewed as
datetime64[ns] values representing the wall time *in UTC*. This is similar
to a nanosecond-precision UNIX epoch. To accept the future behavior, use
pd.to_datetime(integer_data, utc=True).tz_convert(tz)
To keep the previous behavior, use
pd.to_datetime(integer_data).tz_localize(tz)
#!/bin/python3
Out[3]: DatetimeIndex(['2000-01-01 00:00:00-06:00'], dtype='datetime64[ns, US/Central]', freq=None)
如警告消息所解释的,通过指定整数值为 UTC 并转换为最终时区来选择未来行为:
In [99]: pd.to_datetime([946684800000000000], utc=True).tz_convert('US/Central')
Out[99]: DatetimeIndex(['1999-12-31 18:00:00-06:00'], dtype='datetime64[ns, US/Central]', freq=None)
可以通过直接定位到最终时区来保留旧行为:
In [100]: pd.to_datetime([946684800000000000]).tz_localize('US/Central')
Out[100]: DatetimeIndex(['2000-01-01 00:00:00-06:00'], dtype='datetime64[ns, US/Central]', freq=None)
``` ### 将时区感知的 Series 和 Index 转换为 NumPy 数组
将 `Series` 或 `Index` 中的时区感知日期时间数据转换以默认方式来保留时区信息([GH 23569](https://github.com/pandas-dev/pandas/issues/23569))。
NumPy 没有专门用于时区感知日期时间的 dtype。在过去,将具有时区感知日期时间的 `Series` 或 `DatetimeIndex` 转换为 NumPy 数组的方法是通过
1. 将 tz-aware 数据转换为 UTC
1. 丢弃时区信息
1. 返回一个带有`datetime64[ns]` dtype 的[`numpy.ndarray`](https://numpy.org/doc/stable/reference/generated/numpy.ndarray.html#numpy.ndarray "(在 NumPy v1.26)")。
pandas 的将来版本将通过返回一个带有正确时区附加的 `Timestamp` 的对象 dtype NumPy 数组来保留时区信息
```py
In [101]: ser = pd.Series(pd.date_range('2000', periods=2, tz="CET"))
In [102]: ser
Out[102]:
0 2000-01-01 00:00:00+01:00
1 2000-01-02 00:00:00+01:00
Length: 2, dtype: datetime64[ns, CET]
默认行为保持不变,但会发出警告
In [8]: np.asarray(ser)
/bin/ipython:1: FutureWarning: Converting timezone-aware DatetimeArray to timezone-naive
ndarray with 'datetime64[ns]' dtype. In the future, this will return an ndarray
with 'object' dtype where each element is a 'pandas.Timestamp' with the correct 'tz'.
To accept the future behavior, pass 'dtype=object'.
To keep the old behavior, pass 'dtype="datetime64[ns]"'.
#!/bin/python3
Out[8]:
array(['1999-12-31T23:00:00.000000000', '2000-01-01T23:00:00.000000000'],
dtype='datetime64[ns]')
通过指定 dtype
,可以获取以前或将来的行为,而不会收到任何警告。
以前的行为
In [103]: np.asarray(ser, dtype='datetime64[ns]')
Out[103]:
array(['1999-12-31T23:00:00.000000000', '2000-01-01T23:00:00.000000000'],
dtype='datetime64[ns]')
将来的行为
# New behavior
In [104]: np.asarray(ser, dtype=object)
Out[104]:
array([Timestamp('2000-01-01 00:00:00+0100', tz='CET'),
Timestamp('2000-01-02 00:00:00+0100', tz='CET')], dtype=object)
或者使用 Series.to_numpy()
In [105]: ser.to_numpy()
Out[105]:
array([Timestamp('2000-01-01 00:00:00+0100', tz='CET'),
Timestamp('2000-01-02 00:00:00+0100', tz='CET')], dtype=object)
In [106]: ser.to_numpy(dtype="datetime64[ns]")
Out[106]:
array(['1999-12-31T23:00:00.000000000', '2000-01-01T23:00:00.000000000'],
dtype='datetime64[ns]')
所有以上内容同样适用于具有 tz-aware 值的 DatetimeIndex
。### 日期时间和时间增加/减法已弃用
在过去,用户可以——在某些情况下——从Timestamp
、DatetimeIndex
和TimedeltaIndex
中添加或减去整数或整数类型的数组。
此用法现已弃用。相反,应添加或减去对象的 freq
属性的整数倍数(GH 21939,GH 23878)。
以前的行为:
In [5]: ts = pd.Timestamp('1994-05-06 12:15:16', freq=pd.offsets.Hour())
In [6]: ts + 2
Out[6]: Timestamp('1994-05-06 14:15:16', freq='H')
In [7]: tdi = pd.timedelta_range('1D', periods=2)
In [8]: tdi - np.array([2, 1])
Out[8]: TimedeltaIndex(['-1 days', '1 days'], dtype='timedelta64[ns]', freq=None)
In [9]: dti = pd.date_range('2001-01-01', periods=2, freq='7D')
In [10]: dti + pd.Index([1, 2])
Out[10]: DatetimeIndex(['2001-01-08', '2001-01-22'], dtype='datetime64[ns]', freq=None)
新行为:
In [108]: ts = pd.Timestamp('1994-05-06 12:15:16', freq=pd.offsets.Hour())
In[109]: ts + 2 * ts.freq
Out[109]: Timestamp('1994-05-06 14:15:16', freq='H')
In [110]: tdi = pd.timedelta_range('1D', periods=2)
In [111]: tdi - np.array([2 * tdi.freq, 1 * tdi.freq])
Out[111]: TimedeltaIndex(['-1 days', '1 days'], dtype='timedelta64[ns]', freq=None)
In [112]: dti = pd.date_range('2001-01-01', periods=2, freq='7D')
In [113]: dti + pd.Index([1 * dti.freq, 2 * dti.freq])
Out[113]: DatetimeIndex(['2001-01-08', '2001-01-22'], dtype='datetime64[ns]', freq=None)
传递整数数据和时区给 DatetimeIndex
当传递整数数据和时区的DatetimeIndex
时,pandas 的将来版本中的行为正在发生变化。以前,这些被解释为所需时区的壁钟时间。将来,这些将被解释为 UTC 中的壁钟时间,然后转换为所需的时区(GH 24559)。
默认行为保持不变,但会发出警告:
In [3]: pd.DatetimeIndex([946684800000000000], tz="US/Central")
/bin/ipython:1: FutureWarning:
Passing integer-dtype data and a timezone to DatetimeIndex. Integer values
will be interpreted differently in a future version of pandas. Previously,
these were viewed as datetime64[ns] values representing the wall time
*in the specified timezone*. In the future, these will be viewed as
datetime64[ns] values representing the wall time *in UTC*. This is similar
to a nanosecond-precision UNIX epoch. To accept the future behavior, use
pd.to_datetime(integer_data, utc=True).tz_convert(tz)
To keep the previous behavior, use
pd.to_datetime(integer_data).tz_localize(tz)
#!/bin/python3
Out[3]: DatetimeIndex(['2000-01-01 00:00:00-06:00'], dtype='datetime64[ns, US/Central]', freq=None)
正如警告消息所解释的那样,通过指定整数值为 UTC 并将其转换为最终时区来选择未来行为:
In [99]: pd.to_datetime([946684800000000000], utc=True).tz_convert('US/Central')
Out[99]: DatetimeIndex(['1999-12-31 18:00:00-06:00'], dtype='datetime64[ns, US/Central]', freq=None)
可以通过直接定位到最终时区来保留旧行为:
In [100]: pd.to_datetime([946684800000000000]).tz_localize('US/Central')
Out[100]: DatetimeIndex(['2000-01-01 00:00:00-06:00'], dtype='datetime64[ns, US/Central]', freq=None)
将时区感知的 Series 和 Index 转换为 NumPy 数组
从具有时区感知的日期时间数据的 Series
或 Index
的转换将默认保留时区信息 (GH 23569)
NumPy 没有专门的 dtype 来处理时区感知的日期时间。在过去,将具有时区感知的日期时间的 Series
或 DatetimeIndex
转换为 NumPy 数组会通过
-
将时区感知数据转换为 UTC
-
删除时区信息
-
返回具有
datetime64[ns]
dtype 的numpy.ndarray
未来版本的 pandas 将通过返回一个对象 dtype 的 NumPy 数组来保留时区信息,其中每个值都是带有正确时区附加的 Timestamp
In [101]: ser = pd.Series(pd.date_range('2000', periods=2, tz="CET"))
In [102]: ser
Out[102]:
0 2000-01-01 00:00:00+01:00
1 2000-01-02 00:00:00+01:00
Length: 2, dtype: datetime64[ns, CET]
默认行为保持不变,但会发出警告
In [8]: np.asarray(ser)
/bin/ipython:1: FutureWarning: Converting timezone-aware DatetimeArray to timezone-naive
ndarray with 'datetime64[ns]' dtype. In the future, this will return an ndarray
with 'object' dtype where each element is a 'pandas.Timestamp' with the correct 'tz'.
To accept the future behavior, pass 'dtype=object'.
To keep the old behavior, pass 'dtype="datetime64[ns]"'.
#!/bin/python3
Out[8]:
array(['1999-12-31T23:00:00.000000000', '2000-01-01T23:00:00.000000000'],
dtype='datetime64[ns]')
可以通过指定 dtype
来获得先前或将来的行为,而不会收到任何警告
先前行为
In [103]: np.asarray(ser, dtype='datetime64[ns]')
Out[103]:
array(['1999-12-31T23:00:00.000000000', '2000-01-01T23:00:00.000000000'],
dtype='datetime64[ns]')
未来行为
# New behavior
In [104]: np.asarray(ser, dtype=object)
Out[104]:
array([Timestamp('2000-01-01 00:00:00+0100', tz='CET'),
Timestamp('2000-01-02 00:00:00+0100', tz='CET')], dtype=object)
或者使用 Series.to_numpy()
In [105]: ser.to_numpy()
Out[105]:
array([Timestamp('2000-01-01 00:00:00+0100', tz='CET'),
Timestamp('2000-01-02 00:00:00+0100', tz='CET')], dtype=object)
In [106]: ser.to_numpy(dtype="datetime64[ns]")
Out[106]:
array(['1999-12-31T23:00:00.000000000', '2000-01-01T23:00:00.000000000'],
dtype='datetime64[ns]')
所有上述内容同样适用于具有时区感知值的 DatetimeIndex
移除之前版本的弃用/更改
-
LongPanel
和WidePanel
类已被移除 (GH 10892) -
Series.repeat()
将reps
参数重命名为repeats
(GH 14645) -
几个私有函数从(非公开的)模块
pandas.core.common
中删除了 (GH 22001) -
传递给
DataFrame.groupby()
的字符串,既引用了列又引用了索引级别,将引发ValueError
(GH 14432) -
Index.repeat()
和MultiIndex.repeat()
现在将n
参数重命名为repeats
(GH 14645) -
构造函数
Series
和方法.astype
现在如果传入没有单位的时间戳 dtype(例如np.datetime64
)给dtype
参数,会抛出ValueError
异常(GH 15987) -
模块
pandas.types
、pandas.computation
和pandas.util.decorators
已被移除(GH 16157, GH 16250) -
移除了对
pandas.io.formats.style.Styler
的pandas.formats.style
的替代(GH 16059) -
pandas.pnow
、pandas.match
、pandas.groupby
、pd.get_store
、pd.Expr
和pd.Term
已被移除(GH 15538, GH 15940) -
Categorical.searchsorted()
和Series.searchsorted()
现在将v
参数重命名为value
(GH 14645) -
pandas.parser
、pandas.lib
和pandas.tslib
已被移除(GH 15537) -
Index.searchsorted()
现在将key
参数重命名为value
(GH 14645) -
DataFrame.consolidate
和Series.consolidate
已被移除(GH 15501) -
移除了先前废弃的模块
pandas.json
(GH 19944) -
SparseArray.get_values()
和SparseArray.to_dense()
已删除fill
参数(GH 14686) -
DataFrame.sortlevel
和Series.sortlevel
已被移除(GH 15099) -
SparseSeries.to_dense()
已删除sparse_only
参数(GH 14686) -
DataFrame.astype()
和Series.astype()
已将raise_on_error
参数重命名���errors
(GH 14967) -
is_sequence
、is_any_int_dtype
和is_floating_dtype
已从pandas.api.types
中移除(GH 16163, GH 16189)
性能改进
-
使用单调递增的
CategoricalIndex
对 Series 和 DataFrames 进行切片现在非常快速,并且速度与使用Int64Index
进行切片相当。在按标签索引(使用.loc)和位置索引(.iloc)时,速度都有所提高(GH 20395) 对单调递增的CategoricalIndex
本身进行切片(即ci[1000:2000]
)显示出与上述类似的速度改进(GH 21659) -
改进了
CategoricalIndex.equals()
在与另一个CategoricalIndex
比较时的性能(GH 24023) -
改进了
Series.describe()
在数值数据类型的情况下的性能(GH 21274) -
处理并列排名时,改进了
GroupBy.rank()
的性能(GH 21237) -
改进了
DataFrame.set_index()
在由Period
对象组成的列上的性能(GH 21582, GH 21606) -
改进了
Series.at()
和Index.get_value()
在扩展数组值(例如Categorical
)上的性能(GH 24204) -
改进了在
Categorical
和CategoricalIndex
中的成员检查的性能(即x in cat
形式的检查更快)。CategoricalIndex.contains()
同样更快了(GH 21369, GH 21508) -
改进了
HDFStore.groups()
(以及类似HDFStore.keys()
的依赖函数的性能(即x in store
检查更快了)(GH 21372) -
改进了带有
sparse=True
参数的pandas.get_dummies()
的性能(GH 21997) -
改进了对已排序、非唯一索引的
IndexEngine.get_indexer_non_unique()
的性能(GH 9466) -
改进了
PeriodIndex.unique()
的性能(GH 23083) -
改进了对
Series
对象的concat()
的性能(GH 23404) -
改进了对时区无关或 UTC 日期时间的
DatetimeIndex.normalize()
和Timestamp.normalize()
的性能(GH 23634) -
改进了带有 dateutil UTC 时区的
DatetimeIndex.tz_localize()
和各种DatetimeIndex
属性的性能(GH 23772) -
修复了 Windows 上 Python 3.7 版本的
read_csv()
的性能回归问题(GH 23516) -
改进了对
Series
对象的Categorical
构造器的性能(GH 23814) -
改进了对分类数据的
where()
的性能(GH 24077) -
改进了迭代
Series
的性能。现在使用DataFrame.itertuples()
创建迭代器时不再内部分配所有元素的列表(GH 20783) -
改进了
Period
构造函数的性能,同时也有益于PeriodArray
和PeriodIndex
的创建(GH 24084,GH 24118) -
提高了带时区感知的
DatetimeArray
二进制操作的性能(GH 24491)
问题修复
Categorical
-
Categorical.from_codes()
存在错误,codes
中的NaN
值会被静默转换为0
(GH 21767)。将来会引发ValueError
。还更改了.from_codes([1.1, 2.0])
的行为。 -
Categorical.sort_values()
中存在错误,无论na_position
值如何,NaN
值总是位于前面。(GH 22556)。 -
使用布尔值
Categorical
进行索引时存在错误。现在将布尔值Categorical
视为布尔掩码处理(GH 22665) -
使用空值和布尔类别构建
CategoricalIndex
在 dtype 强制转换更改后会引发ValueError
(GH 22702)。 -
Categorical.take()
中存在错误,使用用户提供的fill_value
不会对fill_value
进行编码,这可能导致ValueError
、不正确的结果或段错误(GH 23296)。 -
在
Series.unstack()
中,指定一个不存在于类别中的fill_value
现在会引发TypeError
,而不是忽略fill_value
(GH 23284) -
当在分类数据上重新采样
DataFrame.resample()
并聚合时,分类 dtype 会丢失。(GH 23227) -
多种方法中的
.str
访问器存在错误,调用CategoricalIndex.str
构造函数总是失败(GH 23555,GH 23556) -
Series.where()
中的一个 bug,对分类数据丢失了分类 dtype(GH 24077) -
Categorical.apply()
中的一个 bug,NaN
值可能会被不可预测地处理。现在它们保持不变(GH 24241) -
Categorical
比较方法中的一个 bug,在与DataFrame
进行操作时错误地引发ValueError
(GH 24630) -
Categorical.set_categories()
中的一个 bug,使用rename=True
设置较少的新类别导致段错误(GH 24675)
Datetimelike
-
修复了两个具有不同
normalize
属性的DateOffset
对象可能被评估为相等的 bug(GH 21404) -
修复了
Timestamp.resolution()
错误地返回 1 微秒timedelta
而不是 1 纳秒Timedelta
的 bug(GH 21336, GH 21365) -
to_datetime()
中的一个 bug,当指定box=True
时未始终返回一个Index
(GH 21864) -
DatetimeIndex
比较中的一个 bug,字符串比较错误地引发TypeError
(GH 22074) -
DatetimeIndex
比较中的一个 bug,与timedelta64[ns]
数据类型数组进行比较时;在某些情况下错误地引发TypeError
,在其他情况下错误地未引发(GH 22074) -
DatetimeIndex
比较中的一个 bug,与对象数据类型数组进行比较时(GH 22074) -
DataFrame
中的一个 bug,datetime64[ns]
类型的加减与Timedelta
类似对象时出现问题(GH 22005, GH 22163) -
DataFrame
中datetime64[ns]
类型的 Bug 在使用DateOffset
对象进行加减法时返回object
类型,而不是datetime64[ns]
类型(GH 21610,GH 22163) -
DataFrame
中datetime64[ns]
类型的 Bug 在与NaT
进行比较时错误地返回(GH 22242,GH 22163) -
DataFrame
中datetime64[ns]
类型的 Bug 在减去Timestamp
类对象时错误地返回datetime64[ns]
类型,而不是timedelta64[ns]
类型(GH 8554,GH 22163) -
DataFrame
中datetime64[ns]
类型的 Bug 在减去具有非纳秒单位的np.datetime64
对象时未能转换为纳秒单位(GH 18874,GH 22163) -
DataFrame
中与Timestamp
类对象进行比较的 Bug 未能对类型不匹配的不等式检查引发TypeError
(GH 8932,GH 22163) -
DataFrame
中包含混合类型(包括datetime64[ns]
)的 Bug 在进行相等比较时错误地引发TypeError
(GH 13128,GH 22163) -
DataFrame.values
中的 Bug 在具有带时区的日期时间值的单列DataFrame
上返回一个DatetimeIndex
。现在返回一个由Timestamp
对象组成的二维numpy.ndarray
(在 NumPy v1.26 中)(GH 24024) -
DataFrame.eq()
中的 Bug 在与NaT
进行比较时错误地返回True
或NaN
(GH 15697,GH 22163) -
DatetimeIndex
减法存在错误,错误地未能引发OverflowError
(GH 22492, GH 22508)。 -
DatetimeIndex
存在错误,错误地允许使用Timedelta
对象进行索引(GH 20464)。 -
DatetimeIndex
存在错误,如果原始频率为None
,则设置了频率(GH 22150)。 -
DatetimeIndex
的四舍五入方法(round()
,ceil()
,floor()
)和Timestamp
的四舍五入方法(round()
,ceil()
,floor()
)可能导致精度丢失(GH 22591)。 -
to_datetime()
存在错误,使用Index
参数时,会丢失结果的name
(GH 21697)。 -
PeriodIndex
存在错误,在添加或减去timedelta
或Tick
对象时产生不正确的结果(GH 22988)。 -
Series
的 repr 中存在错误,周期类型数据在数据之前缺少一个空格(GH 23601)。 -
date_range()
出现错误,当将起始日期递减到过去的结束日期时,使用负频率(GH 23270)。 -
Bug in
Series.min()
,当在NaT
系列上调用时,会返回NaN
而不是NaT
(GH 23282) -
Bug in
Series.combine_first()
,未正确对齐分类变量,导致self
中的缺失值未被other
中的有效值填充(GH 24147) -
Bug in
DataFrame.combine()
,具有日期时间值时会引发 TypeError 错误(GH 23079) -
Bug in
date_range()
,当频率为Day
或更高时,未来足够远的日期可能会回到过去,而不是引发OutOfBoundsDatetime
错误(GH 14187) -
Bug in
period_range()
,当提供start
和end
作为Period
对象时,会忽略频率(GH 20535) -
Bug in
PeriodIndex
,当属性freq.n
大于 1 时,添加DateOffset
对象会返回不正确的结果(GH 23215) -
Bug in
Series
,在设置类似日期时间的值时,将字符串索引解释为字符列表(GH 23451) -
Bug in
DataFrame
,从带有时区的Timestamp
对象的 ndarray 创建新列时,会创建一个对象 dtype 列,而不是带有时区的 datetime 列(GH 23932) -
Bug in
Timestamp
构造函数,会丢弃输入Timestamp
的频率(GH 22311) -
Bug in
DatetimeIndex
,调用np.array(dtindex, dtype=object)
会错误地返回一个long
对象数组(GH 23524) -
在
Index
中存在一个错误,当传递一个带有时区信息的DatetimeIndex
和dtype=object
时,会错误地引发ValueError
(GH 23524) -
在
Index
中存在一个错误,当对一个没有时区信息的DatetimeIndex
调用np.array(dtindex, dtype=object)
时,会返回一个datetime
对象数组而不是Timestamp
对象数组,可能会丢失时间戳的纳秒部分(GH 23524) -
Categorical.__setitem__
中存在一个错误,当两者都是无序的且具有相同的类别但顺序不同的Categorical
时,不允许使用另一个Categorical
进行设置(GH 24142) -
在
date_range()
中存在一个错误,使用毫秒或更高分辨率的日期可能会返回不正确的值或索引中的值数量不正确(GH 24110) -
在
DatetimeIndex
中存在一个错误,从Categorical
或CategoricalIndex
构造一个DatetimeIndex
会错误地丢失时区信息(GH 18664) -
在
DatetimeIndex
和TimedeltaIndex
中存在一个错误,使用Ellipsis
进行索引会错误地丢失索引的freq
属性(GH 21282) -
当将错误的
freq
参数传递给DatetimeIndex
并且在传递的数据中将NaT
作为第一个条目时,会产生明确的错误消息(GH 11587) -
在
to_datetime()
中存在一个错误,当传递一个DataFrame
或单位映射的dict
时,会忽略box
和utc
参数(GH 23760) -
Series.dt
中的一个错误,其中缓存在原地操作后不会正确更新 (GH 24408) -
PeriodIndex
中的一个错误,与长度为 1 的类似数组对象进行比较时未能引发ValueError
(GH 23078) -
DatetimeIndex.astype()
、PeriodIndex.astype()
和TimedeltaIndex.astype()
中的一个错误,忽略了无符号整数 dtype 的符号 (GH 24405) -
修复了在具有
datetime64[ns]
-dtype 时的Series.max()
中的错误,当存在空值且传递了skipna=False
时未能返回NaT
(GH 24265) -
to_datetime()
中的一个错误,其中包含既包含时区感知又包含时区无关的datetime
对象数组会导致未能引发ValueError
(GH 24569) -
在无效的日期时间格式的
to_datetime()
中,即使errors='coerce'
,也不会强制将输入转换为NaT
(GH 24763)
时间差
-
具有
timedelta64[ns]
dtype 的DataFrame
通过Timedelta
-like 标量进行除法时,错误地返回timedelta64[ns]
dtype 而不是float64
dtype (GH 20088, GH 22163) -
将带有对象 dtype 的
Index
添加到具有timedelta64[ns]
dtype 的Series
时,错误地引发 (GH 22390) -
将具有数值 dtype 的
Series
与timedelta
对象相乘时出现错误 (GH 22390) -
具有数值 dtype 的
Series
在将数组或具有timedelta64
dtype 的Series
添加或减去时出现错误 (GH 22390) -
对具有数值 dtype 的
Index
进行乘法或除法运算时,如果数组具有timedelta64
dtype,则引发错误 (GH 22390) -
TimedeltaIndex
中的错误,错误地允许使用Timestamp
对象进行索引(GH 20464) -
修复了从对象类型数组中减去
Timedelta
会引发TypeError
的错误(GH 21980) -
修复了将所有-timedelta64[ns]数据类型的
DataFrame
添加到所有整数数据类型的DataFrame
中返回不正确结果而不是引发TypeError
的错误(GH 22696) -
TimedeltaIndex
中的错误,添加时区感知的日期时间标量会错误地返回时区无关的DatetimeIndex
(GH 23215) -
TimedeltaIndex
中的错误,添加np.timedelta64('NaT')
错误地返回全部为NaT
的DatetimeIndex
而不是全部为NaT
的TimedeltaIndex
(GH 23215) -
Timedelta
和to_timedelta()
中的错误,在支持的单位字符串上存在不一致性(GH 21762) -
TimedeltaIndex
的除法错误,除以另一个TimedeltaIndex
会引发TypeError
而不是返回Float64Index
(GH 23829, GH 22631) -
TimedeltaIndex
比较操作的错误,与非Timedelta
类型对象进行比较会引发TypeError
,而不是对于__eq__
返回全部False
和对于__ne__
返回全部True
(GH 24056) -
在与
Tick
对象比较时,Timedelta
比较存在 bug,错误地引发TypeError
(GH 24710)
时区
-
Index.shift()
存在一个 bug,在跨越 DST 时会引发AssertionError
(GH 8616) -
在构造函数中传递无效的时区偏移标识符 (
Z
) 时会导致不会引发ValueError
的 bug (GH 8910) -
Timestamp.replace()
存在一个 bug,在 DST 边界替换时会保留一个不正确的偏移量(GH 7825) -
Series.replace()
存在一个 bug,在替换NaT
时会有datetime64[ns, tz]
数据的问题(GH 11792) -
在传递带有不同字符串日期格式和时区偏移量的
Timestamp
时存在一个 bug,会产生不同的时区偏移量 (GH 12064) -
在比较不带时区的
Timestamp
和带时区的DatetimeIndex
时存在一个 bug,会将DatetimeIndex
强制转换为不带时区的 (GH 12601) -
Series.truncate()
在具有时区信息的DatetimeIndex
上存在一个 bug,可能导致核心转储 (GH 9243) -
Series
构造函数存在一个 bug,会强制将带有时区信息和不带时区信息的Timestamp
转换为带有时区信息的 (GH 13051) -
Index
存在一个 bug,在datetime64[ns, tz]
dtype 上未能正确本地化整数数据 (GH 20964) -
在使用整数和时区构造时
DatetimeIndex
未能正确地进行本地化 (GH 12619) -
修复了当时区感知日期时间上的
DataFrame.describe()
和Series.describe()
未显示first
和last
结果时的 bug (GH 21328) -
在比较时区感知的
DatetimeIndex
和np.datetime64
时未能引发TypeError
的 bug (GH 22074) -
在带有时区感知标量的
DataFrame
赋值时出现 bug (GH 19843) -
在尝试比较时区感知和非时区感知时间戳时,
DataFrame.asof()
引发TypeError
的 bug (GH 21194) -
在使用
replace
方法跨 DST 构造DatetimeIndex
时出现 bug,带有Timestamp
(GH 18785) -
用
DataFrame.loc()
设置新值时出现 bug,带有DatetimeIndex
并带有 DST 转换 (GH 18308, GH 20724) -
Index.unique()
中存在的 bug,未正确重新本地化时区感知日期 (GH 21737) -
用带有 DST 转换的
Series
索引时出现 bug (GH 21846) -
在
DataFrame.resample()
和Series.resample()
中出现 bug,如果带有时区感知的时间序列在 DST 转换上结束,则会引发AmbiguousTimeError
或NonExistentTimeError
(GH 19375, GH 10117) -
当从带有 DST 转换的
DatetimeIndex
中删除一个带有时区的 Timestamp 键时,在DataFrame.drop()
和Series.drop()
中的错误 (GH 21761) -
构造函数
DatetimeIndex
中的错误,其中NaT
和dateutil.tz.tzlocal
会引发OutOfBoundsDatetime
错误(GH 23807) -
在靠近 DST 转换的
dateutil.tz.tzlocal
时的DatetimeIndex.tz_localize()
和Timestamp.tz_localize()
中返回不正确本地化的日期时间的错误 (GH 23807) -
当使用
datetime.datetime
参数传递dateutil.tz.tzutc
时,Timestamp
构造函数会将其转换为pytz.UTC
时区 (GH 23807) -
当指定
utc=True
时,在指定unit
和errors='ignore'
时,to_datetime()
不会被尊重 (GH 23758) -
当传递
Timestamp
时,to_datetime()
中的utc=True
不会被尊重 (GH 24415) -
当
axis=1
且数据是 datetimelike 类型时,DataFrame.any()
返回错误的值 (GH 23070) -
在将时区感知索引首先转换为 UTC 然后创建
PeriodIndex
时的DatetimeIndex.to_period()
中的错误 (GH 22905) -
在
DataFrame.tz_localize()
、DataFrame.tz_convert()
、Series.tz_localize()
和Series.tz_convert()
中存在 Bug,copy=False
会在原始参数上进行原地更改(GH 6326) -
DataFrame.max()
和DataFrame.min()
在axis=1
的情况下存在 Bug,当所有列都包含相同的时区时,会返回一个带有NaN
的Series
(GH 10390)
偏移
-
在
FY5253
中存在 Bug,日期偏移可能在算术运算中不正确地引发AssertionError
(GH 14774) -
DateOffset
中的 Bug,接受并忽略了关键字参数week
和milliseconds
。现在传递这些参数将会引发ValueError
(GH 19398) -
添加
DateOffset
时存在 Bug,DataFrame
或PeriodIndex
不正确地引发TypeError
(GH 23215) -
比较
DateOffset
对象与非DateOffset
对象(特别是字符串)时存在 Bug,不是为相等检查返回False
,而是引发ValueError
,而不是为不相等检查返回True
(GH 23524)
数值
-
在
Series
中存在 Bug,__rmatmul__
不支持矩阵向量乘法(GH 21530) -
factorize()
中存在 Bug,无法处理只读数组(GH 12813) -
在
unique()
中修复了 Bug,不一致地处理了带符号的零:对于某些输入,0.0 和 -0.0 被视为相等,而对于某些输入,它们被视为不同。现在,它们在所有输入中都被视为相等(GH 21866) -
Bug in
DataFrame.agg()
,DataFrame.transform()
andDataFrame.apply()
where, when supplied with a list of functions andaxis=1
(e.g.df.apply(['sum', 'mean'], axis=1)
), aTypeError
was wrongly raised. For all three methods such calculation are now done correctly. (GH 16679). -
Bug in
Series
comparison against datetime-like scalars and arrays (GH 22074) -
Bug in
DataFrame
multiplication between boolean dtype and integer returningobject
dtype instead of integer dtype (GH 22047, GH 22163) -
Bug in
DataFrame.apply()
where, when supplied with a string argument and additional positional or keyword arguments (e.g.df.apply('sum', min_count=1)
), aTypeError
was wrongly raised (GH 22376) -
Bug in
DataFrame.astype()
to extension dtype may raiseAttributeError
(GH 22578) -
Bug in
DataFrame
withtimedelta64[ns]
dtype arithmetic operations withndarray
with integer dtype incorrectly treating the narray astimedelta64[ns]
dtype (GH 23114) -
Bug in
Series.rpow()
with object dtypeNaN
for1 ** NA
instead of1
(GH 22922). -
Series.agg()
can now handle numpy NaN-aware methods likenumpy.nansum()
(GH 19629) -
Bug in
Series.rank()
andDataFrame.rank()
whenpct=True
and more than 2²⁴ rows are present resulted in percentages greater than 1.0 (GH 18271) -
调用类似
DataFrame.round()
的方法,使用非唯一的CategoricalIndex()
,现在返回预期的数据。以前,数据会不正确地重复(GH 21809)。 -
在
DataFrame.eval()
的支持函数列表中添加了log10
、floor
和ceil
(GH 24139,GH 24353) -
逻辑操作
&、|、^
在Series
和Index
之间不再引发ValueError
(GH 22092) -
在
is_scalar()
函数中检查 PEP 3141 数字返回True
(GH 22903) -
像
Series.sum()
这样的减少方法现在在从 NumPy ufunc 调用时接受keepdims=False
的默认值,而不是引发TypeError
。尚未实现对keepdims
的全面支持(GH 24356)。
转换
-
在
DataFrame.combine_first()
中,列类型意外地转换为浮点型(GH 20699) -
在
DataFrame.clip()
中,列类型不会被保留,并转换为浮点型(GH 24162) -
在
DataFrame.clip()
中,当数据框的列顺序不匹配时,观察到的结果在数值上是错误的(GH 20911) -
DataFrame.astype()
中的错误,在存在重复列名时转换为扩展 dtype 会导致RecursionError
(GH 24704)
字符串
-
Index.str.partition()
中的错误不安全,会导致 nan 问题(GH 23558)。 -
Index.str.split()
中的错误不安全,会导致 nan 问题(GH 23677)。 -
Series.str.contains()
中的错误,对于Categorical
类型的Series
,na
参数不被尊重(GH 22158) -
Index.str.cat()
中的错误,当结果只包含NaN
时(GH 24044)
区间
-
IntervalIndex
构造函数中的错误,closed
参数并不总是覆盖推断的closed
(GH 19370) -
IntervalIndex
中的错误,区间列表后缺少逗号(GH 20611) -
Interval
中的错误,标量算术操作未保留closed
值(GH 22313) -
IntervalIndex
中的错误,使用类似日期时间的值进行索引会引发KeyError
(GH 20636) -
IntervalTree
中的错误,包含NaN
的数据会触发警告,并导致使用IntervalIndex
进行不正确的索引查询(GH 23352)
索引
-
DataFrame.ne()
中的错误,如果列包含列名“dtype”则会失败(GH 22383) -
当使用
.loc
请求单个缺失标签时,KeyError
的回溯现在更短更清晰(GH 21557) -
当查找到格式不正确的字符串时,
PeriodIndex
现在会引发KeyError
,这与DatetimeIndex
的行为一致(GH 22803) -
当在具有整数类型第一级的
MultiIndex
中请求缺失的整数标签时,.ix
现在会引发KeyError
,与平坦的Int64Index
的情况一致,而不是回退到位置索引(GH 21593) -
在重新索引一个时区无关和时区感知的
DatetimeIndex
时,在Index.reindex()
中存在错误 (GH 8306) -
在使用
datetime64[ns, tz]
类型的空系列重新索引时,在Series.reindex()
中存在错误 (GH 20869) -
在使用
.loc
和具有时区感知的DatetimeIndex
设置值时,DataFrame
中存在错误 (GH 11365) -
DataFrame.__getitem__
现在接受字典和字典键作为标签的列表,与Series.__getitem__
保持一致 (GH 21294) -
修复了当列不唯一时的
DataFrame[np.nan]
(GH 21428) -
在具有纳秒分辨率日期和时区的
DatetimeIndex
上进行索引时存在错误 (GH 11679) -
当使用包含负值的 Numpy 数组进行索引时,存在索引器变异的错误 (GH 21867)
-
混合索引不允许整数用于
.at
的错误 (GH 19860) -
当布尔键传递时,
Float64Index.get_loc
现在会引发KeyError
。 (GH 19087) -
在使用
IntervalIndex
进行索引时,DataFrame.loc()
中存在错误 (GH 19977) -
Index
不再混淆None
、NaN
和NaT
,即它们被视为三个不同的键。但是,对于数值索引,这三者仍然被强制转换为NaN
(GH 22332) -
如果标量是浮点数,而
Index
是整数类型,则scalar in Index
中存在错误 (GH 22085) -
当 levels 值不可索引时,在
MultiIndex.set_levels()
中存在错误 (GH 23273) -
设置时间差列为
Index
时会被强制转换为双精度浮点数,从而丢失精度的 bug (GH 23511) -
在某些情况下,
Index.union()
和Index.intersection()
的结果的Index
的名称计算不正确的 bug (GH 9943, GH 9862) -
使用布尔值
Index
进行切片可能会引发TypeError
的 bug (GH 22533) -
在接受切片和类列表值时的
PeriodArray.__setitem__
的 bug (GH 23978) -
DatetimeIndex
和TimedeltaIndex
中使用Ellipsis
进行索引会丢失freq
属性的 bug (GH 21282) -
使用
iat
进行赋值时,如果值不兼容会创建一个新列的 bug (GH 23236)
缺失
-
DataFrame.fillna()
存在 bug,当某一列包含datetime64[ns, tz]
类型时会引发ValueError
(GH 15522) -
Series.hasnans()
中的 bug,如果在初始调用后引入空元素,可能会错误地缓存并返回错误的答案 (GH 19700) -
Series.isin()
现在也对于np.object_
类型的值将所有 NaN 浮点数视为相等。这个行为与 float64 的行为一致 (GH 22119) -
unique()
不再对 NaN 浮点数和NaT
对象进行修改,对于np.object_
类型的值,即NaT
不再强制转换为 NaN 值,并且被视为不同的实体。(GH 22295) -
DataFrame
和Series
现在可以正确处理带有硬化掩码的 numpy 掩码数组。以前,从带有硬化掩码的掩码数组构造 DataFrame 或 Series 将创建包含底层值而不是预期的 NaN 的 pandas 对象。 (GH 24574) -
DataFrame
构造函数中的 Bug,处理 numpy 掩码记录数组时未遵守dtype
参数。 (GH 24874)
多重索引
-
io.formats.style.Styler.applymap()
中的 Bug,其中使用MultiIndex
切片的subset=
会缩减为Series
(GH 19861) -
删除对版本 0.8.0 之前的
MultiIndex
pickles 的兼容性;与版本 0.13 及以后的MultiIndex
pickles 的兼容性保持不变 (GH 21654) -
MultiIndex.get_loc_level()
(以及因此,在具有MultiIndex
索引的Series
或DataFrame
上的.loc
)现在将引发KeyError
,而不是返回空slice
,如果询问存在于levels
中但未使用的标签 (GH 22221) -
MultiIndex
现在具有MultiIndex.from_frame()
,它允许从DataFrame
构造一个MultiIndex
对象 (GH 22420) -
修复 Python 3 中创建
MultiIndex
时的TypeError
,其中某些级别具有混合类型,例如当某些标签是元组时 (GH 15457)
IO
-
当将布尔类别的
CategoricalDtype
列指定为字符串值到布尔值时,read_csv()
中存在错误,未能正确地将其强制转换为布尔值(GH 20498)。 -
在 Python 2.x 中,
read_csv()
中未能正确识别 Unicode 列名的错误(GH 13253)。 -
当写入时区感知数据(
datetime64[ns, tz]
类型)时,DataFrame.to_sql()
存在错误会引发TypeError
(GH 9086)。 -
当写入具有错误
DatetimeIndex
的数据时,例如在受支持的数据库(如 PostgreSQL)中,DataFrame.to_sql()
中存在错误,将被写入为TIMESTAMP WITH TIMEZONE
类型(GH 23510)。 -
当在空数据集中指定
parse_cols
时,read_excel()
存在错误(GH 9208)。 -
当考虑
skiprows
和header
参数时,read_html()
不再忽略<thead>
中的所有空白<tr>
。 之前,用户必须减少这些表上的header
和skiprows
值以解决此问题(GH 21641)。 -
read_excel()
将正确显示先前已弃用的sheetname
的弃用警告(GH 17994)。 -
在坏编码的字符串上读取数据时,
read_csv()
和read_table()
将抛出UnicodeError
而不会造成核心转储(GH 22748)。 -
read_csv()
将正确解析时区感知的日期时间(GH 22256)。 -
当数据被分块读取时,在 C 引擎中对内存管理进行了过早的优化,导致
read_csv()
中存在错误(GH 23509)。 -
在提取多重索引时,
read_csv()
中存在 bug,未命名的列被错误地识别。(GH 23687) -
read_sas()
将正确解析宽度小于 8 字节的 sas7bdat 文件中的数字。(GH 21616) -
read_sas()
将正确解析具有许多列的 sas7bdat 文件。(GH 22628) -
read_sas()
将正确解析数据页类型为 128 + 256 = 384 的 sas7bdat 文件。(GH 16615) -
在
read_sas()
中存在 bug,当文件格式无效时会引发错误。(GH 24548) -
在
detect_client_encoding()
中存在 bug,在 mod_wsgi 进程中导入时,由于对标准输出的访问受限,潜在的IOError
未被处理。(GH 21552) -
在具有
index=False
的情况下,DataFrame.to_html()
存在 bug,在截断的 DataFrame 上未显示截断指示符(…)。(GH 15019, GH 22783) -
在具有
index=False
的情况下,DataFrame.to_html()
存在 bug,当列和行索引都是MultiIndex
时,无法正确识别。(GH 22579) -
在具有
index_names=False
的情况下,DataFrame.to_html()
存在 bug,显示索引名称。(GH 22747) -
在具有
header=False
的情况下,DataFrame.to_html()
存在 bug,不显示行索引名称。(GH 23788) -
在具有
sparsify=False
的情况下,DataFrame.to_html()
存在 bug,导致它引发TypeError
。(GH 22887) -
内联代码
DataFrame.to_string()
中的错误导致列对齐在index=False
且第一列的值的宽度大于第一列标题的宽度时出现问题(GH 16839, GH 13032) -
内联代码
DataFrame.to_string()
中的错误导致DataFrame
的表示未占据整个窗口(GH 22984) -
DataFrame.to_csv()
中的错误,单级 MultiIndex 不正确地写入了一个元组。现在只写入索引的值(GH 19589). -
当
format
kwarg 传递给构造函数时,HDFStore
会引发ValueError
(GH 13291) -
在追加一个带有空字符串列和
min_itemsize
< 8 的DataFrame
时,HDFStore.append()
中的错误(GH 12242) -
read_csv()
中的错误,在解析NaN
值时发生内存泄漏,原因是在完成或出现错误时清理不足(GH 21353) -
在传递
skipfooter
时,read_csv()
中的错误消息不正确地引发了nrows
,iterator
或chunksize
(GH 23711) -
在
MultiIndex
索引名称未提供时,read_csv()
中错误地处理了它们(GH 23484) -
在方言的值与默认参数发生冲突时,
read_csv()
中不必要的警告被引发(GH 23761) -
在提供无效参数时,
read_html()
中的错误消息未显示有效的参数选择(GH 23549) -
read_excel()
存在一个 Bug,在这个 Bug 中,即使没有指定,也会提取多余的标题名 (GH 11733) -
read_excel()
存在一个 Bug,在这个 Bug 中,有时列名没有被正确转换为字符串,特别是在 Python 2.x 中 (GH 23874) -
read_excel()
存在一个 Bug,在这个 Bug 中,index_col=None
没有被尊重,并且仍然解析索引列 (GH 18792, GH 20480) -
read_excel()
存在一个 Bug,在这个 Bug 中,当作为字符串传入时,usecols
没有被验证为正确的列名 (GH 20480) -
DataFrame.to_dict()
存在一个 Bug,当结果字典包含非 Python 标量时,会出现问题,特别是在数值数据的情况下 (GH 23753) -
DataFrame.to_string()
、DataFrame.to_html()
、DataFrame.to_latex()
当传递字符串作为float_format
参数时,将正确格式化输出 (GH 21625, GH 22270) -
read_csv()
存在一个 Bug,当尝试将 ‘inf’ 作为na_value
与整数索引列一起使用时,会引发OverflowError
(GH 17128) -
read_csv()
存在一个 Bug,导致 C 引擎在 Python 3.6+ 的 Windows 上无法正确读取带有重音符号或特殊字符的 CSV 文件名 (GH 15086) -
read_fwf()
存在一个 Bug,文件的压缩类型没有被正确推断 (GH 22199) -
pandas.io.json.json_normalize()
存在一个 Bug,导致在record_path
的两个连续元素是字典时会引发TypeError
(GH 22706) -
在
DataFrame.to_stata()
、pandas.io.stata.StataWriter
和pandas.io.stata.StataWriter117
中存在的错误,即异常将导致部分写入且无效的 dta 文件(GH 23573) -
在使用带有非 ASCII 字符的 strLs 时,在
DataFrame.to_stata()
和pandas.io.stata.StataWriter117
中产生无效文件的错误(GH 23573) -
在 Python 3 中从 Python 2 中写入的固定格式中读取 Dataframe 时,导致
ValueError
的HDFStore
中存在的错误(GH 24510) -
在
DataFrame.to_string()
和浮点repr
格式化器中存在的错误。如果inf
存在于列中,则零将不会被修剪,而在存在 NA 值时则会被修剪。现在在存在 NA 时也会修剪零(GH 24861) -
在截断列数并且最后一列宽度较宽时,
repr
中存在的错误(GH 24849)
绘图
-
在 IPython 内联后端中启用颜色条时,导致 x 轴标签和刻度标签消失的
DataFrame.plot.scatter()
和DataFrame.plot.hexbin()
中存在的错误(GH 10611、GH 10678和GH 20455) -
使用
matplotlib.axes.Axes.scatter()
绘制具有日期时间的序列时出现的错误(GH 22039) -
在使用
DataFrame.plot.bar()
时出现的错误,导致柱形图使用多种颜色而不是单一颜色(GH 20585) -
在验证颜色参数时出现的错误,导致额外的颜色被追加到给定的颜色数组中。这发生在使用 matplotlib 的多个绘图函数中(GH 20726)
分组/重采样/滚动
-
在
Rolling.min()
和Rolling.max()
中使用closed='left'
,具有类似日期时间的索引且系列中仅有一个条目时导致段错误的错误(GH 24718) -
在
GroupBy.first()
和GroupBy.last()
中存在一个 bug,当as_index=False
时,会导致时区信息丢失 (GH 15884) -
在跨越 DST 边界下采样时,
DateFrame.resample()
存在一个 bug (GH 8531) -
在使用偏移量
Day
时,DateFrame.resample()
中日期定位存在一个 bug,当 n > 1 时 (GH 24127) -
当调用
SeriesGroupBy
的count()
方法时,如果分组变量只包含 NaN 并且 numpy 版本 < 1.13,则错误地引发ValueError
(GH 21956). -
在
Rolling.min()
中存在多个 bug,使用closed='left'
和 datetime-like 索引会导致错误的结果,并且可能会崩溃。 (GH 21704) -
在
Resampler.apply()
中存在一个 bug,当将位置参数传递给应用的函数时 (GH 14615). -
在
Series.resample()
中存在一个 bug,当将numpy.timedelta64
传递给loffset
kwarg 时 (GH 7687). -
当
TimedeltaIndex
的频率是新频率的子周期时,在Resampler.asfreq()
中存在一个 bug (GH 13022). -
当值是整数但无法适应 int64 时,
SeriesGroupBy.mean()
中存在一个 bug,会溢出。 (GH 22487) -
RollingGroupby.agg()
和ExpandingGroupby.agg()
现在支持多个聚合函数作为参数 (GH 15072) -
在按周偏移 (
'W'
) 跨越 DST 转换时,DataFrame.resample()
和Series.resample()
存在一个 bug (GH 9119, GH 21459) -
在
DataFrame.expanding()
中存在一个 bug,聚合时未遵守axis
参数 (GH 23372) -
在
GroupBy.transform()
中存在 bug,当输入函数可以接受DataFrame
但重命名时会导致缺失值(GH 23455)。 -
在
GroupBy.nth()
中存在 bug,列顺序不总是被保留(GH 20760)。 -
在
method='dense'
和pct=True
时,GroupBy.rank()
存在 bug,当一个组只有一个成员时会引发ZeroDivisionError
(GH 23666)。 -
使用空组调用
GroupBy.rank()
和pct=True
会引发ZeroDivisionError
(GH 22519)。 -
在
TimeDeltaIndex
中重新采样NaT
时,DataFrame.resample()
存在 bug(GH 13223)。 -
在选择列时,
DataFrame.groupby()
中存在 bug,不尊重observed
参数,而总是使用observed=False
(GH 23970)。 -
在计算百分比变化时,
SeriesGroupBy.pct_change()
或DataFrameGroupBy.pct_change()
之前会跨组工作,现在正确地按组工作(GH 21200,GH 21235)。 -
阻止使用非常大数量(2³²)的行创建哈希表的 bug(GH 22805)。
-
在对分类进行分组时,如果
observed=True
且分类列中存在nan
,会导致ValueError
和错误的分组,存在 bug(GH 24740,GH 21151)。
重塑
-
在具有时区感知索引的重新采样的 DataFrames 中连接时,
pandas.concat()
存在 bug(GH 13783)。 -
在仅连接
Series
时,pandas.concat()
不再忽略concat
的names
参数(GH 23490)。 -
在
datetime64[ns, tz]
数据类型中,Series.combine_first()
存在 bug,会返回 tz-naive 结果(GH 21469)。 -
当
datetime64[ns, tz]
数据类型存在时,Series.where()
和DataFrame.where()
存在错误(GH 21546) -
当空 DataFrame 和空
cond
具有非布尔数据类型时,DataFrame.where()
存在错误(GH 21947) -
当使用
list
条件时,Series.mask()
和DataFrame.mask()
存在错误(GH 21891) -
当转换超出范围的
datetime64[ns, tz]
时,DataFrame.replace()
存在 RecursionError 错误(GH 20380) -
当参数
na_option
传递无效值时,GroupBy.rank()
现在会引发ValueError
错误(GH 22124) -
在 Python 2 中,
get_dummies()
中的 Unicode 属性存在错误(GH 22084) -
当替换空列表时,
DataFrame.replace()
存在RecursionError
错误(GH 22083) -
当使用字典作为
to_replace
值,并且字典中的一个键是另一个键的值时,使用整数键和使用字符串键之间的结果不一致,Series.replace()
和DataFrame.replace()
存在错误(GH 20656) -
对于空
DataFrame
,DataFrame.drop_duplicates()
错误地引发错误(GH 20516) -
当将字符串传递给 stubnames 参数并且列名是该 stubname 的子字符串时,
pandas.wide_to_long()
存在错误(GH 22468) -
在
merge()
中存在一个错误,当合并包含 DST 转换的datetime64[ns, tz]
数据时出现错误(GH 18885)。 -
在
merge_asof()
中存在一个错误,当在定义的容差范围内对浮点值进行合并时出错(GH 22981)。 -
在
pandas.concat()
中存在一个错误,当连接带有时区感知数据的多列 DataFrame 与具有不同列数的 DataFrame 时会出现错误(GH 22796)。 -
在
merge_asof()
中存在一个错误,当尝试与缺失值合并时会引发混淆的错误消息(GH 23189)。 -
在
DataFrame.nsmallest()
和DataFrame.nlargest()
中存在一个错误,对于具有MultiIndex
列的数据帧(GH 23033)。 -
在
pandas.melt()
中存在一个错误,当传递的列名在DataFrame
中不存在时(GH 23575)。 -
在
DataFrame.append()
中存在一个错误,当带有 dateutil 时区的Series
进行追加时会引发TypeError
(GH 23682)。 -
在构建
Series
时出现错误,当传递的数据为空且dtype=str
时(GH 22477)。 -
在
cut()
中存在一个错误,当bins
是重叠的IntervalIndex
时,每个项目返回多个箱子而不是引发ValueError
(GH 23980)。 -
在
pandas.concat()
中存在一个错误,当将带有时区信息的Series
与Series
类别连接时会丢失时区信息(GH 23816)。 -
在
DataFrame.join()
中存在一个错误,当部分 MultiIndex 进行连接时会丢失名称(GH 20452)。 -
DataFrame.nlargest()
和DataFrame.nsmallest()
在 keep != ‘all’ 时返回正确的 n 值,同时在第一列并列时也返回正确的值 (GH 22752) -
使用不是
Index
实例的索引参数构建 DataFrame 时出现问题 (GH 22227). -
在
DataFrame
中的 Bug 阻止了列表子类用于构建 (GH 21226) -
DataFrame.unstack()
和DataFrame.pivot_table()
在生成的 DataFrame 元素超过 int32 可处理范围时返回误导性错误消息的 Bug。现在,错误消息已经改进,指向实际问题 (GH 20601) -
在
DataFrame.unstack()
中,当解除堆叠时抛出ValueError
,因为时区感知值 (GH 18338) -
在
DataFrame.stack()
中,时区感知值被转换为时区无关值的 Bug (GH 19420) -
在
merge_asof()
中,当by_col
是时区感知值时抛出TypeError
(GH 21184) -
在
DataFrame
构建过程中出现错误时显示错误形状不正确的 Bug。(GH 20742)
稀疏
-
现在可以将布尔、日期时间或时间增量列更新为稀疏列了 (GH 22367)
-
在
Series.to_sparse()
中,已经持有稀疏数据的 Series 未能正确构建的 Bug (GH 22389) -
现在,向 SparseArray 构造函数提供
sparse_index
不再默认将所有 dtypes 的 na-value 设置为np.nan
。现在使用正确的 na_value 为data.dtype
。 -
SparseArray.nbytes
的 Bug 未包括其稀疏索引大小,导致其内存使用量被低估。 -
对于非 NA
fill_value
,提高了Series.shift()
的性能,因为值不再转换为密集数组。 -
DataFrame.groupby
中存在一个 bug,在以稀疏列分组时,不包括fill_value
在非 NAfill_value
的分组中(GH 5078) -
在具有布尔值的
SparseSeries
上的一元求反运算符 (~
) 存在 bug。此性能也已得到改进(GH 22835) -
SparseArary.unique()
中存在一个 bug,未返回唯一值(GH 19595) -
SparseArray.nonzero()
和SparseDataFrame.dropna()
存在 bug,返回的结果有偏移/不正确(GH 21172) -
在
DataFrame.apply()
中存在一个 bug,其中数据类型会丢失稀疏性(GH 23744) -
在连接一组具有全稀疏值的
Series
时,在concat()
中存在一个 bug,改变了fill_value
并转换为密集 Series(GH 24371)
样式
-
background_gradient()
现在接受一个text_color_threshold
参数,根据背景颜色的亮度自动调亮文本颜色。这在没有限制背景颜色映射范围的情况下,提高了深色背景颜色的可读性(GH 21258) -
background_gradient()
现在也支持表格级的应用(除了行级和列级),使用axis=None
(GH 15204) -
bar()
现在也支持表格级的应用(除了行级和列级),使用axis=None
设置剪裁范围,并使用vmin
和vmax
设置剪裁范围。NaN
值也会被正确处理(GH 21548 和 GH 21526)
构建变更
-
构建 pandas 进行开发现在需要
cython >= 0.28.2
(GH 21688) -
现在测试 pandas 需要
hypothesis>=3.58
。你可以在这里找到 Hypothesis 文档,以及一个针对 pandas 的介绍 在贡献指南中。 (GH 22280) -
在 macOS 上构建 pandas 现在将最低目标定为 macOS 10.9,如果在 macOS 10.9 或以上运行 (GH 23424)
其他
- 在 C 变量中声明外部链接引发了 bug,如果在 pandas 之前导入某些其他 C 库,则会导致导入错误。 (GH 24113)
分类
-
在
Categorical.from_codes()
中存在一个 bug,codes
中的NaN
值会被悄悄地转换为0
(GH 21767)。将来这将引发一个ValueError
。同时也改变了.from_codes([1.1, 2.0])
的行为。 -
Categorical.sort_values()
中存在一个 bug,NaN
值始终位于前面,而不管na_position
的值如何 (GH 22556)。 -
当使用布尔值
Categorical
进行索引时存在 bug。现在将布尔值Categorical
视为布尔掩码 (GH 22665) -
使用空值和布尔类别构建
CategoricalIndex
在 dtype coercion 更改后引发ValueError
(GH 22702)。 -
Categorical.take()
中存在一个 bug,当用户提供fill_value
时未对其进行编码,可能导致ValueError
、错误的结果或段错误 (GH 23296)。 -
在
Series.unstack()
中指定不存在于类别中的fill_value
现在引发TypeError
,而不是忽略fill_value
(GH 23284) -
当对分类数据进行重采样
DataFrame.resample()
并在聚合时出现 bug,分类 dtype 会丢失。 (GH 23227) -
在
.str
-accessor 的许多方法中存在 bug,总是在调用CategoricalIndex.str
构造函数时失败 (GH 23555, GH 23556) -
Series.where()
中的一个 bug,导致分类数据失去了分类 dtype(GH 24077) -
Categorical.apply()
中的一个 bug,NaN
值可能被不可预测地处理。现在它们保持不变(GH 24241) -
Categorical
比较方法中的一个 bug,在与DataFrame
运算时错误地引发ValueError
(GH 24630) -
Categorical.set_categories()
中的一个 bug,使用rename=True
设置更少的新类别会导致段错误(GH 24675)
日期时间类
-
修复了两个具有不同
normalize
属性的DateOffset
对象可能被判定为相等的 bug(GH 21404) -
修复了
Timestamp.resolution()
错误地返回了 1 微秒timedelta
而不是 1 纳秒Timedelta
的 bug(GH 21336, GH 21365) -
to_datetime()
中的一个 bug,在指定box=True
时未能一致返回一个Index
(GH 21864) -
DatetimeIndex
比较中的一个 bug,字符串比较错误地引发了TypeError
(GH 22074) -
当比较与
timedelta64[ns]
dtype 数组相同时,DatetimeIndex
比较中的一个 bug;在某些情况下错误地引发了TypeError
,在其他情况下错误地未引发(GH 22074) -
DatetimeIndex
比较中的一个 bug,与对象 dtype 数组比较时错误引发TypeError
(GH 22074) -
DataFrame
中的一个 bug,使用datetime64[ns]
dtype 与Timedelta
类似对象进行加减法时出错(GH 22005, GH 22163) -
DataFrame
中的 Bug,datetime64[ns]
数据类型与DateOffset
对象的加减法返回object
数据类型而不是datetime64[ns]
数据类型(GH 21610,GH 22163) -
DataFrame
中的 Bug,datetime64[ns]
数据类型与NaT
的比较错误(GH 22242,GH 22163) -
DataFrame
中的 Bug,datetime64[ns]
数据类型减去类似Timestamp
的对象错误地返回datetime64[ns]
数据类型而不是timedelta64[ns]
数据类型(GH 8554,GH 22163) -
DataFrame
中的 Bug,datetime64[ns]
数据类型减去非纳秒单位的np.datetime64
对象无法转换为纳秒(GH 18874,GH 22163) -
DataFrame
中与类似Timestamp
的对象比较错误地未能对不匹配类型的不等式检查引发TypeError
(GH 8932,GH 22163) -
DataFrame
中的 Bug,包含混合数据类型,包括datetime64[ns]
的相等比较错误地引发TypeError
(GH 13128,GH 22163) -
DataFrame.values
返回一个单列DataFrame
的DatetimeIndex
,其包含时区感知的日期时间值。现在返回一个包含Timestamp
对象的二维numpy.ndarray
(GH 24024) -
DataFrame.eq()
中与NaT
的比较错误地返回True
或NaN
(GH 15697,GH 22163) -
在
DatetimeIndex
的减法操作中,错误地未能引发OverflowError
(GH 22492,GH 22508) -
在
DatetimeIndex
中错误地允许使用Timedelta
对象进行索引(GH 20464) -
在
DatetimeIndex
中存在一个 bug,当原始频率为None
时会设置频率(GH 22150) -
在
DatetimeIndex
的四舍五入方法(round()
,ceil()
,floor()
)以及Timestamp
的四舍五入方法(round()
,ceil()
,floor()
)可能导致精度丢失(GH 22591) -
Bug in
to_datetime()
函数中使用Index
参数时会丢失结果中的name
(GH 21697) -
在
PeriodIndex
中,添加或减去timedelta
或Tick
对象会产生错误的结果(GH 22988) -
在
Series
的 repr 中,具有 period-dtype 数据时缺少数据前的空格(GH 23601) -
在
date_range()
中存在一个 bug,通过负频率将起始日期递减到过去的结束日期时会出现问题(GH 23270) -
Series.min()
函数存在一个错误,当在NaT
的 series 上调用时,会返回NaN
而不是NaT
(GH 23282) -
Series.combine_first()
函数存在一个错误,未正确对齐分类数据,因此self
中的缺失值未被other
中的有效值填充(GH 24147) -
DataFrame.combine()
函数存在一个错误,其中 datetimelike 值引发 TypeError 错误(GH 23079) -
date_range()
函数存在一个错误,当频率为Day
或更高时,将来足够遥远的日期可能会被回绕到过去,而不是引发OutOfBoundsDatetime
错误(GH 14187) -
period_range()
存在一个错误,当提供了Period
对象作为start
和end
时,会忽略start
和end
的频率(GH 20535) -
在属性
freq.n
大于 1 时,PeriodIndex
存在一个错误,添加DateOffset
对象会返回不正确的结果(GH 23215) -
Series
存在一个错误,当设置 datetimelike 值时,会将字符串索引解释为字符列表(GH 23451) -
在创建新列时,
DataFrame
存在一个错误,从带有时区的Timestamp
对象的 ndarray 中创建一个对象-dtype 列,而不是带有时区的 datetime 列(GH 23932) -
Timestamp
构造函数存在一个错误,会丢弃输入Timestamp
的频率(GH 22311) -
在调用
np.array(dtindex, dtype=object)
时,DatetimeIndex
存在一个错误,会错误地返回一个long
对象的数组(GH 23524) -
在
Index
中存在一个 bug,当传递一个带有时区信息的DatetimeIndex
和dtype=object
时,会错误地引发ValueError
(GH 23524) -
在
Index
中存在一个 bug,当对一个时区无关的DatetimeIndex
调用np.array(dtindex, dtype=object)
时,会返回一个datetime
对象数组,而不是Timestamp
对象数组,可能会丢失时间戳的纳秒部分 (GH 23524) -
在
Categorical.__setitem__
中存在一个 bug,在两者都是无序的情况下,不允许用另一个Categorical
进行设置,并且具有相同的类别,但顺序不同 (GH 24142) -
在
date_range()
中存在一个 bug,使用毫秒分辨率或更高的日期可能会返回不正确的值或索引中的错误数量的值 (GH 24110) -
在
DatetimeIndex
中存在一个 bug,当从Categorical
或CategoricalIndex
构造一个DatetimeIndex
时,会错误地丢弃时区信息 (GH 18664) -
在
DatetimeIndex
和TimedeltaIndex
中存在一个 bug,使用Ellipsis
进行索引会错误地丢失索引的freq
属性 (GH 21282) -
当将错误的
freq
参数传递给DatetimeIndex
时,以NaT
作为传递数据的第一个条目时,会生成澄清的错误消息 (GH 11587) -
在
to_datetime()
中存在一个 bug,当传递一个DataFrame
或单位映射的dict
时,会忽略box
和utc
参数 (GH 23760) -
在
Series.dt
中存在的错误,即在原地操作后缓存未能正确更新(GH 24408) -
在
PeriodIndex
中存在的错误,与长度为 1 的类似数组进行比较未能引发ValueError
(GH 23078) -
DatetimeIndex.astype()
、PeriodIndex.astype()
和TimedeltaIndex.astype()
中存在的错误,忽略了无符号整数数据类型的dtype
的符号(GH 24405) -
修复了具有
datetime64[ns]
数据类型的Series.max()
在存在空值且传递skipna=False
时未能返回NaT
的错误(GH 24265) -
在
to_datetime()
中存在的错误,即包含既有时区感知又有时区无关的datetime
对象数组会未能引发ValueError
(GH 24569) -
在使用无效日期时间格式的
to_datetime()
中,即使errors='coerce'
也不会将输入强制转换为NaT
的错误(GH 24763)
时间增量
-
具有
timedelta64[ns]
数据类型的DataFrame
除以Timedelta
-like 标量时,错误地返回timedelta64[ns]
数据类型而不是float64
数据类型(GH 20088,GH 22163) -
将具有对象数据类型的
Index
添加到具有timedelta64[ns]
数据类型的Series
时出现错误地引发错误(GH 22390) -
在将具有数值数据类型的
Series
与timedelta
对象相乘时存在的错误(GH 22390) -
在具有数值数据类型的
Series
中,当将数组或具有timedelta64
数据类型的Series
相加或相减时存在的错误(GH 22390) -
在具有数值数据类型的
Index
中,将具有timedelta64
数据类型的数组相乘或相除时存在的错误(GH 22390) -
TimedeltaIndex
中的错误允许使用Timestamp
对象进行索引(GH 20464) -
修复了从对象数据类型的数组中减去
Timedelta
会引发TypeError
的错误(GH 21980) -
修复了将所有-timedelta64[ns]数据类型的
DataFrame
添加到所有整数数据类型的DataFrame
中返回不正确结果而不是引发TypeError
的错误(GH 22696) -
TimedeltaIndex
中的错误,将一个带时区的 datetime 标量错误地返回为时区无关的DatetimeIndex
(GH 23215) -
在
TimedeltaIndex
中的错误,添加np.timedelta64('NaT')
会错误地返回全部为NaT
的DatetimeIndex
而不是全部为NaT
的TimedeltaIndex
(GH 23215) -
Timedelta
和to_timedelta()
中的错误,在支持的单位字符串上存在不一致性(GH 21762) -
TimedeltaIndex
中的错误,将其除以另一个TimedeltaIndex
会引发TypeError
而不是返回Float64Index
的错误(GH 23829,GH 22631) -
在
TimedeltaIndex
的比较操作中,与非Timedelta
类似对象比较会引发TypeError
而不是对于__eq__
返回全部为False
,对于__ne__
返回全部为True
的错误(GH 24056) -
Timedelta
比较中的缺陷,与Tick
对象比较时会不正确地引发TypeError
(GH 24710)
时区
-
在
Index.shift()
中存在缺陷,当跨越 DST 时会引发AssertionError
(GH 8616) -
在
Timestamp
构造函数中存在缺陷,传递无效的时区偏移标识符 (Z
) 不会引发ValueError
(GH 8910) -
在
Timestamp.replace()
中存在缺陷,在 DST 边界处进行替换会保留不正确的偏移 (GH 7825) -
在
Series.replace()
中存在缺陷,用datetime64[ns, tz]
数据替换NaT
时 (GH 11792) -
在
Timestamp
中传递不同的字符串日期格式与时区偏移时会产生不同的时区偏移的缺陷 (GH 12064) -
在比较 tz-naive
Timestamp
和 tz-awareDatetimeIndex
时存在缺陷,会强制DatetimeIndex
转换为 tz-naive (GH 12601) -
Series.truncate()
存在缺陷,使用 tz-awareDatetimeIndex
会导致核心转储 (GH 9243) -
在
Series
构造函数中存在缺陷,会将 tz-aware 和 tz-naiveTimestamp
转换为 tz-aware (GH 13051) -
Index
存在缺陷,datetime64[ns, tz]
dtype 没有正确地本地化整数数据 (GH 20964) -
DatetimeIndex
构造中的错误,使用整数和时区时无法正确本地化(GH 12619) -
修复了在时区感知日期时间上调用
DataFrame.describe()
和Series.describe()
时未显示first
和last
结果的错误(GH 21328) -
DatetimeIndex
比较中的错误,当比较时区感知的DatetimeIndex
和np.datetime64
时未能引发TypeError
错误(GH 22074) -
DataFrame
分配中存在的时区感知标量的错误(GH 19843) -
DataFrame.asof()
中的错误,当尝试比较时区感知和非时区感知时间戳时引发TypeError
错误(GH 21194) -
构造带有 DST 转换的
DatetimeIndex
时使用replace
方法构造的Timestamp
存在的错误(GH 18785) -
使用带有 DST 转换的
DatetimeIndex
的DataFrame.loc()
设置新值时存在的错误(GH 18308, GH 20724) -
Index.unique()
中的错误,未能正确重新本地化时区感知日期(GH 21737) -
在带有 DST 转换的
Series
索引时存在的错误(GH 21846) -
Bug in
DataFrame.resample()
和Series.resample()
中存在的问题,即当时区感知时间序列以 DST 转换结束时,会引发AmbiguousTimeError
或NonExistentTimeError
错误(GH 19375, GH 10117) -
在
DataFrame.drop()
和Series.drop()
中的一个错误,当指定一个带时区信息的Timestamp
键从DatetimeIndex
中删除时,会出现夏令时转换问题(GH 21761) -
在
DatetimeIndex
构造函数中的一个错误,当NaT
和dateutil.tz.tzlocal
同时出现时会引发OutOfBoundsDatetime
错误(GH 23807) -
在夏令时转换附近使用
DatetimeIndex.tz_localize()
和Timestamp.tz_localize()
时的一个错误,会返回一个错误的本地化日期时间(GH 23807) -
在
Timestamp
构造函数中的一个错误,当使用datetime.datetime
参数传递dateutil.tz.tzutc
时,会转换为pytz.UTC
时区(GH 23807) -
在
to_datetime()
中的一个错误,在指定unit
和errors='ignore'
时未能尊重utc=True
(GH 23758) -
to_datetime()
中的一个错误,在传递Timestamp
时未能尊重utc=True
(GH 24415) -
在
DataFrame.any()
中的一个错误,当axis=1
且数据是 datetimelike 类型时,返回错误的值(GH 23070) -
在
DatetimeIndex.to_period()
中的一个错误,当一个带时区的索引被转换为 UTC 时,然后创建PeriodIndex
时出现问题(GH 22905) -
在
DataFrame.tz_localize()
、DataFrame.tz_convert()
、Series.tz_localize()
和Series.tz_convert()
中的错误,其中copy=False
将原始参数就地修改 (GH 6326) -
使用
axis=1
的DataFrame.max()
和DataFrame.min()
中的错误,当所有列包含相同的时区时,会返回一个包含NaN
的Series
(GH 10390)
偏移
-
在
FY5253
中的错误,日期偏移可能在算术运算中错误地引发AssertionError
(GH 14774) -
DateOffset
中的错误,接受并忽略关键字参数week
和milliseconds
。现在传递这些将引发ValueError
(GH 19398) -
使用
DataFrame
或PeriodIndex
添加DateOffset
时的错误,错误地引发TypeError
(GH 23215) -
将
DateOffset
对象与非DateOffset
对象(尤其是字符串)进行比较的错误,在相等检查中引发ValueError
,而不是返回False
,在不相等检查中返回True
(GH 23524)
数值
-
Series
中的错误,__rmatmul__
不支持矩阵向量乘法 (GH 21530) -
在
factorize()
中,无法处理只读数组的错误 (GH 12813) -
在
unique()
中的错误,在处理有符号零时不一致:对于某些输入,0.0 和 -0.0 被视为相等,对于某些输入则视为不同。现在对于所有输入,它们都被视为相等 (GH 21866) -
在
DataFrame.agg()
、DataFrame.transform()
和DataFrame.apply()
中存在错误,当提供函数列表和axis=1
(例如df.apply(['sum', 'mean'], axis=1)
)时,错误地引发了TypeError
。现在这三种方法都已经正确计算了(GH 16679)。 -
对于
Series
与日期时间样式标量和数组的比较存在错误(GH 22074)。 -
在布尔 dtype 和整数之间的
DataFrame
乘法中,返回的是对象 dtype 而不是整数 dtype(GH 22047, GH 22163)。 -
在
DataFrame.apply()
中存在错误,当提供字符串参数和额外的位置或关键字参数时(例如df.apply('sum', min_count=1)
),错误地引发了TypeError
(GH 22376)。 -
在将到扩展 dtype 的
DataFrame.astype()
时,可能会引发AttributeError
(GH 22578)。 -
在带有
timedelta64[ns]
dtype 的DataFrame
中,与整数 dtype 的ndarray
进行算术运算时,错误地将 narray 视为timedelta64[ns]
dtype(GH 23114)。 -
在带有对象 dtype 的
Series.rpow()
中,对于NaN
的1 ** NA
而不是1
存在错误(GH 22922)。 -
Series.agg()
现在可以处理像numpy.nansum()
这样的 numpy NaN-aware 方法了(GH 19629)。 -
当存在超过 2²⁴ 行时,
Series.rank()
和DataFrame.rank()
中pct=True
时存在错误,导致百分比大于 1.0(GH 18271)。 -
如
DataFrame.round()
在具有非唯一CategoricalIndex()
的情况下的调用现在返回预期的数据。先前,数据会被错误地重复(GH 21809)。 -
将
log10
、floor
和ceil
添加到支持的函数列表中,以在DataFrame.eval()
中使用(GH 24139, GH 24353) -
逻辑操作
&, |, ^
在Series
和Index
之间将不再引发ValueError
(GH 22092) -
在
is_scalar()
函数中检查 PEP 3141 数字现在返回True
(GH 22903) -
当从 NumPy ufunc 调用时,类似
Series.sum()
的归约方法现在接受keepdims=False
的默认值,而不是引发TypeError
。完整支持keepdims
尚未实现 (GH 24356).
转换
-
在
DataFrame.combine_first()
中的一个 bug 导致列类型意外地转换为浮点数 (GH 20699) -
在
DataFrame.clip()
中存在的一个 bug,其中列类型未被保留并转换为浮点数 (GH 24162) -
在数据框的列顺序不匹配时,
DataFrame.clip()
中的一个 bug 导致观察到的结果在数字值上是错误的 (GH 20911) -
在存在重复列名时,将
DataFrame.astype()
中的转换为扩展数据类型会导致RecursionError
的错误(GH 24704)
字符串
-
Index.str.partition()
中的一个 bug 不是 nan 安全的 (GH 23558). -
Index.str.split()
中的一个 bug 不是 nan 安全的 (GH 23677). -
Series.str.contains()
中的错误不尊重Categorical
类型的Series
的na
参数 (GH 22158) -
当结果仅包含
NaN
时,Index.str.cat()
中存在的错误 (GH 24044)
区间
-
在
IntervalIndex
构造函数中,closed
参数并不总是覆盖推断的closed
(GH 19370) -
IntervalIndex
的表示中存在尾随逗号丢失的错误 (GH 20611) -
在
Interval
中存在的错误,标量算术运算不保留closed
值 (GH 22313) -
在
IntervalIndex
中,使用类似日期时间的值进行索引会引发KeyError
(GH 20636) -
在
IntervalTree
中的错误,其中包含NaN
的数据会触发警告,并导致使用IntervalIndex
进行的不正确的索引查询 (GH 23352)
索引
-
如果列包含列名“dtype”,
DataFrame.ne()
会失败 (GH 22383) -
当请求
.loc
获取单个缺失标签时,KeyError
的回溯现在更短更清晰了 (GH 21557) -
当查找的字符串格式不正确时,
PeriodIndex
现在会引发KeyError
,这与DatetimeIndex
的行为一致 (GH 22803) -
当在具有整数类型第一级的
MultiIndex
中请求缺失的整数标签时,.ix
现在会引发KeyError
,与平坦的Int64Index
的情况一致,而不是回退到位置索引 (GH 21593) -
当重新索引一个时区无关和时区感知的
DatetimeIndex
时,在Index.reindex()
中出现错误。(GH 8306) -
当使用
datetime64[ns, tz]
dtype 重新索引一个空系列时,在Series.reindex()
中出现错误。(GH 20869) -
在使用
.loc
和一个时区感知的DatetimeIndex
设置值时,在DataFrame
中修复了问题。(GH 11365) -
DataFrame.__getitem__
现在接受字典和字典键作为标签的列表,与Series.__getitem__
保持一致。(GH 21294) -
修复了在列不唯一时
DataFrame[np.nan]
的问题。(GH 21428) -
当使用纳秒分辨率日期和时区索引
DatetimeIndex
时出现错误。(GH 11679) -
当使用包含负值的 Numpy 数组进行索引时,会改变索引器。(GH 21867)
-
混合索引不允许整数用于
.at
时出现错误。(GH 19860) -
Float64Index.get_loc
现在在传递布尔键时引发KeyError
。(GH 19087) -
当使用
IntervalIndex
进行索引时,在DataFrame.loc()
中出现错误。(GH 19977) -
Index
不再混淆None
、NaN
和NaT
,即它们被视为三个不同的键。但是,对于数值索引,这三个仍然被强制转换为NaN
。(GH 22332) -
如果标量是浮点数,而
Index
是整数 dtype,则在scalar in Index
中出现错误。(GH 22085) -
当 levels 值不可索引时,在
MultiIndex.set_levels()
中出现错误。(GH 23273) -
在通过
Index
设置 timedelta 列时,会将其转换为 double,从而失去精度的 bug (GH 23511) -
在
Index.union()
和Index.intersection()
中存在一个 bug,对于某些情况,结果的Index
的名称计算不正确(GH 9943, GH 9862) -
在使用布尔型
Index
对Index
进行切片时可能会引发TypeError
的 bug (GH 22533) -
在接受切片和类似列表值时,
PeriodArray.__setitem__
存在 bug (GH 23978) -
对于
DatetimeIndex
和TimedeltaIndex
存在一个 bug,使用Ellipsis
进行索引会丢失它们的freq
属性(GH 21282) -
在使用
iat
进行赋值时,如果赋值的值不兼容,会创建一个新列的 bug (GH 23236)
缺失
-
在
DataFrame.fillna()
中存在一个 bug,当一列包含datetime64[ns, tz]
类型时,会引发ValueError
(GH 15522) -
在
Series.hasnans()
中存在一个 bug,如果在初始调用后引入了空元素,则可能会错误地缓存和返回错误的答案 (GH 19700) -
Series.isin()
现在对于np.object_
-dtype 也将所有 NaN-floats 视为相等。这个行为与 float64 的行为一致 (GH 22119) -
unique()
不再对 NaN-floats 和NaT
-object 进行修改,并且对于np.object_
-dtype,即NaT
不再被强制转换为 NaN 值,并且被视为一个不同的实体。 (GH 22295) -
现在,
DataFrame
和Series
可以正确处理带有强化掩码的 numpy 掩码数组。以前,从带有硬掩码的掩码数组构造 DataFrame 或 Series 会创建一个包含底层值的 pandas 对象,而不是预期的 NaN。(GH 24574) -
在处理 numpy 掩码记录数组时,
DataFrame
构造函数中的dtype
参数未被遵守的错误。(GH 24874)
多重索引
-
在
io.formats.style.Styler.applymap()
中存在的错误,在使用MultiIndex
切片的subset=
会被缩减为Series
(GH 19861) -
删除了对版本 0.8.0 之前的
MultiIndex
pickles 的兼容性;与版本 0.13 之后的MultiIndex
pickles 的兼容性保持不变。(GH 21654) -
MultiIndex.get_loc_level()
(以及作为结果,对具有MultiIndex
索引的Series
或DataFrame
的.loc
)现在将引发一个KeyError
,而不是返回一个空的slice
,如果询问在levels
中存在但未使用的标签。(GH 22221) -
MultiIndex
已经获得了MultiIndex.from_frame()
,它允许从DataFrame
构造一个MultiIndex
对象。(GH 22420) -
在 Python 3 中修复了当创建
MultiIndex
时出现的TypeError
,其中某些级别具有混合类型,例如当某些标签是元组时。(GH 15457)
IO
-
read_csv()
中的错误,当指定了CategoricalDtype
的布尔类别列时,字符串值未能正确转换为布尔值(GH 20498) -
read_csv()
中的错误,Python 2.x 下未正确识别 Unicode 列名(GH 13253) -
DataFrame.to_sql()
中的错误,当写入带有时区信息的数据(datetime64[ns, tz]
dtype)时会引发TypeError
(GH 9086) -
DataFrame.to_sql()
中的错误,当在支持的数据库中写入一个未经过时区处理的DatetimeIndex
时,会被写入为TIMESTAMP WITH TIMEZONE
类型,例如在 PostgreSQL 中(GH 23510) -
read_excel()
中的错误,当使用空数据集指定parse_cols
时会出错(GH 9208) -
read_html()
在考虑skiprows
和header
参数时,不再忽略所有空格<thead>
中的全空白<tr>
。以前,用户不得不降低header
和skiprows
值以解决此问题。(GH 21641) -
read_excel()
将正确显示先前弃用的sheetname
的弃用警告(GH 17994) -
read_csv()
和read_table()
在遇到错误编码的字符串时,将抛出UnicodeError
而不是导致核心转储(GH 22748) -
read_csv()
将正确解析带有时区信息的日期时间(GH 22256) -
read_csv()
中的错误,在数据被分块读取时,当数据以 C 引擎被读取时,内存管理过早地进行了优化,导致了错误(GH 23509) -
read_csv()
存在错误,当提取多级索引时,无名列被错误地识别(GH 23687) -
read_sas()
将正确解析宽度小于 8 字节的 sas7bdat 文件中的数字(GH 21616) -
read_sas()
将正确解析具有许多列的 sas7bdat 文件(GH 22628) -
read_sas()
将正确解析数据页面类型为 128 + 256 = 384 的 sas7bdat 文件(GH 16615) -
read_sas()
存在错误,对无效文件格式会抛出不正确的错误(GH 24548) -
detect_client_encoding()
中存在错误,当在 mod_wsgi 进程中导入时,由于对标准输出的访问受限,潜在的IOError
未处理(GH 21552) -
DataFrame.to_html()
在index=False
的情况下,截断的 DataFrame 缺失了截断指示符(…)(GH 15019, GH 22783) -
DataFrame.to_html()
在index=False
时,当列和行索引都是MultiIndex
时存在错误(GH 22579) -
DataFrame.to_html()
在index_names=False
的情况下,显示了索引名称(GH 22747) -
DataFrame.to_html()
在header=False
的情况下存在错误,未显示行索引名称(GH 23788) -
DataFrame.to_html()
在sparsify=False
的情况下存在错误,导致引发TypeError
错误(GH 22887) -
当
index=False
且第一列的值的宽度大于第一列的标头宽度时,导致列对齐中断的DataFrame.to_string()
中的 bug (GH 16839, GH 13032) -
导致
DataFrame
的表示形式不占据整个窗口的DataFrame.to_string()
中的 bug (GH 22984) -
单级 MultiIndex 错误地写入元组的
DataFrame.to_csv()
中的 bug,现在只写入索引的值 (GH 19589). -
当
format
kwarg 被传递给构造函数时,HDFStore
会引发ValueError
(GH 13291) -
在向具有空字符串列和
min_itemsize
< 8 的DataFrame
添加时存在 bug 的HDFStore.append()
(GH 12242) -
在解析
NaN
值时,由于完成或错误时清理不足,导致 C 引擎中发生内存泄漏的read_csv()
中的 bug (GH 21353) -
当
skipfooter
与nrows
、iterator
或chunksize
一起传递时,引发不正确错误消息的read_csv()
中的 bug (GH 23711) -
在
read_csv()
中存在的 bug 是在未提供MultiIndex
索引名称时处理不当的情况 (GH 23484) -
在
read_csv()
中存在的 bug 是在方言的值与默认参数冲突时引发不必要警告 (GH 23761) -
在提供无效值时,
read_html()
中的错误消息未显示有效的 flavors 的 bug (GH 23549) -
read_excel()
中即使未指定也提取了多余的标题名称的错误(GH 11733) -
read_excel()
中有时未正确将列名转换为字符串的错误在 Python 2.x 中发生(GH 23874) -
read_excel()
中index_col=None
未被尊重且仍然解析索引列的错误(GH 18792,GH 20480) -
read_excel()
中usecols
作为字符串传递时未验证适当的列名的错误(GH 20480) -
DataFrame.to_dict()
在数值数据情况下生成的字典包含非 Python 标量时存在错误(GH 23753) -
DataFrame.to_string()
、DataFrame.to_html()
、DataFrame.to_latex()
当将字符串作为float_format
参数传递时,将正确格式化输出(GH 21625,GH 22270) -
read_csv()
尝试使用 ‘inf’ 作为整数索引列的na_value
时引发OverflowError
的错误(GH 17128) -
read_csv()
在 Python 3.6+ 的 Windows 上,C 引擎在不正确读取带重音符号或特殊字符的 CSV 文件名时的错误(GH 15086) -
read_fwf()
中文件的压缩类型无法正确推断导致的错误(GH 22199) -
pandas.io.json.json_normalize()
中当record_path
的连续两个元素是字典时引发TypeError
的错误(GH 22706) -
在
DataFrame.to_stata()
、pandas.io.stata.StataWriter
和pandas.io.stata.StataWriter117
中存在错误,当异常发生时,会留下部分写入的无效 dta 文件(GH 23573)。 -
使用带有非 ASCII 字符的 strLs 时,
DataFrame.to_stata()
和pandas.io.stata.StataWriter117
会生成无效文件(GH 23573)。 -
在 Python 3 中从 Python 2 中固定格式编写的 Dataframe 中读取时,
HDFStore
会导致引发ValueError
的错误(GH 24510)。 -
在
DataFrame.to_string()
和浮点repr
格式化器中普遍存在错误。如果列中存在inf
,则不会删除零,而 NA 值则会。现在,与存在 NA 值时一样,零已被删除(GH 24861)。 -
在截断列数并且最后一列宽度较宽时,
repr
中存在错误(GH 24849)。
绘图
-
在 IPython inline 后端中启用 colorbar 时,
DataFrame.plot.scatter()
和DataFrame.plot.hexbin()
中的 x 轴标签和刻度标签消失了(GH 10611,GH 10678,以及GH 20455)。 -
使用
matplotlib.axes.Axes.scatter()
绘制日期时间序列的图表时存在错误(GH 22039)。 -
DataFrame.plot.bar()
中的错误导致柱形图使用多种颜色而不是单一颜色(GH 20585)。 -
验证颜色参数时存在错误,导致额外的颜色被追加到给定的颜色数组中。这发生在使用 matplotlib 的多个绘图函数中(GH 20726)。
GroupBy/resample/rolling
-
在
closed='left'
、类似日期时间的索引和序列中只有一个条目时,Rolling.min()
和Rolling.max()
存在错误,导致段错误(GH 24718)。 -
Bug in
GroupBy.first()
和GroupBy.last()
在as_index=False
的情况下导致时区信息丢失的问题(GH 15884) -
Bug in
DateFrame.resample()
在跨越夏令时边界进行降采样时出现问题(GH 8531) -
Bug in
DateFrame.resample()
中使用偏移量Day
进行日期定位时,当 n > 1 时出现问题(GH 24127) -
当调用
SeriesGroupBy.count()
方法时,当分组变量仅包含 NaN 并且 numpy 版本 < 1.13 时错误地引发ValueError
的问题(GH 21956). -
在具有
closed='left'
和类似日期时间索引的情况下,Rolling.min()
中存在多个错误导致结果不正确并且出现段错误。(GH 21704) -
Bug in
Resampler.apply()
在将位置参数传递给应用函数时出现问题(GH 14615). -
Bug in
Series.resample()
在将numpy.timedelta64
传递给loffset
kwarg 时出现问题(GH 7687)。 -
Bug in
Resampler.asfreq()
当TimedeltaIndex
的频率是新频率的子周期时出现问题(GH 13022). -
Bug in
SeriesGroupBy.mean()
当值为整数但无法适应 int64 时溢出而出现问题。(GH 22487) -
RollingGroupby.agg()
和ExpandingGroupby.agg()
现在支持多个聚合函数作为参数(GH 15072) -
Bug in
DataFrame.resample()
和Series.resample()
在通过周偏移量('W'
)跨越夏令时转换进行重采样时出现问题(GH 9119, GH 21459) -
Bug in
DataFrame.expanding()
中在聚合过程中未能尊重axis
参数的问题(GH 23372) -
在
GroupBy.transform()
中存在错误,当输入函数可以接受一个DataFrame
但重命名时会导致缺失值(GH 23455)。 -
在
GroupBy.nth()
中,未始终保留列顺序时存在错误(GH 20760)。 -
当一个组只有一个成员时,在使用
method='dense'
和pct=True
的情况下,GroupBy.rank()
中存在错误会引发ZeroDivisionError
(GH 23666)。 -
使用空分组调用
GroupBy.rank()
并且pct=True
时,会引发ZeroDivisionError
(GH 22519)。 -
在
TimeDeltaIndex
中重新采样NaT
时,DataFrame.resample()
存在错误(GH 13223)。 -
在选择列并且始终使用
observed=False
时,DataFrame.groupby()
中的错误未遵守observed
参数(GH 23970)。 -
在计算百分比变化时,
SeriesGroupBy.pct_change()
或DataFrameGroupBy.pct_change()
之前跨组工作,现在在每个组中正确工作(GH 21200,GH 21235)。 -
阻止创建非常大的行数(2³²)的哈希表时存在错误(GH 22805)。
-
在对分类数据进行分组时,如果
observed=True
且nan
存在于分类列中,则会导致ValueError
和不正确的分组(GH 24740,GH 21151)。
重塑
-
当使用具有时区感知索引的重新采样的 DataFrame 连接时,
pandas.concat()
存在错误(GH 13783)。 -
当仅连接
Series
时,pandas.concat()
中的错误导致concat
的names
参数不再被忽略(GH 23490)。 -
当返回
datetime64[ns, tz]
dtype 时,Series.combine_first()
存在错误,会返回 tz-naive 结果(GH 21469)。 -
具有
datetime64[ns, tz]
dtype 的Series.where()
和DataFrame.where()
中的错误(GH 21546) -
在空 DataFrame 和空
cond
具有非布尔 dtype 时,DataFrame.where()
中的错误(GH 21947) -
具有
list
条件的Series.mask()
和DataFrame.mask()
中的错误(GH 21891) -
DataFrame.replace()
中的错误在将 OutOfBoundsdatetime64[ns, tz]
转换时引发了 RecursionError(GH 20380) -
当为参数
na_option
传递无效值时,GroupBy.rank()
现在会引发ValueError
(GH 22124) -
在 Python 2 中具有 Unicode 属性的
get_dummies()
中的错误(GH 22084) -
在替换空列表时,
DataFrame.replace()
引发RecursionError
(GH 22083) -
当字典用作
to_replace
值并且字典中的一个键是另一个键的值时,Series.replace()
和DataFrame.replace()
中的错误在使用整数键和使用字符串键时结果不一致(GH 20656) -
对于空
DataFrame
,DataFrame.drop_duplicates()
中的错误不正确地引发了错误(GH 20516) -
当将字符串传递给 stubnames 参数并且列名是该 stubname 的子字符串时,
pandas.wide_to_long()
中的错误(GH 22468) -
在合并具有 DST 转换的
datetime64[ns, tz]
数据时出现的错误 (GH 18885) -
在
merge_asof()
进行合并时,当在定义的容差范围内合并浮点值时出现的错误 (GH 22981) -
在使用
pandas.concat()
进行拼接时,当拼接具有 tz-aware 数据的多列 DataFrame 与列数不同的 DataFrame 时出现的错误 (GH 22796) -
在尝试使用 merge_asof()`进行合并时,当尝试与缺失值合并时会引发混淆的错误消息 (GH 23189)
-
在具有
MultiIndex
列的 DataFrame 上使用DataFrame.nsmallest()
和DataFrame.nlargest()
时出现的错误 (GH 23033) -
在传递不存在于 DataFrame 中的列名时,使用
pandas.melt()
出现的错误 (GH 23575) -
在具有
Series
且带有 dateutil 时区的情况下,使用DataFrame.append()
会引发TypeError
(GH 23682) -
在构造
Series
时出现的错误,当没有传递数据且dtype=str
时 (GH 22477) -
在使用
bins
作为重叠的IntervalIndex
时,返回多个 bin 而不是引发ValueError
的情况下,使用cut()
出现的错误 (GH 23980) -
在使用
pandas.concat()
进行连接时,将具有时区信息的Series
与Series
类别进行连接会丢失时区信息 (GH 23816) -
在部分 MultiIndex 上进行连接时,使用
DataFrame.join()
会丢失名称 (GH 20452) -
DataFrame.nlargest()
和DataFrame.nsmallest()
现在在 keep != ‘all’时返回正确的 n 值,同时在第一列上并列时也返回正确的值。(GH 22752) -
使用不是
Index
实例的索引参数构造 DataFrame 时出现问题。(GH 22227). -
Bug in
DataFrame
阻止了列表子类用于构造(GH 21226) -
DataFrame.unstack()
和DataFrame.pivot_table()
中的错误,当结果 DataFrame 的元素超过 int32 可以处理的范围时,返回一个误导性的错误消息。现在,错误消息已经改进,指向实际问题。(GH 20601) -
DataFrame.unstack()
中的错误,当解除堆叠时,对时区感知值引发ValueError
。(GH 18338) -
DataFrame.stack()
中的错误,将时区感知值转换为时区无关值。(GH 19420) -
merge_asof()
中的错误,当by_col
为时区感知值时引发TypeError
。(GH 21184) -
在
DataFrame
构造过程中抛出错误时,显示错误形状不正确的错误。(GH 20742)
稀疏
-
现在可以将布尔值、日期时间或时间差列更新为稀疏列。(GH 22367)
-
Series.to_sparse()
中的错误,对已持有稀疏数据的 Series 未能正确构造。(GH 22389) -
为 SparseArray 构造函数提供
sparse_index
不再将所有数据类型的 na-value 默认为np.nan
。现在使用data.dtype
的正确 na_value。 -
SparseArray.nbytes
中的错误,未包括其稀疏索引大小,导致其内存使用量报告不准确。 -
改进了对非 NA
fill_value
的Series.shift()
的性能,因为值不再转换为密集数组。 -
在通过稀疏列分组时,
DataFrame.groupby
中的错误未包括非 NAfill_value
在组中(GH 5078) -
在具有布尔值的
SparseSeries
上的一元反转运算符(~
)存在错误。此性能也得到了改进(GH 22835) -
SparseArary.unique()
存在错误,未返回唯一值(GH 19595) -
SparseArray.nonzero()
和SparseDataFrame.dropna()
存在错误,返回了偏移/不正确的结果(GH 21172) -
在
DataFrame.apply()
中存在错误,dtype 会失去稀疏性(GH 23744) -
在使用
concat()
连接具有全稀疏值的Series
列表时存在错误,改变fill_value
并转换为密集 Series 时出现问题(GH 24371)
样式
-
background_gradient()
现在接受text_color_threshold
参数,根据背景颜色的亮度自动调整文本颜色。这在不限制背景色彩映射范围的情况下提高了深色背景颜色的可读性。(GH 21258) -
background_gradient()
现在还支持表格级应用(除了行级和列级),使用axis=None
(GH 15204) -
bar()
现在还支持表格级应用(除了行级和列级),使用axis=None
并使用vmin
和vmax
设置剪裁范围(GH 21548和GH 21526)。NaN
值也得到了正确处理。
构建更改
-
为了开发,构建 pandas 现在需要
cython >= 0.28.2
(GH 21688) -
现在测试 pandas 需要
hypothesis>=3.58
。你可以在这里找到 Hypothesis 文档,以及 pandas 特定的介绍。(GH 22280) -
现在在 macOS 上构建 pandas 会将最低 macOS 版本定为 10.9(如果在 macOS 10.9 或更高版本上运行)(GH 23424)
Other
- 修复了一个 bug,其中 C 变量被声明为外部链接,导致在导入 pandas 之前导入某些其他 C 库时出现导入错误。(GH 24113)
贡献者
这个版本有 337 人参与了补丁的贡献。名字后面有“+”的人是首次贡献补丁的。
-
AJ Dyka +
-
AJ Pryor, Ph.D +
-
Aaron Critchley
-
Adam Hooper
-
Adam J. Stewart
-
Adam Kim
-
Adam Klimont +
-
Addison Lynch +
-
Alan Hogue +
-
Alex Radu +
-
Alex Rychyk
-
Alex Strick van Linschoten +
-
Alex Volkov +
-
Alexander Buchkovsky
-
Alexander Hess +
-
Alexander Ponomaroff +
-
Allison Browne +
-
Aly Sivji
-
Andrew
-
Andrew Gross +
-
Andrew Spott +
-
Andy +
-
Aniket uttam +
-
Anjali2019 +
-
Anjana S +
-
Antti Kaihola +
-
Anudeep Tubati +
-
Arjun Sharma +
-
Armin Varshokar
-
Artem Bogachev
-
ArtinSarraf +
-
Barry Fitzgerald +
-
Bart Aelterman +
-
Ben James +
-
Ben Nelson +
-
Benjamin Grove +
-
Benjamin Rowell +
-
Benoit Paquet +
-
Boris Lau +
-
Brett Naul
-
Brian Choi +
-
C.A.M. Gerlach +
-
Carl Johan +
-
Chalmer Lowe
-
Chang She
-
Charles David +
-
Cheuk Ting Ho
-
Chris
-
Chris Roberts +
-
Christopher Whelan
-
Chu Qing Hao +
-
Da Cheezy Mobsta +
-
Damini Satya
-
Daniel Himmelstein
-
Daniel Saxton +
-
Darcy Meyer +
-
DataOmbudsman
-
David Arcos
-
David Krych
-
Dean Langsam +
-
Diego Argueta +
-
Diego Torres +
-
Dobatymo +
-
Doug Latornell +
-
Dr. Irv
-
Dylan Dmitri Gray +
-
Eric Boxer +
-
Eric Chea
-
Erik +
-
Erik Nilsson +
-
Fabian Haase +
-
Fabian Retkowski
-
Fabien Aulaire +
-
Fakabbir Amin +
-
Fei Phoon +
-
Fernando Margueirat +
-
Florian Müller +
-
Fábio Rosado +
-
Gabe Fernando
-
Gabriel Reid +
-
Giftlin Rajaiah
-
Gioia Ballin +
-
Gjelt
-
Gosuke Shibahara +
-
Graham Inggs
-
Guillaume Gay
-
Guillaume Lemaitre +
-
Hannah Ferchland
-
Haochen Wu
-
Hubert +
-
HubertKl +
-
HyunTruth +
-
Iain Barr
-
Ignacio Vergara Kausel +
-
Irv Lustig +
-
IsvenC +
-
Jacopo Rota
-
Jakob Jarmar +
-
James Bourbeau +
-
James Myatt +
-
James Winegar +
-
Jan Rudolph
-
Jared Groves +
-
Jason Kiley +
-
Javad Noorbakhsh +
-
Jay Offerdahl +
-
Jeff Reback
-
Jeongmin Yu +
-
Jeremy Schendel
-
Jerod Estapa +
-
Jesper Dramsch +
-
Jim Jeon +
-
Joe Jevnik
-
Joel Nothman
-
Joel Ostblom +
-
Jordi Contestí
-
Jorge López Fueyo +
-
Joris Van den Bossche
-
Jose Quinones +
-
Jose Rivera-Rubio +
-
Josh
-
Jun +
-
Justin Zheng +
-
Kaiqi Dong +
-
Kalyan Gokhale
-
Kang Yoosam +
-
Karl Dunkle Werner +
-
Karmanya Aggarwal +
-
Kevin Markham +
-
Kevin Sheppard
-
Kimi Li +
-
Koustav Samaddar +
-
Krishna +
-
Kristian Holsheimer +
-
Ksenia Gueletina +
-
Kyle Prestel +
-
LJ +
-
LeakedMemory +
-
Li Jin +
-
Licht Takeuchi
-
Luca Donini +
-
Luciano Viola +
-
Mak Sze Chun +
-
Marc Garcia
-
Marius Potgieter +
-
Mark Sikora +
-
Markus Meier +
-
Marlene Silva Marchena +
-
Martin Babka +
-
MatanCohe +
-
Mateusz Woś +
-
Mathew Topper +
-
Matt Boggess +
-
Matt Cooper +
-
Matt Williams +
-
Matthew Gilbert
-
Matthew Roeschke
-
Max Kanter
-
Michael Odintsov
-
Michael Silverstein +
-
Michael-J-Ward +
-
Mickaël Schoentgen +
-
Miguel Sánchez de León Peque +
-
Ming Li
-
Mitar
-
Mitch Negus
-
Monson Shao +
-
Moonsoo Kim +
-
Mortada Mehyar
-
Myles Braithwaite
-
Nehil Jain +
-
Nicholas Musolino +
-
Nicolas Dickreuter +
-
Nikhil Kumar Mengani +
-
Nikoleta Glynatsi +
-
Ondrej Kokes
-
Pablo Ambrosio +
-
Pamela Wu +
-
Parfait G +
-
Patrick Park +
-
Paul
-
Paul Ganssle
-
Paul Reidy
-
Paul van Mulbregt +
-
Phillip Cloud
-
Pietro Battiston
-
Piyush Aggarwal +
-
Prabakaran Kumaresshan +
-
Pulkit Maloo
-
Pyry Kovanen
-
Rajib Mitra +
-
Redonnet Louis +
-
Rhys Parry +
-
Rick +
-
Robin
-
Roei.r +
-
RomainSa +
-
Roman Imankulov +
-
Roman Yurchak +
-
Ruijing Li +
-
Ryan +
-
Ryan Nazareth +
-
Rüdiger Busche +
-
SEUNG HOON, SHIN +
-
Sandrine Pataut +
-
Sangwoong Yoon
-
Santosh Kumar +
-
Saurav Chakravorty +
-
Scott McAllister +
-
Sean Chan +
-
Shadi Akiki +
-
Shengpu Tang +
-
Shirish Kadam +
-
Simon Hawkins +
-
Simon Riddell +
-
Simone Basso
-
Sinhrks
-
Soyoun(Rose) Kim +
-
Srinivas Reddy Thatiparthy (శ్రీనివాస్ రెడ్డి తాటిపర్తి) +
-
Stefaan Lippens +
-
Stefano Cianciulli
-
Stefano Miccoli +
-
Stephen Childs
-
Stephen Pascoe
-
Steve Baker +
-
Steve Cook +
-
Steve Dower +
-
Stéphan Taljaard +
-
Sumin Byeon +
-
Sören +
-
Tamas Nagy +
-
Tanya Jain +
-
Tarbo Fukazawa
-
Thein Oo +
-
Thiago Cordeiro da Fonseca +
-
Thierry Moisan
-
Thiviyan Thanapalasingam +
-
Thomas Lentali +
-
Tim D. Smith +
-
Tim Swast
-
Tom Augspurger
-
Tomasz Kluczkowski +
-
Tony Tao +
-
Triple0 +
-
Troels Nielsen +
-
Tuhin Mahmud +
-
Tyler Reddy +
-
Uddeshya Singh
-
Uwe L. Korn +
-
Vadym Barda +
-
Varad Gunjal +
-
Victor Maryama +
-
Victor Villas
-
Vincent La
-
Vitória Helena +
-
Vu Le
-
Vyom Jain +
-
Weiwen Gu +
-
Wenhuan
-
Wes Turner
-
Wil Tan +
-
William Ayd
-
Yeojin Kim +
-
Yitzhak Andrade +
-
Yuecheng Wu +
-
Yuliya Dovzhenko +
-
Yury Bayda +
-
Zac Hatfield-Dodds +
-
aberres +
-
aeltanawy +
-
ailchau +
-
alimcmaster1
-
alphaCTzo7G +
-
amphy +
-
araraonline +
-
azure-pipelines[bot] +
-
benarthur91 +
-
bk521234 +
-
cgangwar11 +
-
chris-b1
-
cxl923cc +
-
dahlbaek +
-
dannyhyunkim +
-
darke-spirits +
-
david-liu-brattle-1
-
davidmvalente +
-
deflatSOCO
-
doosik_bae +
-
dylanchase +
-
eduardo naufel schettino +
-
euri10 +
-
evangelineliu +
-
fengyqf +
-
fjdiod
-
fl4p +
-
fleimgruber +
-
gfyoung
-
h-vetinari
-
harisbal +
-
henriqueribeiro +
-
himanshu awasthi
-
hongshaoyang +
-
igorfassen +
-
jalazbe +
-
jbrockmendel
-
jh-wu +
-
justinchan23 +
-
louispotok
-
marcosrullan +
-
miker985
-
nicolab100 +
-
nprad
-
nsuresh +
-
ottiP
-
pajachiet +
-
raguiar2 +
-
ratijas +
-
realead +
-
robbuckley +
-
saurav2608 +
-
sideeye +
-
ssikdar1
-
svenharris +
-
syutbai +
-
testvinder +
-
thatneat
-
tmnhat2001
-
tomascassidy +
-
tomneep
-
topper-123
-
vkk800 +
-
winlu +
-
ym-pett +
-
yrhooke +
-
ywpark1 +
-
zertrin
-
zhezherun +
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 地球OL攻略 —— 某应届生求职总结
· 提示词工程——AI应用必不可少的技术
· 字符编码:从基础到乱码解决
· Open-Sora 2.0 重磅开源!
2023-06-26 Bert Pytorch 源码分析:五、模型架构简图
2023-06-26 Bert Pytorch 源码分析:四、编解码器
2023-06-26 Bert Pytorch 源码分析:三、Transformer块
2020-06-26 PythonGuru 中文系列教程·翻译完成