0.25.0 (2019年7月18日) 新增內容#
警告
從 0.25.x 系列版本開始,pandas 僅支援 Python 3.5.3 及以上版本。詳情請參閱放棄 Python 2.7。
警告
未來版本中,最低支援的 Python 版本將提升至 3.6。
警告
已完全移除 Panel。對於 N 維標籤資料結構,請使用 xarray。
警告
read_pickle() 和 read_msgpack() 僅保證向後相容至 pandas 版本 0.20.3 (GH 27082)。
這是 pandas 0.25.0 中的更改。如需包含其他 pandas 版本的完整變更日誌,請參閱 釋出說明。
增強功能#
帶重新命名的 GroupBy 聚合#
pandas 為在特定列上應用多個聚合函式時命名輸出列添加了特殊的 groupby 行為,稱為“命名聚合”(named aggregation) (GH 18366, GH 26512)。
In [1]: animals = pd.DataFrame({'kind': ['cat', 'dog', 'cat', 'dog'],
...: 'height': [9.1, 6.0, 9.5, 34.0],
...: 'weight': [7.9, 7.5, 9.9, 198.0]})
...:
In [2]: animals
Out[2]:
kind height weight
0 cat 9.1 7.9
1 dog 6.0 7.5
2 cat 9.5 9.9
3 dog 34.0 198.0
In [3]: animals.groupby("kind").agg(
...: min_height=pd.NamedAgg(column='height', aggfunc='min'),
...: max_height=pd.NamedAgg(column='height', aggfunc='max'),
...: average_weight=pd.NamedAgg(column='weight', aggfunc="mean"),
...: )
...:
Out[3]:
min_height max_height average_weight
kind
cat 9.1 9.5 8.90
dog 6.0 34.0 102.75
將所需的列名作為 **kwargs 傳遞給 .agg。 **kwargs 的值應為元組,其中第一個元素是列選擇,第二個元素是要應用的聚合函式。pandas 提供了 pandas.NamedAgg 命名元組,以更清晰地表示函式引數,但也接受普通元組。
In [4]: animals.groupby("kind").agg(
...: min_height=('height', 'min'),
...: max_height=('height', 'max'),
...: average_weight=('weight', 'mean'),
...: )
...:
Out[4]:
min_height max_height average_weight
kind
cat 9.1 9.5 8.90
dog 6.0 34.0 102.75
命名聚合是已棄用的“字典巢狀字典”方法來命名列特定聚合輸出的推薦替代方案 (棄用重新命名時使用字典的 groupby.agg())。
Series groupby 物件現在也提供了類似的方法。由於不需要列選擇,因此值只需是函式即可。
In [5]: animals.groupby("kind").height.agg(
...: min_height="min",
...: max_height="max",
...: )
...:
Out[5]:
min_height max_height
kind
cat 9.1 9.5
dog 6.0 34.0
這種聚合方式是傳遞字典到 Series groupby 聚合時已棄用行為的推薦替代方案 (棄用重新命名時使用字典的 groupby.agg())。
更多資訊請參閱 命名聚合。
多個 Lambda 函式的 GroupBy 聚合#
現在可以將多個 lambda 函式提供給 GroupBy.agg 中的類列表聚合 (GH 26430)。
In [6]: animals.groupby('kind').height.agg([
...: lambda x: x.iloc[0], lambda x: x.iloc[-1]
...: ])
...:
Out[6]:
<lambda_0> <lambda_1>
kind
cat 9.1 9.5
dog 6.0 34.0
In [7]: animals.groupby('kind').agg([
...: lambda x: x.iloc[0] - x.iloc[1],
...: lambda x: x.iloc[0] + x.iloc[1]
...: ])
...:
Out[7]:
height weight
<lambda_0> <lambda_1> <lambda_0> <lambda_1>
kind
cat -0.4 18.6 -2.0 17.8
dog -28.0 40.0 -190.5 205.5
以前,這會引發 SpecificationError。
MultiIndex 的更好 repr#
現在列印 MultiIndex 例項時會顯示每行的元組,並確保元組項垂直對齊,因此更容易理解 MultiIndex 的結構。( GH 13480)
repr 現在看起來是這樣的:
In [8]: pd.MultiIndex.from_product([['a', 'abc'], range(500)])
Out[8]:
MultiIndex([( 'a', 0),
( 'a', 1),
( 'a', 2),
( 'a', 3),
( 'a', 4),
( 'a', 5),
( 'a', 6),
( 'a', 7),
( 'a', 8),
( 'a', 9),
...
('abc', 490),
('abc', 491),
('abc', 492),
('abc', 493),
('abc', 494),
('abc', 495),
('abc', 496),
('abc', 497),
('abc', 498),
('abc', 499)],
length=1000)
以前,輸出 MultiIndex 會列印 MultiIndex 的所有 levels 和 codes,這在視覺上不美觀,並且使輸出更難導航。例如(限制範圍為 5):
In [1]: pd.MultiIndex.from_product([['a', 'abc'], range(5)])
Out[1]: MultiIndex(levels=[['a', 'abc'], [0, 1, 2, 3]],
...: codes=[[0, 0, 0, 0, 1, 1, 1, 1], [0, 1, 2, 3, 0, 1, 2, 3]])
在新的 repr 中,如果行數小於 options.display.max_seq_items(預設為 100 項),則會顯示所有值。如果輸出寬度大於 options.display.width(預設為 80 個字元),則會水平截斷。
Series 和 DataFrame 的更短截斷 repr#
當前,pandas 的預設顯示選項確保當 Series 或 DataFrame 的行數超過 60 行時,其 repr 會截斷為最多 60 行(display.max_rows 選項)。但是,這仍然會佔用大部分垂直螢幕空間。因此,引入了一個新的選項 display.min_rows,預設為 10,它決定了截斷 repr 中顯示的行數。
對於小型 Series 或 DataFrame,最多顯示
max_rows行(預設為 60)。對於長度大於
max_rows的大型 Series 或 DataFrame,僅顯示min_rows行(預設為 10,即前 5 行和後 5 行)。
這個雙選項允許仍然檢視相對較小物件的完整內容(例如,df.head(20) 顯示所有 20 行),同時為大型物件提供簡短的 repr。
要恢復之前單一閾值的行為,請將 pd.options.display.min_rows = None 設定為 None。
JSON 規範化支援 max_level 引數#
json_normalize() 將提供的輸入字典規範化到所有巢狀級別。新的 max_level 引數提供了對結束規範化的級別的更多控制 (GH 23843)。
repr 現在看起來是這樣的:
from pandas.io.json import json_normalize
data = [{
'CreatedBy': {'Name': 'User001'},
'Lookup': {'TextField': 'Some text',
'UserField': {'Id': 'ID001', 'Name': 'Name001'}},
'Image': {'a': 'b'}
}]
json_normalize(data, max_level=1)
Series.explode 將列表類值拆分為行#
Series 和 DataFrame 獲得了 DataFrame.explode() 方法,用於將列表類轉換為單獨的行。更多資訊請參閱文件中關於“展平列表類列”的 章節 (GH 16538, GH 10511)。
這是一個典型的用例。您有一個列中包含逗號分隔的字串。
In [9]: df = pd.DataFrame([{'var1': 'a,b,c', 'var2': 1},
...: {'var1': 'd,e,f', 'var2': 2}])
...:
In [10]: df
Out[10]:
var1 var2
0 a,b,c 1
1 d,e,f 2
現在可以使用鏈式操作輕鬆建立長格式 DataFrame。
In [11]: df.assign(var1=df.var1.str.split(',')).explode('var1')
Out[11]:
var1 var2
0 a 1
0 b 1
0 c 1
1 d 2
1 e 2
1 f 2
其他增強功能#
DataFrame.plot()的關鍵字logy、logx和loglog現在可以接受值'sym'用於 symlog 縮放。(GH 24867)在使用
to_datetime()解析日期時間時,添加了對 ISO 週年份格式(‘%G-%V-%u’)的支援 (GH 16607)。現在,
DataFrame和Series的索引可以接受零維np.ndarray(GH 24919)。Timestamp.replace()現在支援fold引數,以消除 DST 轉換時間的歧義 (GH 25017)。DataFrame.at_time()和Series.at_time()現在支援帶時區的datetime.time物件 (GH 24043)。DataFrame.pivot_table()現在接受一個observed引數,該引數會傳遞給底層對DataFrame.groupby()的呼叫,以加速對分類資料進行分組。(GH 24923)。Series.str現在獲得了Series.str.casefold()方法,用於移除字串中所有的大小寫區分 (GH 25405)。DataFrame.set_index()現在可以用於abc.Iterator的例項,前提是它們的輸出長度與呼叫框架相同 (GH 22484, GH 24984)。DatetimeIndex.union()現在支援sort引數。sort 引數的行為與Index.union()的行為一致 (GH 24994)。RangeIndex.union()現在支援sort引數。如果sort=False,則始終返回一個未排序的Int64Index。sort=None是預設值,如果可能,則返回一個單調遞增的RangeIndex,否則返回一個已排序的Int64Index(GH 24471)。TimedeltaIndex.intersection()現在也支援sort關鍵字 (GH 24471)。DataFrame.rename()現在支援errors引數,以在嘗試重新命名不存在的鍵時引發錯誤 (GH 13473)。RangeIndex獲得了start、stop和step屬性 (GH 25710)。現在支援將
datetime.timezone物件作為時區方法和建構函式的引數 (GH 25065)。DataFrame.query()和DataFrame.eval()現在支援使用反引號引用列名,以引用包含空格的名稱 (GH 6508)。merge_asof()現在會為類別合併鍵不相等的情況提供更清晰的錯誤訊息 (GH 26136)。Rolling()支援指數(或泊松)視窗型別 (GH 21303)。缺少必需匯入的錯誤訊息現在包含原始匯入錯誤的文字 (GH 23868)。
DatetimeIndex和TimedeltaIndex現在有一個mean方法 (GH 24757)。DataFrame.describe()現在將整數百分位數格式化為不帶小數點的形式 (GH 26660)。添加了對使用
read_spss()讀取 SPSS .sav 檔案的支援 (GH 26537)。添加了新的選項
plotting.backend,以便能夠選擇一個不同於現有matplotlib的繪圖後端。使用pandas.set_option('plotting.backend', '<backend-module>'),其中<backend-module>是實現 pandas 繪圖 API 的庫 (GH 14130)。pandas.offsets.BusinessHour支援多個營業時間間隔 (GH 15481)。read_excel()現在可以透過engine='openpyxl'引數使用openpyxl讀取 Excel 檔案。這將在未來版本中成為預設設定 (GH 11499)。pandas.io.excel.read_excel()支援讀取 OpenDocument 表格。指定engine='odf'即可啟用。更多詳情請參閱 IO 使用者指南 (GH 9070)。Interval、IntervalIndex和IntervalArray獲得了is_empty屬性,用於指示給定的區間是否為空 (GH 27219)。
向後不相容的 API 更改#
使用帶 UTC 偏移量的日期字串進行索引#
以前,使用帶 UTC 偏移量的日期字串索引 DataFrame 或 Series 會忽略 UTC 偏移量。現在,索引會尊重 UTC 偏移量。 (GH 24076, GH 16785)
In [12]: df = pd.DataFrame([0], index=pd.DatetimeIndex(['2019-01-01'], tz='US/Pacific'))
In [13]: df
Out[13]:
0
2019-01-01 00:00:00-08:00 0
先前行為:
In [3]: df['2019-01-01 00:00:00+04:00':'2019-01-01 01:00:00+04:00']
Out[3]:
0
2019-01-01 00:00:00-08:00 0
新行為:
In [14]: df['2019-01-01 12:00:00+04:00':'2019-01-01 13:00:00+04:00']
Out[14]:
0
2019-01-01 00:00:00-08:00 0
從 levels 和 codes 構建 MultiIndex#
以前允許使用 NaN levels 或 codes 值 < -1 構建 MultiIndex。現在,不允許使用 codes 值 < -1 進行構建,並且 NaN levels 的相應 codes 將被重新分配為 -1。(GH 19387)
先前行為:
In [1]: pd.MultiIndex(levels=[[np.nan, None, pd.NaT, 128, 2]],
...: codes=[[0, -1, 1, 2, 3, 4]])
...:
Out[1]: MultiIndex(levels=[[nan, None, NaT, 128, 2]],
codes=[[0, -1, 1, 2, 3, 4]])
In [2]: pd.MultiIndex(levels=[[1, 2]], codes=[[0, -2]])
Out[2]: MultiIndex(levels=[[1, 2]],
codes=[[0, -2]])
新行為:
In [15]: pd.MultiIndex(levels=[[np.nan, None, pd.NaT, 128, 2]],
....: codes=[[0, -1, 1, 2, 3, 4]])
....:
Out[15]:
MultiIndex([(nan,),
(nan,),
(nan,),
(nan,),
(128,),
( 2,)],
)
In [16]: pd.MultiIndex(levels=[[1, 2]], codes=[[0, -2]])
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
Cell In[16], line 1
----> 1 pd.MultiIndex(levels=[[1, 2]], codes=[[0, -2]])
File ~/work/pandas/pandas/pandas/core/indexes/multi.py:335, in MultiIndex.__new__(cls, levels, codes, sortorder, names, copy, name, verify_integrity)
332 result.sortorder = sortorder
334 if verify_integrity:
--> 335 new_codes = result._verify_integrity()
336 result._codes = new_codes
338 result._reset_identity()
File ~/work/pandas/pandas/pandas/core/indexes/multi.py:419, in MultiIndex._verify_integrity(self, codes, levels, levels_to_verify)
413 raise ValueError(
414 f"On level {i}, code max ({level_codes.max()}) >= length of "
415 f"level ({len(level)}). NOTE: this index is in an "
416 "inconsistent state"
417 )
418 if len(level_codes) and level_codes.min() < -1:
--> 419 raise ValueError(f"On level {i}, code value ({level_codes.min()}) < -1")
420 if not level.is_unique:
421 raise ValueError(
422 f"Level values must be unique: {list(level)} on level {i}"
423 )
ValueError: On level 0, code value (-2) < -1
對 DataFrame 使用 GroupBy.apply 只會評估第一個組一次#
DataFrameGroupBy.apply() 的實現以前會一致地對第一個組評估兩次提供的函式,以推斷是否可以安全地使用快速程式碼路徑。特別是對於具有副作用的函式,這是一種不期望的行為,並且可能導致意外。(GH 2936, GH 2656, GH 7739, GH 10519, GH 12155, GH 20084, GH 21417)
現在每個組只評估一次。
In [17]: df = pd.DataFrame({"a": ["x", "y"], "b": [1, 2]})
In [18]: df
Out[18]:
a b
0 x 1
1 y 2
In [19]: def func(group):
....: print(group.name)
....: return group
....:
先前行為:
In [3]: df.groupby('a').apply(func)
x
x
y
Out[3]:
a b
0 x 1
1 y 2
新行為:
In [3]: df.groupby('a').apply(func)
x
y
Out[3]:
a b
0 x 1
1 y 2
連線稀疏值#
當傳入值是稀疏的 DataFrame 時,concat() 現在會返回一個具有稀疏值的 Series 或 DataFrame,而不是 SparseDataFrame (GH 25702)。
In [20]: df = pd.DataFrame({"A": pd.arrays.SparseArray([0, 1])})
先前行為:
In [2]: type(pd.concat([df, df]))
pandas.core.sparse.frame.SparseDataFrame
新行為:
In [21]: type(pd.concat([df, df]))
Out[21]: pandas.DataFrame
這現在與 concat 對具有稀疏值的 Series 的現有行為一致。當所有值都是 SparseDataFrame 的例項時,concat() 將繼續返回 SparseDataFrame。
此更改還會影響內部使用 concat() 的例程,例如 get_dummies(),後者現在在所有情況下都返回一個 DataFrame(以前,如果所有列都被虛擬編碼,則返回 SparseDataFrame,否則返回 DataFrame)。
向 concat() 提供任何 SparseSeries 或 SparseDataFrame 將像以前一樣導致返回 SparseSeries 或 SparseDataFrame。
.str 訪問器執行更嚴格的型別檢查#
由於缺乏更精細的資料型別,Series.str 到目前為止只檢查資料是否為 object 資料型別。現在,Series.str 將推斷 Series 內部的資料型別;特別是,僅包含 'bytes' 的資料將引發異常(除了 Series.str.decode()、Series.str.get()、Series.str.len()、Series.str.slice()),請參閱 GH 23163、GH 23011、GH 23551。
先前行為:
In [1]: s = pd.Series(np.array(['a', 'ba', 'cba'], 'S'), dtype=object)
In [2]: s
Out[2]:
0 b'a'
1 b'ba'
2 b'cba'
dtype: object
In [3]: s.str.startswith(b'a')
Out[3]:
0 True
1 False
2 False
dtype: bool
新行為:
In [22]: s = pd.Series(np.array(['a', 'ba', 'cba'], 'S'), dtype=object)
In [23]: s
Out[23]:
0 b'a'
1 b'ba'
2 b'cba'
dtype: object
In [24]: s.str.startswith(b'a')
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
Cell In[24], line 1
----> 1 s.str.startswith(b'a')
File ~/work/pandas/pandas/pandas/core/strings/accessor.py:141, in forbid_nonstring_types.<locals>._forbid_nonstring_types.<locals>.wrapper(self, *args, **kwargs)
136 if self._inferred_dtype not in allowed_types:
137 msg = (
138 f"Cannot use .str.{func_name} with values of "
139 f"inferred dtype '{self._inferred_dtype}'."
140 )
--> 141 raise TypeError(msg)
142 return func(self, *args, **kwargs)
TypeError: Cannot use .str.startswith with values of inferred dtype 'bytes'.
GroupBy 操作會保留 Categorical 資料型別#
以前,在 groupby 操作中,除 groupby 鍵之外的分類列會被轉換為 object 資料型別。pandas 現在將保留這些資料型別。(GH 18502)
In [25]: cat = pd.Categorical(["foo", "bar", "bar", "qux"], ordered=True)
In [26]: df = pd.DataFrame({'payload': [-1, -2, -1, -2], 'col': cat})
In [27]: df
Out[27]:
payload col
0 -1 foo
1 -2 bar
2 -1 bar
3 -2 qux
In [28]: df.dtypes
Out[28]:
payload int64
col category
dtype: object
之前的行為:
In [5]: df.groupby('payload').first().col.dtype
Out[5]: dtype('O')
新行為:
In [29]: df.groupby('payload').first().col.dtype
Out[29]: CategoricalDtype(categories=['bar', 'foo', 'qux'], ordered=True, categories_dtype=str)
不相容的 Index 型別並集#
在執行不相容資料型別物件之間的 Index.union() 操作時,結果將是一個 object 資料型別的基本 Index。此行為適用於之前被禁止的 Index 物件之間的並集。現在,在執行並集操作之前會評估空 Index 物件的 dtype,而不是簡單地返回另一個 Index 物件。現在可以認為 Index.union() 是可交換的,即 A.union(B) == B.union(A) (GH 23525)。
先前行為:
In [1]: pd.period_range('19910905', periods=2).union(pd.Int64Index([1, 2, 3]))
...
ValueError: can only call with other PeriodIndex-ed objects
In [2]: pd.Index([], dtype=object).union(pd.Index([1, 2, 3]))
Out[2]: Int64Index([1, 2, 3], dtype='int64')
新行為:
In [3]: pd.period_range('19910905', periods=2).union(pd.Int64Index([1, 2, 3]))
Out[3]: Index([1991-09-05, 1991-09-06, 1, 2, 3], dtype='object')
In [4]: pd.Index([], dtype=object).union(pd.Index([1, 2, 3]))
Out[4]: Index([1, 2, 3], dtype='object')
請注意,整數和浮點數資料型別的索引被認為是“相容”的。整數值將被強制轉換為浮點數,這可能會導致精度損失。更多資訊請參閱 Index 物件的集合操作。
DataFrame GroupBy ffill/bfill 不再返回組標籤#
DataFrameGroupBy 的 ffill、bfill、pad 和 backfill 方法以前會將組標籤包含在返回值中,這與其他 groupby 轉換不一致。現在只返回填充後的值。(GH 21521)
In [30]: df = pd.DataFrame({"a": ["x", "y"], "b": [1, 2]})
In [31]: df
Out[31]:
a b
0 x 1
1 y 2
先前行為:
In [3]: df.groupby("a").ffill()
Out[3]:
a b
0 x 1
1 y 2
新行為:
In [32]: df.groupby("a").ffill()
Out[32]:
b
0 1
1 2
對空的 Categorical / object 列呼叫 DataFrame describe 將返回 top 和 freq#
當使用空的 categorical / object 列呼叫 DataFrame.describe() 時,之前會省略“top”和“freq”列,這與非空列的輸出不一致。現在,“top”和“freq”列將始終包含,對於空 DataFrame 的情況,將使用 numpy.nan (GH 26397)。
In [33]: df = pd.DataFrame({"empty_col": pd.Categorical([])})
In [34]: df
Out[34]:
Empty DataFrame
Columns: [empty_col]
Index: []
先前行為:
In [3]: df.describe()
Out[3]:
empty_col
count 0
unique 0
新行為:
In [35]: df.describe()
Out[35]:
empty_col
count 0
unique 0
top NaN
freq NaN
__str__ 方法現在呼叫 __repr__ 而不是反之#
pandas 迄今為止主要在其 pandas 物件的 __str__/__unicode__/__bytes__ 方法中定義字串表示形式,並從 __repr__ 方法呼叫 __str__,如果找不到特定的 __repr__ 方法。Python 3 不需要這樣做。在 pandas 0.25 中,pandas 物件的字串表示形式現在通常定義在 __repr__ 中,並且對 __str__ 的呼叫通常會傳遞給 __repr__,如果不存在特定的 __str__ 方法,這符合 Python 的標準。此更改對 pandas 的直接使用是向後相容的,但如果您繼承 pandas 物件並為您的子類提供特定的 __str__/__repr__ 方法,則可能需要調整您的 __str__/__repr__ 方法 (GH 26495)。
使用 Interval 物件索引 IntervalIndex#
對 IntervalIndex 的索引方法已修改為僅對 Interval 查詢要求精確匹配。 IntervalIndex 方法以前會匹配任何重疊的 Interval。對於標量點(例如,使用整數進行查詢)的行為保持不變(GH 16316)。
In [36]: ii = pd.IntervalIndex.from_tuples([(0, 4), (1, 5), (5, 8)])
In [37]: ii
Out[37]: IntervalIndex([(0, 4], (1, 5], (5, 8]], dtype='interval[int64, right]')
“in”運算子(__contains__)現在僅對 IntervalIndex 中的 Intervals 返回精確匹配的 True,而以前對於任何與 IntervalIndex 中的 Interval 重疊的 Interval 都會返回 True。
先前行為:
In [4]: pd.Interval(1, 2, closed='neither') in ii
Out[4]: True
In [5]: pd.Interval(-10, 10, closed='both') in ii
Out[5]: True
新行為:
In [38]: pd.Interval(1, 2, closed='neither') in ii
Out[38]: False
In [39]: pd.Interval(-10, 10, closed='both') in ii
Out[39]: False
與之前返回重疊匹配的位置不同,get_loc() 方法現在僅為 Interval 查詢的精確匹配返回位置。如果找不到精確匹配,將引發 KeyError。
先前行為:
In [6]: ii.get_loc(pd.Interval(1, 5))
Out[6]: array([0, 1])
In [7]: ii.get_loc(pd.Interval(2, 6))
Out[7]: array([0, 1, 2])
新行為:
In [6]: ii.get_loc(pd.Interval(1, 5))
Out[6]: 1
In [7]: ii.get_loc(pd.Interval(2, 6))
---------------------------------------------------------------------------
KeyError: Interval(2, 6, closed='right')
同樣,get_indexer() 和 get_indexer_non_unique() 也將僅為 Interval 查詢的精確匹配返回位置,其中 -1 表示未找到精確匹配。
這些索引更改已擴充套件到使用 IntervalIndex 索引來查詢 Series 或 DataFrame。
In [40]: s = pd.Series(list('abc'), index=ii)
In [41]: s
Out[41]:
(0, 4] a
(1, 5] b
(5, 8] c
dtype: str
使用 [] (__getitem__)或 loc 從 Series 或 DataFrame 中進行選擇,現在僅為 Interval 查詢返回精確匹配。
先前行為:
In [8]: s[pd.Interval(1, 5)]
Out[8]:
(0, 4] a
(1, 5] b
dtype: object
In [9]: s.loc[pd.Interval(1, 5)]
Out[9]:
(0, 4] a
(1, 5] b
dtype: object
新行為:
In [42]: s[pd.Interval(1, 5)]
Out[42]: 'b'
In [43]: s.loc[pd.Interval(1, 5)]
Out[43]: 'b'
類似地,對於非精確匹配,將引發 KeyError,而不是返回重疊匹配。
先前行為:
In [9]: s[pd.Interval(2, 3)]
Out[9]:
(0, 4] a
(1, 5] b
dtype: object
In [10]: s.loc[pd.Interval(2, 3)]
Out[10]:
(0, 4] a
(1, 5] b
dtype: object
新行為:
In [6]: s[pd.Interval(2, 3)]
---------------------------------------------------------------------------
KeyError: Interval(2, 3, closed='right')
In [7]: s.loc[pd.Interval(2, 3)]
---------------------------------------------------------------------------
KeyError: Interval(2, 3, closed='right')
可以使用 overlaps() 方法來建立布林索引器,該索引器可複製之前返回重疊匹配的行為。
新行為:
In [44]: idxr = s.index.overlaps(pd.Interval(2, 3))
In [45]: idxr
Out[45]: array([ True, True, False])
In [46]: s[idxr]
Out[46]:
(0, 4] a
(1, 5] b
dtype: str
In [47]: s.loc[idxr]
Out[47]:
(0, 4] a
(1, 5] b
dtype: str
Series 上的二元 ufunc 現在會進行對齊#
當兩個都是 Series 時,像 numpy.power() 這樣的二元 ufunc 的應用現在會按索引對齊輸入(GH 23293)。
In [48]: s1 = pd.Series([1, 2, 3], index=['a', 'b', 'c'])
In [49]: s2 = pd.Series([3, 4, 5], index=['d', 'c', 'b'])
In [50]: s1
Out[50]:
a 1
b 2
c 3
dtype: int64
In [51]: s2
Out[51]:
d 3
c 4
b 5
dtype: int64
先前行為
In [5]: np.power(s1, s2)
Out[5]:
a 1
b 16
c 243
dtype: int64
新行為
In [52]: np.power(s1, s2)
Out[52]:
a 1.0
b 32.0
c 81.0
d NaN
dtype: float64
這與其他 pandas 中的二元運算(如 Series.add())的行為一致。要保留之前的行為,請在應用 ufunc 之前將另一個 Series 轉換為陣列。
In [53]: np.power(s1, s2.array)
Out[53]:
a 1
b 16
c 243
dtype: int64
Categorical.argsort 現在將缺失值放在末尾#
Categorical.argsort() 現在將缺失值放在陣列末尾,使其與 NumPy 和 pandas 的其餘部分一致(GH 21801)。
In [54]: cat = pd.Categorical(['b', None, 'a'], categories=['a', 'b'], ordered=True)
先前行為
In [2]: cat = pd.Categorical(['b', None, 'a'], categories=['a', 'b'], ordered=True)
In [3]: cat.argsort()
Out[3]: array([1, 2, 0])
In [4]: cat[cat.argsort()]
Out[4]:
[NaN, a, b]
categories (2, object): [a < b]
新行為
In [55]: cat.argsort()
Out[55]: array([2, 0, 1])
In [56]: cat[cat.argsort()]
Out[56]:
['a', 'b', NaN]
Categories (2, str): ['a' < 'b']
將字典列表傳遞給 DataFrame 時保留列順序#
從 Python 3.7 開始,dict 的鍵順序已得到保證。實際上,這自 Python 3.6 起就一直成立。 DataFrame 建構函式現在像處理 OrderedDict 列表一樣處理字典列表,即保留字典的順序。此更改僅在 pandas 在 Python>=3.6 上執行時適用(GH 27309)。
In [57]: data = [
....: {'name': 'Joe', 'state': 'NY', 'age': 18},
....: {'name': 'Jane', 'state': 'KY', 'age': 19, 'hobby': 'Minecraft'},
....: {'name': 'Jean', 'state': 'OK', 'age': 20, 'finances': 'good'}
....: ]
....:
之前的行為:
以前,列是按字典序排序的;
In [1]: pd.DataFrame(data)
Out[1]:
age finances hobby name state
0 18 NaN NaN Joe NY
1 19 NaN Minecraft Jane KY
2 20 good NaN Jean OK
新行為:
現在,列順序與字典鍵的插入順序匹配,從上到下考慮所有記錄。因此,結果 DataFrame 的列順序與之前的 pandas 版本相比發生了變化。
In [58]: pd.DataFrame(data)
Out[58]:
name state age hobby finances
0 Joe NY 18 NaN NaN
1 Jane KY 19 Minecraft NaN
2 Jean OK 20 NaN good
提高了依賴項的最低版本#
由於不再支援 Python 2.7,許多可選依賴項已更新最低版本(GH 25725、GH 24942、GH 25752)。此外,還更新了一些依賴項的最低支援版本(GH 23519、GH 25554)。如果已安裝,我們現在要求
包 |
最低版本 |
必需 |
|---|---|---|
numpy |
1.13.3 |
X |
pytz |
2015.4 |
X |
python-dateutil |
2.6.1 |
X |
bottleneck |
1.2.1 |
|
numexpr |
2.6.2 |
|
pytest (dev) |
4.0.2 |
對於可選庫,一般建議使用最新版本。下表列出了在 pandas 開發過程中始終進行測試的每個庫的最低版本。低於最低測試版本的可選庫可能仍然有效,但未被視為受支援。
包 |
最低版本 |
|---|---|
beautifulsoup4 |
4.6.0 |
fastparquet |
0.2.1 |
gcsfs |
0.2.2 |
lxml |
3.8.0 |
matplotlib |
2.2.2 |
openpyxl |
2.4.8 |
pyarrow |
0.9.0 |
pymysql |
0.7.1 |
pytables |
3.4.2 |
scipy |
0.19.0 |
sqlalchemy |
1.1.4 |
xarray |
0.8.2 |
xlrd |
1.1.0 |
xlsxwriter |
0.9.8 |
xlwt |
1.2.0 |
有關更多資訊,請參閱Dependencies和Optional dependencies。
其他 API 更改#
DatetimeTZDtype現在將 pytz 時區標準化為通用的時區例項(GH 24713)Timestamp和Timedelta標量現在分別實現to_numpy()方法,作為Timestamp.to_datetime64()和Timedelta.to_timedelta64()的別名。(GH 24653)Timestamp.strptime()現在將引發NotImplementedError(GH 25016)將
Timestamp與不受支援的物件進行比較現在返回NotImplemented而不是引發TypeError。這意味著不受支援的豐富比較會委託給其他物件,並且現在與 Python 3 中datetime物件的行為一致(GH 24011)修復了
DatetimeIndex.snap()中未保留輸入Index的name的錯誤(GH 25575)DataFrameGroupBy.agg()中的arg引數已重新命名為func(GH 26089)Window.aggregate()中的arg引數已重新命名為func(GH 26372)大多數 pandas 類都有一個
__bytes__方法,該方法用於獲取物件的 python2 風格位元組字串表示形式。此方法已作為刪除 Python2 的一部分被移除(GH 26447)1 級
MultiIndex的.str訪問器已被停用,如有必要,請使用MultiIndex.to_flat_index()(GH 23679)移除了 gtk 包對剪貼簿的支援(GH 26563)
使用不受支援的 Beautiful Soup 4 版本現在將引發
ImportError而不是ValueError(GH 27063)Series.to_excel()和DataFrame.to_excel()在儲存時區感知資料時現在將引發ValueError。(GH 27008,GH 7056)ExtensionArray.argsort()將 NA 值放在排序陣列的末尾。(GH 21801)DataFrame.to_hdf()和Series.to_hdf()在為fixed格式儲存具有擴充套件資料型別的MultiIndex時,現在將引發NotImplementedError。(GH 7775)在
read_csv()中傳遞重複的names現在將引發ValueError(GH 17346)
棄用#
稀疏子類#
SparseSeries 和 SparseDataFrame 子類已棄用。它們的功能可以透過具有稀疏值的 Series 或 DataFrame 來更好地提供。
以前的方式
df = pd.SparseDataFrame({"A": [0, 0, 1, 2]})
df.dtypes
新的方式
In [59]: df = pd.DataFrame({"A": pd.arrays.SparseArray([0, 0, 1, 2])})
In [60]: df.dtypes
Out[60]:
A Sparse[int64, 0]
dtype: object
這兩種方法的使用記憶體量是相同的(GH 19239)。
msgpack 格式#
msgpack 格式自 0.25 版本起已棄用,並將在未來版本中移除。建議使用 pyarrow 來進行 pandas 物件的線上傳輸。(GH 27084)
其他棄用#
已棄用的
.ix[]索引器現在引發更可見的FutureWarning而不是DeprecationWarning(GH 26438)。棄用了
pandas.to_timedelta()、pandas.Timedelta()和pandas.TimedeltaIndex()的units引數中的units=M(月)和units=Y(年)引數(GH 16344)pandas.concat()已棄用join_axes關鍵字。改為在結果上或在輸入上使用DataFrame.reindex()或DataFrame.reindex_like()(GH 21951)SparseArray.values屬性已棄用。可以使用np.asarray(...)或SparseArray.to_dense()方法代替(GH 26421)。函式
pandas.to_datetime()和pandas.to_timedelta()已棄用box關鍵字。改為使用to_numpy()或Timestamp.to_datetime64()或Timedelta.to_timedelta64()。(GH 24416)DataFrame.compound()和Series.compound()方法已棄用,將在未來版本中移除(GH 26405)。RangeIndex的內部屬性_start、_stop和_step已棄用。請改用公共屬性start、stop和step(GH 26581)。Series.ftype()、Series.ftypes()和DataFrame.ftypes()方法已棄用,將在未來版本中移除。請改用Series.dtype()和DataFrame.dtypes()(GH 26705)。Series.get_values()、DataFrame.get_values()、Index.get_values()、SparseArray.get_values()和Categorical.get_values()方法已棄用。可以使用np.asarray(..)或to_numpy()代替(GH 19617)。NumPy ufuncs 上的“outer”方法,例如
np.subtract.outer在Series物件上已棄用。首先使用Series.array將輸入轉換為陣列(GH 27186)Timedelta.resolution()已棄用,並由Timedelta.resolution_string()替換。在未來版本中,Timedelta.resolution()的行為將更改為與標準庫datetime.timedelta.resolution相同(GH 21344)read_table()已解除棄用。(GH 25220)Index.dtype_str已棄用。(GH 18262)Series.imag和Series.real已棄用。(GH 18262)Series.put()已棄用。(GH 18262)Index.item()和Series.item()已棄用。(GH 18262)CategoricalDtype中ordered=None的預設值已棄用,改為使用ordered=False。在不同類別型別之間轉換時,必須顯式傳遞ordered=True才能保留。(GH 26336)Index.contains()已棄用。請改用key in index(__contains__)(GH 17753)。DataFrame.get_dtype_counts()已棄用。(GH 18262)Categorical.ravel()將返回一個Categorical而不是np.ndarray(GH 27199)
移除先前版本的棄用/更改#
移除了
read_excel()中之前棄用的sheetname關鍵字(GH 16442、GH 20938)移除了之前棄用的
TimeGrouper(GH 16942)移除了
read_excel()中之前棄用的parse_cols關鍵字(GH 16488)移除了之前棄用的
pd.options.html.border(GH 16970)移除了之前棄用的
convert_objects(GH 11221)移除了之前棄用的
DataFrame和Series的select方法(GH 17633)移除了
rename_categories()中Series被視為列表類之前的棄用行為(GH 17982)移除了之前棄用的
DataFrame.reindex_axis和Series.reindex_axis(GH 17842)移除了使用
Series.rename_axis()或DataFrame.rename_axis()修改列或索引標籤之前的棄用行為(GH 17842)移除了
read_html()、read_csv()和DataFrame.to_csv()中之前棄用的tupleize_cols關鍵字引數(GH 17877、GH 17820)移除了之前棄用的
DataFrame.from.csv和Series.from_csv(GH 17812)移除了
DataFrame.where()和DataFrame.mask()中之前棄用的raise_on_error關鍵字引數(GH 17744)移除了
astype中之前棄用的ordered和categories關鍵字引數(GH 17742)移除了之前棄用的
cdate_range(GH 17691)移除了
SeriesGroupBy.nth()中dropna關鍵字引數的True選項(GH 17493)移除了
Series.take()和DataFrame.take()中之前棄用的convert關鍵字引數(GH 17352)移除了之前棄用的
datetime.date物件與算術運算之間的互動行為(GH 21152)
效能改進#
顯著加速了
SparseArray的初始化,這對大多數操作都有益,修復了 v0.20.0 中引入的效能迴歸(GH 24985)當輸出包含任何字串或非原生位元組序的列時,
DataFrame.to_stata()現在更快(GH 25045)改進了
Series.searchsorted()的效能。當 dtype 是 int8/int16/int32 且搜尋的鍵在 dtype 的整數範圍內時,速度提升尤為顯著(GH 22034)改進了
GroupBy.quantile()的效能(GH 20405)提高了對 `RangeIndex` 的切片和其他選定操作的效能(GH 26565, GH 26617, GH 26722)
`RangeIndex` 現在執行標準查詢,而無需例項化實際的雜湊表,從而節省記憶體(GH 16685)
透過更快的標記化和對小浮點數的更快速解析,提高了 `read_csv()` 的效能(GH 25784)
透過更快速地解析 N/A 和布林值,提高了 `read_csv()` 的效能(GH 25804)
透過移除轉換為 `MultiIndex`,提高了 `IntervalIndex.is_monotonic`、`IntervalIndex.is_monotonic_increasing` 和 `IntervalIndex.is_monotonic_decreasing` 的效能(GH 24813)
在寫入 datetime dtypes 時,提高了 `DataFrame.to_csv()` 的效能(GH 25708)
透過更快速地解析 `MM/YYYY` 和 `DD/MM/YYYY` 日期時間格式,提高了 `read_csv()` 的效能(GH 25922)
提高了無法儲存 NaN 的 dtypes 的 nanops 效能。對於 `Series.all()` 和 `Series.any()`,加速尤為明顯(GH 25070)
透過對映類別而不是對映所有值,提高了 `Series.map()` 對於分類 series 的字典對映器的效能(GH 23785)
提高了 `IntervalIndex.intersection()` 的效能(GH 24813)
透過更快速地連線日期列,而無需將整數/浮點零和浮點 `NaN` 額外轉換為字串;透過更快地檢查字串是否可能為日期,提高了 `read_csv()` 的效能(GH 25754)
透過移除轉換為 `MultiIndex`,提高了 `IntervalIndex.is_unique` 的效能(GH 24813)
透過重新啟用專用程式碼路徑,恢復了 `DatetimeIndex.__iter__()` 的效能(GH 26702)
在構建至少包含一個 `CategoricalIndex` 級別的 `MultiIndex` 時,提高了效能(GH 22044)
透過移除檢查 `SettingWithCopyWarning` 時所需的垃圾回收,提高了效能(GH 27031)
對於 `to_datetime()`,將 `cache` 引數的預設值更改為 `True`(GH 26043)
在非唯一、單調資料的情況下,提高了 `DatetimeIndex` 和 `PeriodIndex` 的切片效能(GH 27136)。
對於面向索引的資料,提高了 `pd.read_json()` 的效能。(GH 26773)
提高了 `MultiIndex.shape()` 的效能(GH 27384)。
Bug 修復#
分類#
修復了 `DataFrame.at()` 和 `Series.at()` 的錯誤,該錯誤在索引為 `CategoricalIndex` 時會引發異常(GH 20629)
修復了有序 `Categorical`(包含缺失值)與標量比較時出現錯誤的 bug,該錯誤有時會錯誤地返回 `True`(GH 26504)
修復了 `DataFrame.dropna()` 中當 `DataFrame` 具有包含 `Interval` 物件的 `CategoricalIndex` 時,會錯誤地引發 `TypeError` 的 bug(GH 25087)
日期時間型別#
修復了 `to_datetime()` 的 bug,該 bug在呼叫時,如果日期非常遙遠且指定了 `format` 引數,則會引發(錯誤的)`ValueError`,而不是引發 `OutOfBoundsDatetime`(GH 23830)
修復了 `to_datetime()` 的 bug,當呼叫時 `cache=True`,並且 `arg` 包含 `None`、`numpy.nan`、`pandas.NaT` 中的至少兩個不同元素時,會引發 `InvalidIndexError: Reindexing only valid with uniquely valued Index objects`(GH 22305)
修復了 `DataFrame` 和 `Series` 中的 bug,即帶有 `dtype='datetime64[ns]'` 的時區感知資料未被強制轉換為樸素資料(GH 25843)
提高了各種日期時間函式中的 `Timestamp` 型別檢查,以防止在使用子類化的 `datetime` 時出現異常(GH 25851)
修復了 `Series` 和 `DataFrame` repr 中的 bug,其中 `np.datetime64('NaT')` 和 `np.timedelta64('NaT')`(dtype=object)將被表示為 `NaN`(GH 25445)
修復了 `to_datetime()` 中的 bug,當 `error` 設定為 `coerce` 時,該 bug不會將無效引數替換為 `NaT`(GH 26122)
修復了將具有非零月份的 `DateOffset` 新增到 `DatetimeIndex` 中會引發 `ValueError` 的 bug(GH 26258)
修復了 `to_datetime()` 的 bug,當使用 `format='%Y%m%d'` 和 `error='coerce'` 呼叫時,混合了無效日期和 `NaN` 值會導致未處理的 `OverflowError`(GH 25512)
修復了 `isin()` 在 datetimelike 索引上的 bug,`DatetimeIndex`、`TimedeltaIndex` 和 `PeriodIndex` 中的 `levels` 引數被忽略。(GH 26675)
修復了 `to_datetime()` 的 bug,當使用 `format='%Y%m%d'` 呼叫無效的整數日期(長度 >= 6 位)且 `errors='ignore'` 時,會引發 `TypeError`。
修復了將 `PeriodIndex` 與零維 numpy 陣列進行比較時的 bug(GH 26689)
修復了從具有非 ns 單位和超出邊界時間戳的 numpy `datetime64` 陣列構建 `Series` 或 `DataFrame` 時的 bug,該 bug會生成錯誤資料,現在會正確引發 `OutOfBoundsDatetime` 錯誤(GH 26206)。
修復了 `date_range()` 中為非常大或非常小的日期不必要地引發 `OverflowError` 的 bug(GH 26651)
修復了將 `Timestamp` 新增到 `np.timedelta64` 物件時會引發異常而不是返回 `Timestamp` 的 bug(GH 24775)
修復了將包含 `np.datetime64` 物件的零維 numpy 陣列與 `Timestamp` 進行比較時錯誤地引發 `TypeError` 的 bug(GH 26916)
修復了 `to_datetime()` 的 bug,當 `cache=True` 時,並且 `arg` 包含具有不同偏移量的日期時間字串,會引發 `ValueError: Tz-aware datetime.datetime cannot be converted to datetime64 unless utc=True`(GH 26097)
時間差#
修復了 `TimedeltaIndex.intersection()` 中的 bug,對於非單調索引,在某些情況下即使存在交集也返回了一個空的 `Index`(GH 25913)
修復了 `Timedelta` 和 `NaT` 之間比較時引發 `TypeError` 的 bug(GH 26039)
修復了將 `BusinessHour` 新增或減去到 `Timestamp` 時,結果時間落在後續或先前日期的 bug(GH 26381)
修復了將 `TimedeltaIndex` 與零維 numpy 陣列進行比較時的 bug(GH 26689)
時區#
修復了 `DatetimeIndex.to_frame()` 中的 bug,其中時區感知資料會被轉換為時區樸素資料(GH 25809)
修復了 `to_datetime()` 中 `utc=True` 和日期時間字串的 bug,該 bug會將先前解析的 UTC 偏移量應用於後續引數(GH 24992)
修復了 `Timestamp.tz_localize()` 和 `Timestamp.tz_convert()` 不會傳播 `freq` 的 bug(GH 25241)
修復了 `Series.at()` 中設定帶時區的 `Timestamp` 會引發 `TypeError` 的 bug(GH 25506)
修復了 `DataFrame.update()` 中使用時區感知資料更新時會返回時區樸素資料的 bug(GH 25807)
修復了 `to_datetime()` 的 bug,當傳入樸素 `Timestamp` 和具有混合 UTC 偏移量的日期時間字串時,會引發無資訊的 `RuntimeError`(GH 25978)
修復了 `to_datetime()` 中 `unit='ns'` 會刪除解析引數時區資訊的 bug(GH 26168)
修復了 `DataFrame.join()` 中,連線時區感知索引和時區感知列會導致列為 `NaN` 的 bug(GH 26335)
修復了 `date_range()` 中,`ambiguous` 或 `nonexistent` 關鍵字未能分別處理模糊或不存在的開始或結束時間(GH 27088)
修復了 `DatetimeIndex.union()` 在組合時區感知和時區樸素 `DatetimeIndex` 時的 bug(GH 21671)
修復了將 numpy 歸約函式(例如 `numpy.minimum()`)應用於時區感知 `Series` 時的 bug(GH 15552)
數值#
修復了 `to_numeric()` 中大負數處理不當的 bug(GH 24910)
修復了 `to_numeric()` 中,即使 `errors` 不是 `coerce`,數字仍被強制轉換為浮點數的 bug(GH 24910)
修復了 `to_numeric()` 中,允許了 `errors` 的無效值的 bug(GH 26466)
修復了 `format` 中的 bug,其中浮點複數未能以正確的顯示精度和截斷進行格式化(GH 25514)
修復了 `DataFrame.corr()` 和 `Series.corr()` 中錯誤訊息的 bug。增加了使用可呼叫物件(callable)的可能性。(GH 25729)
修復了 `Series.divmod()` 和 `Series.rdivmod()` 中的 bug,該 bug會引發(錯誤的)`ValueError`,而不是返回一對 `Series` 物件作為結果(GH 25557)
當將非數字索引傳遞給需要數字索引的方法(如 `interpolate()`)時,引發了有用的異常。(GH 21662)
修復了 `eval()` 中,當使用標量運算子比較浮點數時(例如:`x < -0.1`)的 bug(GH 25928)
修復了將全布林陣列轉換為整數擴充套件陣列失敗的 bug(GH 25211)
修復了 `divmod` 中,包含零的 `Series` 物件錯誤地引發 `AttributeError` 的 bug(GH 26987)
修復了 `Series` 中,地板除 (`//`) 和 `divmod` 將正數//零填充為 `NaN` 而不是 `Inf` 的不一致性(GH 27321)
轉換#
修復了 `DataFrame.astype()` 中,傳遞列和型別字典時 `errors` 引數被忽略的 bug。(GH 25905)
字串#
修復了 `Series.str` 的幾個方法的 `__name__` 屬性 bug,該屬性被錯誤地設定了(GH 23551)
當將錯誤 dtype 的 `Series` 傳遞給 `Series.str.cat()` 時,改進了錯誤訊息(GH 22722)
Interval#
將 `Interval` 的構造限制為僅限於 `Timestamp` 和 `Timedelta` 端點(GH 23013)
修復了 `Series`/`DataFrame` 在 `IntervalIndex` 中顯示 `NaN`(帶有缺失值)的 bug(GH 25984)
修復了 `IntervalIndex.get_loc()` 中的 bug,該 bug在遞減 `IntervalIndex` 時會錯誤地引發 `KeyError`(GH 25860)
修復了 `Index` 建構函式中的 bug,當傳入混合的閉合 `Interval` 物件時,會引發 `ValueError` 而不是 `object` dtype `Index`(GH 27172)
索引#
改進了呼叫
DataFrame.iloc()時,使用非數字物件列表的異常訊息(GH 25753)。改進了使用長度不同的布林索引器呼叫
.iloc或.loc時的異常訊息(GH 26658)。使用不存在的鍵索引
MultiIndex時,KeyError異常訊息未能顯示原始鍵的錯誤(GH 27250)。使用長度不足的布林索引器進行
.iloc和.loc操作時,未能引發IndexError的錯誤(GH 26658)。在
DataFrame.loc()和Series.loc()中,當使用MultiIndex且鍵的長度小於或等於MultiIndex的級別數時,未能引發KeyError的錯誤(GH 14885)。當要追加的資料包含新列時,
DataFrame.append()產生了一個錯誤的警告,提示未來將丟擲KeyError(GH 22252)。當使用單層
MultiIndex的重索引資料框呼叫DataFrame.to_csv()時,導致了段錯誤(GH 26303)。允許在
DataFrame.query()字串中使用可呼叫區域性引用的關鍵字引數(GH 26426)。修復了使用包含單個缺失標籤的列表索引
MultiIndex級別時出現的KeyError錯誤(GH 27148)。在
MultiIndex中部分匹配Timestamp時,產生AttributeError的錯誤(GH 26944)。在
Categorical和CategoricalIndex中,使用in運算子(__contains)進行Interval值比較時,與Interval中的值不相容的物件進行比較,錯誤地引發了異常(GH 23705)。在具有單個時區感知 datetime64[ns] 列的
DataFrame上使用DataFrame.loc()和DataFrame.iloc()時,錯誤地返回標量而不是Series(GH 27110)。在
CategoricalIndex和Categorical中,當使用in運算子(__contains__)傳入列表時,錯誤地引發了ValueError而不是TypeError(GH 21729)。在
Series中使用時區感知日期時間設定新鍵(__setitem__)時,錯誤地引發了ValueError(GH 12862)。在使用只讀索引器索引
DataFrame.iloc()時出現錯誤(GH 17192)。在
Series中使用時區感知日期時間設定現有元組鍵(__setitem__)時,錯誤地引發了TypeError(GH 20441)。
Missing#
修復了
Series.interpolate()中,如果order引數是必需的但被省略時,誤導性的異常訊息(GH 10633, GH 24014)。修復了在
DataFrame.dropna()中傳遞無效的axis引數時,異常訊息中顯示的類型別不正確的問題(GH 25555)。現在,當
limit不是正整數時,DataFrame.fillna()會丟擲ValueError(GH 27042)。
MultiIndex#
在測試
Timedelta對MultiIndex的成員資格測試時,引發了錯誤的異常(GH 24570)。
IO#
在
DataFrame.to_html()中,值被使用顯示選項截斷,而不是輸出完整內容(GH 17004)。修復了在 Windows 上使用 Python 3 複製 utf-16 字元時,
to_clipboard()中缺失文字的錯誤(GH 25040)。對於
orient='table'的read_json(),當它嘗試預設推斷 dtypes 時存在錯誤,因為 dtypes 已在 JSON 模式中定義(GH 21345)。對於
orient='table'和浮點數索引的read_json(),當它預設推斷索引 dtype 時存在錯誤,因為索引 dtype 已在 JSON 模式中定義(GH 25433)。對於
orient='table'和浮點數字段名稱字串的read_json(),當它將列名型別轉換為Timestamp時存在錯誤,因為列名已在 JSON 模式中定義(GH 25435)。在
json_normalize()中,當 `errors='ignore'` 且輸入資料中存在缺失值時,結果DataFrame中的缺失值被填充為字串"nan"而不是numpy.nan(GH 25468)。DataFrame.to_html()現在在使用classes引數時,如果傳入無效型別,會引發TypeError而不是AssertionError(GH 25608)。在
DataFrame.to_string()和DataFrame.to_latex()中,當使用header關鍵字時,會導致輸出不正確的錯誤(GH 16718)。在 Windows 上使用 Python 3.6+ 時,
read_csv()未能正確解釋 UTF8 編碼的檔名(GH 15086)。改進了
pandas.read_stata()和pandas.io.stata.StataReader在轉換具有缺失值的列時的效能(GH 25772)。在
DataFrame.to_html()中,當四捨五入時,頁首數字會忽略顯示選項(GH 17280)。當使用 PyTables 直接寫入的 HDF5 檔案中的表進行子選擇(透過 `start` 或 `stop` 引數)讀取時,
read_hdf()會因ValueError而失敗(GH 11188)。當
KeyError被引發後,read_hdf()未能正確關閉 store(GH 25766)。改進了 Stata dta 檔案中重複值標籤的失敗解釋,並提出瞭解決方法(GH 25772)。
改進了
pandas.read_stata()和pandas.io.stata.StataReader以讀取 Stata 儲存的格式不正確的 118 格式檔案(GH 25960)。改進了
DataFrame.to_html()中的col_space引數,使其能夠接受字串,以便正確設定 CSS 長度值(GH 25941)。修復了載入包含 URL 中 '#' 字元的 S3 物件時的錯誤(GH 25945)。
向
read_gbq()添加了 `use_bqstorage_api` 引數,以加速下載大型資料幀。此功能需要 `pandas-gbq` 庫的版本 0.10.0 以及 `google-cloud-bigquery-storage` 和 `fastavro` 庫。(GH 26104)。修復了處理數值資料時
DataFrame.to_json()中的記憶體洩漏問題(GH 24889)。在
read_json()中,具有 'Z' 的日期字串未轉換為 UTC 時區的問題(GH 26168)。向
read_csv()添加了 `cache_dates=True` 引數,該引數允許在解析唯一日期時快取它們(GH 25990)。DataFrame.to_excel()現在當呼叫者的維度超出 Excel 的限制時,會引發ValueError(GH 26051)。修復了使用 engine='python' 解析時,BOM 會導致
pandas.read_csv()解析不正確的問題(GH 26545)。read_excel()現在,當輸入是pandas.io.excel.ExcelFile型別並且傳遞了 `engine` 引數時,會引發ValueError,因為pandas.io.excel.ExcelFile已經定義了引擎(GH 26566)。在從
HDFStore中選擇並指定 `where=''` 時出現錯誤(GH 26610)。修復了
DataFrame.to_excel()中,合併單元格內的自定義物件(例如PeriodIndex)未能轉換為 Excel writer 安全型別的錯誤(GH 27006)。在讀取時區感知的
DatetimeIndex時,read_hdf()會引發TypeError(GH 11926)。在
to_msgpack()和read_msgpack()中,對於無效路徑會引發ValueError而不是FileNotFoundError的錯誤(GH 27160)。修復了
DataFrame.to_parquet()中,當資料幀沒有列時會引發ValueError的錯誤(GH 27339)。允許在
read_csv()中解析PeriodDtype列(GH 26934)。
繪圖#
修復了
api.extensions.ExtensionArray無法在 matplotlib 繪圖中使用的錯誤(GH 25587)。修復了
DataFrame.plot()中的錯誤訊息。當向DataFrame.plot()傳遞非數字型別時,改進了錯誤訊息(GH 25481)。在繪製非數字/非 datetime 索引時,刻度標籤位置不正確的錯誤(GH 7612, GH 15912, GH 22334)。
修復了繪製
PeriodIndex時間序列時,如果頻率是頻率規則程式碼的倍數,繪圖會失敗的錯誤(GH 14763)。修復了繪製具有 `datetime.timezone.utc` 時區的
DatetimeIndex時出現的錯誤(GH 17173)。
GroupBy/resample/rolling
在
Resampler.agg()中,當使用時區感知的索引並傳遞函式列表時,會引發OverflowError的錯誤(GH 22660)。在
DataFrameGroupBy.nunique()中,列級別的名稱丟失的錯誤(GH 23222)。在
GroupBy.agg()中,將聚合函式應用於時區感知資料時出現錯誤(GH 23683)。在
GroupBy.first()和GroupBy.last()中,時區資訊會被丟棄的錯誤(GH 21603)。在
GroupBy.size()中,僅分組 NA 值時出現錯誤(GH 23050)。在
Series.groupby()中,`observed` 關鍵字引數之前被忽略的錯誤(GH 24880)。在使用
groupby與MultiIndexSeries 進行分組,並且傳入的標籤列表長度等於 Series 長度時,導致了錯誤的分組(GH 25704)。確保了 `groupby` 聚合函式輸出的順序在所有 Python 版本中保持一致(GH 25692)。
確保了在對有序的
Categorical進行分組並指定 `observed=True` 時,結果組的順序是正確的(GH 25871, GH 25167)。在
Rolling.min()和Rolling.max()中導致記憶體洩漏的錯誤(GH 25893)。在
Rolling.count()和.Expanding.count中,`axis` 關鍵字引數之前被忽略(GH 13503)。在帶有 datetime 列的
GroupBy.idxmax()和GroupBy.idxmin()中,返回的 dtype 不正確(GH 25444, GH 15306)。在使用具有缺失類別的分類列時,
GroupBy.cumsum()、GroupBy.cumprod()、GroupBy.cummin()和GroupBy.cummax()會返回不正確的結果或導致段錯誤(GH 16771)。在
GroupBy.nth()中,分組中的 NA 值會返回不正確的結果(GH 26011)。在
SeriesGroupBy.transform()中,轉換空組會引發ValueError的錯誤(GH 26208)。在
DataFrame.groupby()中存在一個 bug,當使用.groups訪問器時,傳遞Grouper會返回不正確的組 (GH 26326)在
GroupBy.agg()中存在一個 bug,對於 uint64 列會返回不正確的結果。( GH 26310)在
Rolling.median()和Rolling.quantile()中存在一個 bug,當視窗為空時會引發 MemoryError (GH 26005)在
Rolling.median()和Rolling.quantile()中存在一個 bug,當使用closed='left'和closed='neither'時會返回不正確的結果 (GH 26005)改進了
Rolling,Window和ExponentialMovingWindow函式,使其從結果中排除無關的列而不是引發錯誤,並且僅當所有列都無關時才引發DataError(GH 12537)在
Rolling.max()和Rolling.min()中存在一個 bug,當使用空的變數視窗時會返回不正確的結果 (GH 26005)當
Window.aggregate()的引數中使用了不支援的加權視窗函式時,引發一個有用的異常 (GH 26597)
Reshaping#
在
pandas.merge()中存在一個 bug,如果None被賦值給 suffixes,而不是保留列名不變,會新增一個字串 "None" (GH 24782)。在
merge()中存在一個 bug,當按索引名稱合併時,有時會導致索引編號不正確(現在缺失的索引值被分配為 NA) (GH 24212, GH 25009)to_records()現在接受column_dtypes引數的 dtype (GH 24895)在
concat()中存在一個 bug,當OrderedDict(以及 Python 3.6+ 中的dict)作為objs引數傳入時,其順序不會被尊重 (GH 21510)在
pivot_table()中存在一個 bug,當aggfunc引數包含一個list時,即使dropna引數為False,包含NaN值的列也會被刪除 (GH 22159)在
concat()中存在一個 bug,兩條具有相同freq的DatetimeIndex會丟失其freq(GH 3232)。在
merge()中存在一個 bug,當合並具有等效 Categorical dtypes 時會引發錯誤 (GH 22501)使用迭代器或生成器的字典(例如
pd.DataFrame({'A': reversed(range(3))}))例項化DataFrame時存在一個 bug,會引發錯誤 (GH 26349)。使用
range(例如pd.DataFrame(range(3)))例項化DataFrame時存在一個 bug,會引發錯誤 (GH 26342)。在
Series.apply()中存在一個 bug,當 Series 是時區感知的DatetimeIndex時,apply 會失敗 (GH 25959)在
pandas.cut()中存在一個 bug,由於整數溢位,大型 bin 可能會錯誤地引發錯誤 (GH 26045)在
DataFrame.sort_index()中存在一個 bug,當對多索引DataFrame的所有級別進行排序,且初始級別最後排序時,會丟擲錯誤 (GH 26053)在
Series.nlargest()中存在一個 bug,它將True視為小於False(GH 26154)在
DataFrame.pivot_table()中存在一個 bug,當使用IntervalIndex作為透視索引時,會引發TypeError(GH 25814)在
DataFrame.from_dict()中存在一個 bug,當orient='index'時,它會忽略OrderedDict的順序 (GH 8425)。在
DataFrame.transpose()中存在一個 bug,當轉置一個具有時區感知 datetime 列的 DataFrame 時,會錯誤地引發ValueError(GH 26825)在
pivot_table()中存在一個 bug,當將時區感知的列作為values進行透視時,會刪除時區資訊 (GH 14948)在
merge_asof()中存在一個 bug,當指定多個by列,其中一個列是datetime64[ns, tz]dtype 時 (GH 26649)
Sparse#
顯著加速了
SparseArray的初始化,這對大多數操作都有益,修復了 v0.20.0 中引入的效能迴歸(GH 24985)在
SparseFrame建構函式中存在一個 bug,當將None作為資料傳遞時,default_fill_value會被忽略 (GH 16807)在
SparseDataFrame中存在一個 bug,當新增一個值長度與索引長度不匹配的列時,會引發AssertionError而不是ValueError(GH 25484)為
Series.sparse.from_coo()引入了更好的錯誤訊息,以便為不是 coo 矩陣的輸入返回TypeError(GH 26554)在
numpy.modf()中對SparseArray存在一個 bug。現在返回一個SparseArray的元組 (GH 26946)。
構建更改#
修復了在 macOS 上使用 PyPy 進行安裝的錯誤 (GH 26536)
ExtensionArray#
在
factorize()中存在一個 bug,當傳遞一個帶有自定義na_sentinel的ExtensionArray時 (GH 25696)。Series.count()錯誤地計算了 ExtensionArrays 中的 NA 值 (GH 26835)添加了
Series.__array_ufunc__以更好地處理應用於基於擴充套件陣列的 Series 的 NumPy ufuncs (GH 23293)。從
ExtensionArray.copy()中移除了關鍵字引數deep(GH 27083)
其他#
貢獻者#
總共有 231 人為本次釋出貢獻了補丁。名字旁邊帶有“+”的人是首次貢獻補丁。
1_x7 +
Abdullah İhsan Seçer +
Adam Bull +
Adam Hooper
Albert Villanova del Moral
Alex Watt +
AlexTereshenkov +
Alexander Buchkovsky
Alexander Hendorf +
Alexander Nordin +
Alexander Ponomaroff
Alexandre Batisse +
Alexandre Decan +
Allen Downey +
Alyssa Fu Ward +
Andrew Gaspari +
Andrew Wood +
Antoine Viscardi +
Antonio Gutierrez +
Arno Veenstra +
ArtinSarraf
Batalex +
Baurzhan Muftakhidinov
Benjamin Rowell
Bharat Raghunathan +
Bhavani Ravi +
Big Head +
Brett Randall +
Bryan Cutler +
C John Klehm +
Caleb Braun +
Cecilia +
Chris Bertinato +
Chris Stadler +
Christian Haege +
Christian Hudon
Christopher Whelan
Chuanzhu Xu +
Clemens Brunner
Damian Kula +
Daniel Hrisca +
Daniel Luis Costa +
Daniel Saxton
DanielFEvans +
David Liu +
Deepyaman Datta +
Denis Belavin +
Devin Petersohn +
Diane Trout +
EdAbati +
Enrico Rotundo +
EternalLearner42 +
Evan +
Evan Livelo +
Fabian Rost +
Flavien Lambert +
Florian Rathgeber +
Frank Hoang +
Gaibo Zhang +
Gioia Ballin
Giuseppe Romagnuolo +
Gordon Blackadder +
Gregory Rome +
Guillaume Gay
HHest +
Hielke Walinga +
How Si Wei +
Hubert
Huize Wang +
Hyukjin Kwon +
Ian Dunn +
Inevitable-Marzipan +
Irv Lustig
JElfner +
Jacob Bundgaard +
James Cobon-Kerr +
Jan-Philip Gehrcke +
Jarrod Millman +
Jayanth Katuri +
Jeff Reback
Jeremy Schendel
Jiang Yue +
Joel Ostblom
Johan von Forstner +
Johnny Chiu +
Jonas +
Jonathon Vandezande +
Jop Vermeer +
Joris Van den Bossche
Josh
Josh Friedlander +
Justin Zheng
Kaiqi Dong
Kane +
Kapil Patel +
Kara de la Marck +
Katherine Surta +
Katrin Leinweber +
Kendall Masse
Kevin Sheppard
Kyle Kosic +
Lorenzo Stella +
Maarten Rietbergen +
Mak Sze Chun
Marc Garcia
Mateusz Woś
Matias Heikkilä
Mats Maiwald +
Matthew Roeschke
Max Bolingbroke +
Max Kovalovs +
Max van Deursen +
Michael
Michael Davis +
Michael P. Moran +
Mike Cramblett +
Min ho Kim +
Misha Veldhoen +
Mukul Ashwath Ram +
MusTheDataGuy +
Nanda H Krishna +
Nicholas Musolino
Noam Hershtig +
Noora Husseini +
Paul
Paul Reidy
Pauli Virtanen
Pav A +
Peter Leimbigler +
Philippe Ombredanne +
Pietro Battiston
Richard Eames +
Roman Yurchak
Ruijing Li
Ryan
Ryan Joyce +
Ryan Nazareth
Ryan Rehman +
Sakar Panta +
Samuel Sinayoko
Sandeep Pathak +
Sangwoong Yoon
Saurav Chakravorty
Scott Talbert +
Sergey Kopylov +
Shantanu Gontia +
Shivam Rana +
Shorokhov Sergey +
Simon Hawkins
Soyoun(Rose) Kim
Stephan Hoyer
Stephen Cowley +
Stephen Rauch
Sterling Paramore +
Steven +
Stijn Van Hoey
Sumanau Sareen +
Takuya N +
Tan Tran +
Tao He +
Tarbo Fukazawa
Terji Petersen +
Thein Oo
ThibTrip +
Thijs Damsma +
Thiviyan Thanapalasingam
Thomas A Caswell
Thomas Kluiters +
Tilen Kusterle +
Tim Gates +
Tim Hoffmann
Tim Swast
Tom Augspurger
Tom Neep +
Tomáš Chvátal +
Tyler Reddy
Vaibhav Vishal +
Vasily Litvinov +
Vibhu Agarwal +
Vikramjeet Das +
Vladislav +
Víctor Moron Tejero +
Wenhuan
Will Ayd +
William Ayd
Wouter De Coster +
Yoann Goular +
Zach Angell +
alimcmaster1
anmyachev +
chris-b1
danielplawrence +
endenis +
enisnazif +
ezcitron +
fjetter
froessler
gfyoung
gwrome +
h-vetinari
haison +
hannah-c +
heckeop +
iamshwin +
jamesoliverh +
jbrockmendel
jkovacevic +
killerontherun1 +
knuu +
kpapdac +
kpflugshaupt +
krsnik93 +
leerssej +
lrjball +
mazayo +
nathalier +
nrebena +
nullptr +
pilkibun +
pmaxey83 +
rbenes +
robbuckley
shawnbrown +
sudhir mohanraj +
tadeja +
tamuhey +
thatneat
topper-123
willweil +
yehia67 +
yhaque1213 +