1.0.0 版本的新增內容(2020 年 1 月 29 日)#
pandas 1.0.0 版本中的更改。有關包括其他 pandas 版本在內的完整變更日誌,請參閱釋出說明。
注意
pandas 1.0 版本移除了許多在先前版本中已棄用的功能(概述請參閱下方)。建議您在升級到 pandas 1.0 之前,先升級到 pandas 0.25 並確保您的程式碼在沒有警告的情況下正常工作。
新的棄用策略#
從 pandas 1.0.0 版本開始,pandas 將採用 SemVer 的一個變種來發布版本。簡而言之:
棄用將在次要版本中引入(例如,1.1.0、1.2.0、2.1.0 等)。
棄用將在主要版本中強制執行(例如,1.0.0、2.0.0、3.0.0 等)。
API 破壞性更改僅在主要版本中進行(實驗性功能除外)。
更多詳情請參閱版本策略。
增強功能#
在 rolling.apply 和 expanding.apply 中使用 Numba#
我們在 apply() 和 apply() 中添加了 engine 關鍵字引數,允許使用者使用 Numba 而不是 Cython 來執行例程。如果 apply 函式可以操作 numpy 陣列且資料集較大(100 萬行或更多),使用 Numba 引擎可以帶來顯著的效能提升。有關更多詳細資訊,請參閱rolling apply 文件(GH 28987,GH 30936)。
為滾動操作定義自定義視窗#
我們添加了一個 pandas.api.indexers.BaseIndexer() 類,允許使用者定義在 rolling 操作期間如何建立視窗邊界。使用者可以在 pandas.api.indexers.BaseIndexer() 的子類上定義自己的 get_window_bounds 方法,該方法將在滾動聚合期間生成每個視窗使用的開始和結束索引。有關更多詳細資訊和示例用法,請參閱自定義視窗滾動文件。
轉換為 markdown#
我們添加了 to_markdown() 方法,用於建立 markdown 表格(GH 11052)。
In [1]: df = pd.DataFrame({"A": [1, 2, 3], "B": [1, 2, 3]}, index=['a', 'a', 'b'])
In [2]: print(df.to_markdown())
| | A | B |
|:---|----:|----:|
| a | 1 | 1 |
| a | 2 | 2 |
| b | 3 | 3 |
實驗性新功能#
實驗性 NA 標量用於表示缺失值#
引入了一個新的 pd.NA 值(單例),用於表示標量缺失值。到目前為止,pandas 使用了多種值來表示缺失資料:浮點資料使用 np.nan,物件型別資料使用 np.nan 或 None,日期時間型別資料使用 pd.NaT。 pd.NA 的目標是提供一個可在資料型別之間一致使用的“缺失”指示符。 pd.NA 目前被可空整數、布林資料型別以及新的字串資料型別使用(GH 28095)。
警告
實驗性:pd.NA 的行為仍可能在未通知的情況下發生更改。
例如,使用可空整數 dtype 建立 Series。
In [3]: s = pd.Series([1, 2, None], dtype="Int64")
In [4]: s
Out[4]:
0 1
1 2
2 <NA>
dtype: Int64
In [5]: s[2]
Out[5]: <NA>
與 np.nan 相比,pd.NA 在某些操作中的行為不同。除了算術運算之外,pd.NA 在比較運算中也會作為“缺失”或“未知”傳播。
In [6]: np.nan > 1
Out[6]: False
In [7]: pd.NA > 1
Out[7]: <NA>
對於邏輯運算,pd.NA 遵循三值邏輯(或Kleene 邏輯)的規則。例如:
In [8]: pd.NA | True
Out[8]: True
更多資訊,請參閱使用者指南中關於缺失資料的 NA 部分。
專用的字串資料型別#
我們添加了 StringDtype,這是一個專用於字串資料的擴充套件型別。在此之前,字串通常儲存在 object-dtype 的 NumPy 陣列中。(GH 29975)。
警告
StringDtype 目前被視為實驗性的。實現和部分 API 可能在未通知的情況下發生更改。
‘string’ 擴充套件型別解決了 object-dtype NumPy 陣列的幾個問題:
您可能會不小心在
objectdtype 陣列中儲存字串和非字串的混合體。而StringArray只能儲存字串。objectdtype 會破壞特定於 dtype 的操作,例如DataFrame.select_dtypes()。沒有明確的方法可以選擇僅文字而排除非文字但仍為 object-dtype 的列。在閱讀程式碼時,
objectdtype 陣列的內容不如string清晰。
In [9]: pd.Series(['abc', None, 'def'], dtype=pd.StringDtype())
Out[9]:
0 abc
1 <NA>
2 def
dtype: string
您也可以使用別名 "string"。
In [10]: s = pd.Series(['abc', None, 'def'], dtype="string")
In [11]: s
Out[11]:
0 abc
1 <NA>
2 def
dtype: string
常規的字串訪問器方法仍然有效。在適當的情況下,Series 或 DataFrame 列的返回型別也將具有字串 dtype。
In [12]: s.str.upper()
Out[12]:
0 ABC
1 <NA>
2 DEF
dtype: string
In [13]: s.str.split('b', expand=True).dtypes
Out[13]:
0 string
1 string
dtype: object
返回整數的字串訪問器方法將返回具有 Int64Dtype 的值。
In [14]: s.str.count("a")
Out[14]:
0 1
1 <NA>
2 0
dtype: Int64
我們建議在處理字串時顯式使用 string 資料型別。有關更多資訊,請參閱文字資料型別。
支援缺失值的布林資料型別#
我們添加了 BooleanDtype / BooleanArray,這是一個專用於可以包含缺失值的布林資料的擴充套件型別。基於 bool-dtype NumPy 陣列的預設 bool 資料型別,該列只能包含 True 或 False,而不能包含缺失值。這個新的 BooleanArray 可以透過在單獨的掩碼中跟蹤來儲存缺失值。(GH 29555,GH 30095,GH 31131)。
In [15]: pd.Series([True, False, None], dtype=pd.BooleanDtype())
Out[15]:
0 True
1 False
2 <NA>
dtype: boolean
您也可以使用別名 "boolean"。
In [16]: s = pd.Series([True, False, None], dtype="boolean")
In [17]: s
Out[17]:
0 True
1 False
2 <NA>
dtype: boolean
使用 convert_dtypes 方法簡化支援的擴充套件 dtype 的使用#
為了鼓勵使用支援 pd.NA 的擴充套件 dtype,如 StringDtype、BooleanDtype、Int64Dtype、Int32Dtype 等,我們引入了 DataFrame.convert_dtypes() 和 Series.convert_dtypes() 方法。(GH 29752)(GH 30929)。
示例
In [18]: df = pd.DataFrame({'x': ['abc', None, 'def'],
....: 'y': [1, 2, np.nan],
....: 'z': [True, False, True]})
....:
In [19]: df
Out[19]:
x y z
0 abc 1.0 True
1 NaN 2.0 False
2 def NaN True
In [20]: df.dtypes
Out[20]:
x str
y float64
z bool
dtype: object
In [21]: converted = df.convert_dtypes()
In [22]: converted
Out[22]:
x y z
0 abc 1 True
1 <NA> 2 False
2 def <NA> True
In [23]: converted.dtypes
Out[23]:
x string
y Int64
z boolean
dtype: object
這在使用 read_csv() 和 read_excel() 等讀取器讀取資料後,尤其有用。請參閱此處瞭解說明。
其他增強功能#
在
DataFrame.to_string()中添加了max_colwidth引數,用於控制何時截斷寬列(GH 9784)。為
Series.to_numpy()、Index.to_numpy()和DataFrame.to_numpy()添加了na_value引數,用於控制缺失值使用的值(GH 30322)。MultiIndex.from_product()如果未顯式提供,將從輸入推斷級別名稱(GH 27292)。DataFrame.to_latex()現在接受caption和label引數(GH 25436)。具有可空整數、新字串 dtype 和 period 資料型別的 DataFrame 現在可以轉換為
pyarrow(>=0.15.0),這意味著在使用pyarrow引擎寫入 Parquet 檔案格式時支援(GH 28368)。完全的 Parquet 往返(使用to_parquet()/read_parquet()寫入和讀回)在 pyarrow >= 0.16 版本中受支援(GH 20612)。to_parquet()現在正確處理 pyarrow 引擎中使用者定義模式的schema引數。(GH 30270)。DataFrame.to_json()現在接受indent整數引數,以啟用 JSON 輸出的格式化列印(GH 12004)。read_stata()可以讀取 Stata 119 dta 檔案。(GH 28250)。實現了
Window.var()和Window.std()函式(GH 26597)。為
DataFrame.to_string()添加了encoding引數,用於處理非 ASCII 文字(GH 28766)。為
DataFrame.to_html()添加了encoding引數,用於處理非 ASCII 文字(GH 28663)。Styler.background_gradient()現在接受vmin和vmax引數(GH 12145)。透過傳遞
engine='pyxlsb',read_excel()現在可以讀取二進位制 Excel(.xlsb)檔案。有關更多詳細資訊和示例用法,請參閱二進位制 Excel 檔案文件。關閉 GH 8540。在
DataFrame.to_parquet()中的partition_cols引數現在接受字串(GH 27117)。pandas.read_json()現在解析NaN、Infinity和-Infinity(GH 12213)。DataFrame 建構函式使用
ExtensionArray保留ExtensionArraydtype(GH 11363)。DataFrame.sort_values()和Series.sort_values()增加了ignore_index關鍵字引數,以便在排序後重置索引(GH 30114)。DataFrame.sort_index()和Series.sort_index()增加了ignore_index關鍵字引數以重置索引(GH 30114)。DataFrame.drop_duplicates()增加了ignore_index關鍵字引數以重置索引(GH 30114)。添加了用於匯出 Stata 118 和 119 版本 dta 檔案的新寫入器
StataWriterUTF8。這些檔案格式支援匯出包含 Unicode 字元的字串。格式 119 支援包含超過 32,767 個變數的資料集(GH 23573,GH 30959)。Series.map()現在接受collections.abc.Mapping的子類作為對映器(GH 29733)。Timestamp.fromisocalendar()現在與 python 3.8 及以上版本相容(GH 28115)。DataFrame.to_pickle()和read_pickle()現在接受 URL(GH 30163)。
向後不相容的 API 更改#
避免使用 MultiIndex.levels 中的名稱#
作為對 MultiIndex 的更大重構的一部分,級別名稱現在與級別分開儲存(GH 27242)。我們建議使用 MultiIndex.names 來訪問名稱,並使用 Index.set_names() 來更新名稱。
為了向後相容,您仍然可以訪問透過級別訪問的名稱。
In [24]: mi = pd.MultiIndex.from_product([[1, 2], ['a', 'b']], names=['x', 'y'])
In [25]: mi.levels[0].name
Out[25]: 'x'
但是,不再可能透過級別更新 MultiIndex 的名稱。
In [26]: mi.levels[0].name = "new name"
---------------------------------------------------------------------------
RuntimeError Traceback (most recent call last)
Cell In[26], line 1
----> 1 mi.levels[0].name = "new name"
File ~/work/pandas/pandas/pandas/core/indexes/base.py:1809, in Index.name(self, value)
1805 @name.setter
1806 def name(self, value: Hashable) -> None:
1807 if self._no_setting_name:
1808 # Used in MultiIndex.levels to avoid silently ignoring name updates.
-> 1809 raise RuntimeError(
1810 "Cannot set name on a level of a MultiIndex. Use "
1811 "'MultiIndex.set_names' instead."
1812 )
1813 maybe_extract_name(value, None, type(self))
1814 self._name = value
RuntimeError: Cannot set name on a level of a MultiIndex. Use 'MultiIndex.set_names' instead.
In [27]: mi.names
Out[27]: FrozenList(['x', 'y'])
要更新,請使用 MultiIndex.set_names,它會返回一個新的 MultiIndex。
In [28]: mi2 = mi.set_names("new name", level=0)
In [29]: mi2.names
Out[29]: FrozenList(['new name', 'y'])
IntervalArray 的新 repr#
pandas.arrays.IntervalArray 採用了新的 __repr__,與其他陣列類保持一致(GH 25022)。
pandas 0.25.x
In [1]: pd.arrays.IntervalArray.from_tuples([(0, 1), (2, 3)])
Out[2]:
IntervalArray([(0, 1], (2, 3]],
closed='right',
dtype='interval[int64]')
pandas 1.0.0
In [30]: pd.arrays.IntervalArray.from_tuples([(0, 1), (2, 3)])
Out[30]:
<IntervalArray>
[(0, 1], (2, 3]]
Length: 2, dtype: interval[int64, right]
DataFrame.rename 現在只接受一個位置引數#
DataFrame.rename() 以前會接受導致歧義或未定義行為的位置引數。從 pandas 1.0 開始,只有第一個引數(將標籤對映到其新名稱,沿預設軸)允許透過位置傳遞(GH 29136)。
pandas 0.25.x
In [1]: df = pd.DataFrame([[1]])
In [2]: df.rename({0: 1}, {0: 2})
Out[2]:
FutureWarning: ...Use named arguments to resolve ambiguity...
2
1 1
pandas 1.0.0
In [3]: df.rename({0: 1}, {0: 2})
Traceback (most recent call last):
...
TypeError: rename() takes from 1 to 2 positional arguments but 3 were given
請注意,現在提供衝突或可能引起歧義的引數時將引發錯誤。
pandas 0.25.x
In [4]: df.rename({0: 1}, index={0: 2})
Out[4]:
0
1 1
In [5]: df.rename(mapper={0: 1}, index={0: 2})
Out[5]:
0
2 1
pandas 1.0.0
In [6]: df.rename({0: 1}, index={0: 2})
Traceback (most recent call last):
...
TypeError: Cannot specify both 'mapper' and any of 'index' or 'columns'
In [7]: df.rename(mapper={0: 1}, index={0: 2})
Traceback (most recent call last):
...
TypeError: Cannot specify both 'mapper' and any of 'index' or 'columns'
您仍然可以透過提供 axis 關鍵字引數來更改應用第一個位置引數的軸。
In [31]: df.rename({0: 1})
Out[31]:
0
1 1
In [32]: df.rename({0: 1}, axis=1)
Out[32]:
1
0 1
如果您想更新索引和列標籤,請務必使用相應的關鍵字。
In [33]: df.rename(index={0: 1}, columns={0: 2})
Out[33]:
2
1 1
為 DataFrame 擴充套件了詳細資訊輸出#
DataFrame.info() 現在顯示列摘要的行號(GH 17304)。
pandas 0.25.x
In [1]: df = pd.DataFrame({"int_col": [1, 2, 3],
... "text_col": ["a", "b", "c"],
... "float_col": [0.0, 0.1, 0.2]})
In [2]: df.info(verbose=True)
<class 'pandas.DataFrame'>
RangeIndex: 3 entries, 0 to 2
Data columns (total 3 columns):
int_col 3 non-null int64
text_col 3 non-null object
float_col 3 non-null float64
dtypes: float64(1), int64(1), object(1)
memory usage: 152.0+ bytes
pandas 1.0.0
In [34]: df = pd.DataFrame({"int_col": [1, 2, 3],
....: "text_col": ["a", "b", "c"],
....: "float_col": [0.0, 0.1, 0.2]})
....:
In [35]: df.info(verbose=True)
<class 'pandas.DataFrame'>
RangeIndex: 3 entries, 0 to 2
Data columns (total 3 columns):
# Column Non-Null Count Dtype
--- ------ -------------- -----
0 int_col 3 non-null int64
1 text_col 3 non-null str
2 float_col 3 non-null float64
dtypes: float64(1), int64(1), str(1)
memory usage: 207.0 bytes
pandas.array() 推斷的變化#
在幾種情況下,pandas.array() 現在會推斷 pandas 的新擴充套件型別(GH 29791)。
字串資料(包括缺失值)現在返回
arrays.StringArray。整數資料(包括缺失值)現在返回
arrays.IntegerArray。布林資料(包括缺失值)現在返回新的
arrays.BooleanArray。
pandas 0.25.x
In [1]: pd.array(["a", None])
Out[1]:
<PandasArray>
['a', None]
Length: 2, dtype: object
In [2]: pd.array([1, None])
Out[2]:
<PandasArray>
[1, None]
Length: 2, dtype: object
pandas 1.0.0
In [36]: pd.array(["a", None])
Out[36]:
<ArrowStringArray>
['a', <NA>]
Length: 2, dtype: string
In [37]: pd.array([1, None])
Out[37]:
<IntegerArray>
[1, <NA>]
Length: 2, dtype: Int64
作為提醒,您可以指定 dtype 來停用所有推斷。
arrays.IntegerArray 現在使用 pandas.NA#
arrays.IntegerArray 現在使用 pandas.NA 而不是 numpy.nan 作為其缺失值標記(GH 29964)。
pandas 0.25.x
In [1]: a = pd.array([1, 2, None], dtype="Int64")
In [2]: a
Out[2]:
<IntegerArray>
[1, 2, NaN]
Length: 3, dtype: Int64
In [3]: a[2]
Out[3]:
nan
pandas 1.0.0
In [38]: a = pd.array([1, 2, None], dtype="Int64")
In [39]: a
Out[39]:
<IntegerArray>
[1, 2, <NA>]
Length: 3, dtype: Int64
In [40]: a[2]
Out[40]: <NA>
這帶來了一些 API 破壞性後果。
轉換為 NumPy ndarray
轉換為 NumPy 陣列時,缺失值將是 pd.NA,無法轉換為浮點數。因此,呼叫 np.asarray(integer_array, dtype="float") 現在將引發錯誤。
pandas 0.25.x
In [1]: np.asarray(a, dtype="float")
Out[1]:
array([ 1., 2., nan])
pandas 1.0.0
In [41]: np.asarray(a, dtype="float")
Out[41]: array([ 1., 2., nan])
請改用 arrays.IntegerArray.to_numpy() 並明確指定 na_value。
In [42]: a.to_numpy(dtype="float", na_value=np.nan)
Out[42]: array([ 1., 2., nan])
聚合操作可能返回 pd.NA
當使用 skipna=False 執行求和等聚合操作時,如果存在缺失值,結果將是 pd.NA 而不是 np.nan(GH 30958)。
pandas 0.25.x
In [1]: pd.Series(a).sum(skipna=False)
Out[1]:
nan
pandas 1.0.0
In [43]: pd.Series(a).sum(skipna=False)
Out[43]: <NA>
value_counts 返回可空的整數 dtype
具有可空整數 dtype 的 Series.value_counts() 現在為值返回可空整數 dtype。
pandas 0.25.x
In [1]: pd.Series([2, 1, 1, None], dtype="Int64").value_counts().dtype
Out[1]:
dtype('int64')
pandas 1.0.0
In [44]: pd.Series([2, 1, 1, None], dtype="Int64").value_counts().dtype
Out[44]: Int64Dtype()
arrays.IntegerArray 的比較返回 arrays.BooleanArray#
對 arrays.IntegerArray 的比較操作現在返回 arrays.BooleanArray 而不是 NumPy 陣列(GH 29964)。
pandas 0.25.x
In [1]: a = pd.array([1, 2, None], dtype="Int64")
In [2]: a
Out[2]:
<IntegerArray>
[1, 2, NaN]
Length: 3, dtype: Int64
In [3]: a > 1
Out[3]:
array([False, True, False])
pandas 1.0.0
In [45]: a = pd.array([1, 2, None], dtype="Int64")
In [46]: a > 1
Out[46]:
<BooleanArray>
[False, True, <NA>]
Length: 3, dtype: boolean
請注意,缺失值現在會傳播,而不是像 numpy.nan 那樣始終比較不相等。更多資訊請參閱 NA 語義。
預設情況下,Categorical.min() 返回最小值而不是 np.nan#
當 Categorical 包含 np.nan 時,Categorical.min() 預設(skipna=True)不再返回 np.nan(GH 25303)。
pandas 0.25.x
In [1]: pd.Categorical([1, 2, np.nan], ordered=True).min()
Out[1]: nan
pandas 1.0.0
In [47]: pd.Categorical([1, 2, np.nan], ordered=True).min()
Out[47]: np.int64(1)
空 pandas.Series 的預設 dtype#
初始化一個空的 pandas.Series 而不指定 dtype 現在將引發 DeprecationWarning(GH 17261)。預設 dtype 將從 float64 更改為 object,以便與 DataFrame 和 Index 的行為保持一致。
pandas 1.0.0
In [1]: pd.Series()
Out[2]:
DeprecationWarning: The default dtype for empty Series will be 'object' instead of 'float64' in a future version. Specify a dtype explicitly to silence this warning.
Series([], dtype: float64)
resample 操作的結果 dtype 推斷髮生變化#
DataFrame.resample() 聚合結果 dtype 的規則已針對擴充套件型別進行了更改(GH 31359)。以前,pandas 會嘗試將結果轉換回原始 dtype,如果不可能則回退到常規推斷規則。現在,只有當結果中的標量值是擴充套件 dtype 的標量型別的例項時,pandas 才會返回原始 dtype 的結果。
In [48]: df = pd.DataFrame({"A": ['a', 'b']}, dtype='category',
....: index=pd.date_range('2000', periods=2))
....:
In [49]: df
Out[49]:
A
2000-01-01 a
2000-01-02 b
pandas 0.25.x
In [1]> df.resample("2D").agg(lambda x: 'a').A.dtype
Out[1]:
CategoricalDtype(categories=['a', 'b'], ordered=False)
pandas 1.0.0
In [50]: df.resample("2D").agg(lambda x: 'a').A.dtype
Out[50]: CategoricalDtype(categories=['a', 'b'], ordered=False, categories_dtype=str)
這修復了 resample 和 groupby 之間的不一致。這也修復了一個潛在的 bug,即結果的 **值** 可能會根據結果如何轉換回原始 dtype 而有所不同。
pandas 0.25.x
In [1] df.resample("2D").agg(lambda x: 'c')
Out[1]:
A
0 NaN
pandas 1.0.0
In [51]: df.resample("2D").agg(lambda x: 'c')
Out[51]:
A
2000-01-01 c
提高了 Python 的最低版本要求#
pandas 1.0.0 支援 Python 3.6.1 及更高版本(GH 29212)。
提高了依賴項的最低版本#
更新了某些依賴項的最低支援版本(GH 29766、GH 29723)。如果已安裝,我們現在要求
包 |
最低版本 |
必需 |
已更改 |
|---|---|---|---|
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.3.2 |
X |
gcsfs |
0.2.2 |
|
lxml |
3.8.0 |
|
matplotlib |
2.2.2 |
|
numba |
0.46.0 |
X |
openpyxl |
2.5.7 |
X |
pyarrow |
0.13.0 |
X |
pymysql |
0.7.1 |
|
pytables |
3.4.2 |
|
s3fs |
0.3.0 |
X |
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。
構建更改#
pandas 添加了一個 pyproject.toml 檔案,並且將不再在上傳到 PyPI 的源分發版中包含 cythonized 檔案(GH 28341、GH 20775)。如果您安裝的是已構建的分發版(wheel)或透過 conda 安裝,這應該不會對您產生任何影響。如果您要從原始碼構建 pandas,則在呼叫 pip install pandas 之前,您應該不再需要將 Cython 安裝到您的構建環境中。
其他 API 更改#
DataFrameGroupBy.transform()和SeriesGroupBy.transform()現在在無效操作名稱時引發錯誤(GH 27489)。pandas.api.types.infer_dtype()現在將返回“integer-na”,用於整數和np.nan的混合(GH 27283)。MultiIndex.from_arrays()在顯式提供names=None時將不再從陣列推斷名稱(GH 27292)。為了改進 Tab 鍵自動補全,pandas 在使用
dir自省 pandas 物件時(例如dir(df)),不包含大多數已棄用的屬性。要檢視哪些屬性被排除,請參閱物件的_deprecations屬性,例如pd.DataFrame._deprecations(GH 28805)。unique()返回的 dtype 現在與輸入 dtype 匹配。(GH 27874)。將
options.matplotlib.register_converters的預設配置值從True更改為"auto"(GH 18720)。現在,pandas 自定義格式化程式僅應用於 pandas 透過plot()建立的圖。以前,pandas 的格式化程式會應用於在呼叫plot()**之後** 建立的所有圖。更多資訊請參閱 units registration。Series.dropna()已刪除其**kwargs引數,改為使用單個how引數。以前,向**kwargs傳遞how以外的任何內容都會引發TypeError(GH 29388)。在測試 pandas 時,pytest 的新最低要求版本為 5.0.1(GH 29664)。
Series.str.__iter__()已棄用,將在將來的版本中刪除(GH 28277)。已將
<NA>新增到read_csv()的預設 NA 值列表中(GH 30821)。
文件改進#
新增了關於 Scale to large datasets 的新章節(GH 28315)。
為 HDF5 資料集添加了關於 Query MultiIndex 的子章節(GH 28791)。
棄用#
Series.item()和Index.item()已被 _取消棄用_(GH 29250)。Index.set_value已被棄用。對於給定的索引idx,陣列arr,索引中的值idx_val和新值val,idx.set_value(arr, idx_val, val)等同於arr[idx.get_loc(idx_val)] = val,應使用後者代替(GH 28621)。is_extension_type()已棄用,應改用is_extension_array_dtype()(GH 29457)。eval()的關鍵字引數 “truediv” 已棄用,將在將來的版本中刪除(GH 29812)。DateOffset.isAnchored()和DatetOffset.onOffset()已棄用,將在將來的版本中刪除,請改用DateOffset.is_anchored()和DateOffset.is_on_offset()(GH 30340)。pandas.tseries.frequencies.get_offset已棄用,將在將來的版本中刪除,請改用pandas.tseries.frequencies.to_offset(GH 4205)。Categorical.take_nd()和CategoricalIndex.take_nd()已棄用,請改用Categorical.take()和CategoricalIndex.take()(GH 27745)。Categorical.min()和Categorical.max()的引數numeric_only已棄用,並被skipna取代(GH 25303)。在
lreshape()中的引數label已棄用,將在將來的版本中刪除(GH 29742)。pandas.core.index已棄用,將在將來的版本中刪除,公共類可在頂層名稱空間中訪問(GH 19711)。pandas.json_normalize()現在已暴露在頂層名稱空間。使用json_normalize作為pandas.io.json.json_normalize現在已棄用,建議使用json_normalize作為pandas.json_normalize()代替(GH 27586)。在
pandas.read_json()中的引數numpy已棄用(GH 28512)。DataFrame.to_stata()、DataFrame.to_feather()和DataFrame.to_parquet()中的引數 “fname” 已棄用,請改用 “path”(GH 23574)。RangeIndex中已棄用的內部屬性_start、_stop和_step現在引發FutureWarning而不是DeprecationWarning(GH 26581)。已棄用
pandas.util.testing模組。請改用pandas.testing中記錄在 Assertion functions 中的公共 API(GH 16232)。已棄用
pandas.SparseArray。請改用pandas.arrays.SparseArray(arrays.SparseArray)(GH 30642)。引數
is_copy在Series.take()和DataFrame.take()中已棄用,將在將來的版本中刪除。(GH 27357)。對
Index的多維索引(例如index[:, None])支援已棄用,將在將來的版本中刪除,請改為在索引之前轉換為 numpy 陣列(GH 30588)。已棄用
pandas.np子模組。請直接匯入 numpy 代替(GH 30296)。已棄用
pandas.datetime類。請直接從datetime匯入(GH 30610)。整數型別陣列對
Timedelta的 Floordiv 現在引發TypeError(GH 21036)。
整數型別陣列對 Timedelta 的 Floordiv 現在引發 TypeError(GH 21036)。
從 DataFrameGroupBy 物件中選擇列時,在方括號內傳遞單個鍵(或鍵的元組)已棄用,應改用專案列表。(GH 23566)例如。
df = pd.DataFrame({
"A": ["foo", "bar", "foo", "bar", "foo", "bar", "foo", "foo"],
"B": np.random.randn(8),
"C": np.random.randn(8),
})
g = df.groupby('A')
# single key, returns SeriesGroupBy
g['B']
# tuple of single key, returns SeriesGroupBy
g[('B',)]
# tuple of multiple keys, returns DataFrameGroupBy, raises FutureWarning
g[('B', 'C')]
# multiple keys passed directly, returns DataFrameGroupBy, raises FutureWarning
# (implicitly converts the passed strings into a single tuple)
g['B', 'C']
# proper way, returns DataFrameGroupBy
g[['B', 'C']]
移除先前版本的棄用/更改#
刪除了 SparseSeries 和 SparseDataFrame
已刪除 SparseSeries、SparseDataFrame 以及 DataFrame.to_sparse 方法(GH 28425)。我們建議使用具有稀疏值的 Series 或 DataFrame 代替。
Matplotlib 單位註冊
以前,pandas 會將轉換器作為匯入 pandas 的副作用註冊到 matplotlib(GH 18720)。這改變了在匯入 pandas **之後** 使用 matplotlib 直接建立的圖(即使您使用的是 matplotlib 而不是 plot())。
要在 matplotlib 圖中使用 pandas 格式化程式,請指定
In [1]: import pandas as pd
In [2]: pd.options.plotting.matplotlib.register_converters = True
請注意,由 DataFrame.plot() 和 Series.plot() 建立的圖**會**自動註冊轉換器。唯一的行為變化是當透過 matplotlib.pyplot.plot 或 matplotlib.Axes.plot 繪製日期類物件時。更多資訊請參閱 Custom formatters for timeseries plots。
其他移除項
已移除
read_stata()、StataReader和StataReader.read()中先前已棄用的關鍵字 “index”,請改用 “index_col”(GH 17328)。已移除
StataReader.data方法,請改用StataReader.read()(GH 9493)。已移除
pandas.plotting._matplotlib.tsplot,請改用Series.plot()(GH 19980)。pandas.tseries.converter.register已移動到pandas.plotting.register_matplotlib_converters()(GH 18307)。Series.plot()不再接受位置引數,請改用關鍵字引數(GH 30003)。DataFrame.hist()和Series.hist()不再允許figsize="default",請透過傳遞元組來指定圖形大小(GH 30003)。整數型別陣列對
Timedelta的 Floordiv 現在引發TypeError(GH 21036)。TimedeltaIndex和DatetimeIndex不再接受非納秒 dtype 字串,如 “timedelta64” 或 “datetime64”,請改用 “timedelta64[ns]” 和 “datetime64[ns]”(GH 24806)。將
pandas.api.types.infer_dtype()的預設 “skipna” 引數從False更改為True(GH 24050)。已移除
Series.ix和DataFrame.ix(GH 26438)。已移除
Index.summary(GH 18217)。已移除
Index建構函式中先前已棄用的關鍵字 “fastpath”(GH 23110)。已移除
Series.get_value、Series.set_value、DataFrame.get_value、DataFrame.set_value(GH 17739)。已移除
Series.compound和DataFrame.compound(GH 26405)。已將
DataFrame.set_index()和Series.set_axis()中的預設 “inplace” 引數從None更改為False(GH 27600)。已移除
Series.cat.categorical、Series.cat.index、Series.cat.name(GH 24751)。從
to_datetime()和to_timedelta()中移除了之前已棄用的關鍵字 “box”。此外,這些函式現在始終返回DatetimeIndex、TimedeltaIndex、Index、Series或DataFrame(GH 24486)to_timedelta()、Timedelta和TimedeltaIndex不再允許“unit”引數使用“M”、“y”或“Y”(GH 23264)從(非公開的)
offsets.generate_range中移除了之前已棄用的關鍵字 “time_rule”,該函式已移動到core.arrays._ranges.generate_range()(GH 24157)使用列表索引器和缺失標籤的
DataFrame.loc()或Series.loc()不再重新索引(GH 17295)使用不存在列的
DataFrame.to_excel()和Series.to_excel()不再重新索引(GH 17295)從
concat()中移除了之前已棄用的關鍵字 “join_axes”;請改用結果上的reindex_like(GH 22318)從
DataFrame.sort_index()中移除了之前已棄用的關鍵字 “by”;請改用DataFrame.sort_values()(GH 10726)移除了對
DataFrame.aggregate()、Series.aggregate()、core.groupby.DataFrameGroupBy.aggregate()、core.groupby.SeriesGroupBy.aggregate()、core.window.rolling.Rolling.aggregate()中巢狀重新命名(nested renaming)的支援(GH 18529)將
datetime64資料傳遞給TimedeltaIndex或將timedelta64資料傳遞給DatetimeIndex現在會引發TypeError(GH 23539,GH 23937)將
int64值傳遞給帶有時區的DatetimeIndex會將這些值解釋為 UTC 的納秒級時間戳,而不是給定區域的實際時間(GH 24559)傳遞給
DataFrame.groupby()的元組現在僅被視為一個鍵(GH 18314)移除了
Index.contains,請改用key in index(GH 30103)不再允許在
Timestamp、DatetimeIndex、TimedeltaIndex中進行int或整數陣列的加減法。請改用obj + n * obj.freq代替obj + n(GH 22535)移除了
Series.ptp(GH 21614)移除了
Series.from_array(GH 18258)移除了
DataFrame.from_items(GH 18458)移除了
DataFrame.as_matrix、Series.as_matrix(GH 18458)移除了
Series.asobject(GH 18477)移除了
DataFrame.as_blocks、Series.as_blocks、DataFrame.blocks、Series.blocks(GH 17656)pandas.Series.str.cat()現在預設對others進行對齊,使用join='left'(GH 27611)pandas.Series.str.cat()不再接受列表中的列表(list-likes within list-likes)(GH 27611)帶有
Categorical資料型別的Series.where()(或帶有Categorical列的DataFrame.where())不再允許設定新類別(GH 24114)從
DatetimeIndex、TimedeltaIndex和PeriodIndex的建構函式中移除了之前已棄用的關鍵字 “start”、“end” 和 “periods”;請改用date_range()、timedelta_range()和period_range()(GH 23919)從
DatetimeIndex和TimedeltaIndex的建構函式中移除了之前已棄用的關鍵字 “verify_integrity”(GH 23919)從
pandas.core.internals.blocks.make_block中移除了之前已棄用的關鍵字 “fastpath”(GH 19265)從
Block.make_block_same_class()中移除了之前已棄用的關鍵字 “dtype”(GH 19434)移除了
ExtensionArray._formatting_values。請改用ExtensionArray._formatter。(GH 23601)移除了
MultiIndex.to_hierarchical(GH 21613)移除了
MultiIndex.labels,請改用MultiIndex.codes(GH 23752)從
MultiIndex建構函式中移除了之前已棄用的關鍵字 “labels”,請改用 “codes”(GH 23752)移除了
MultiIndex.set_labels,請改用MultiIndex.set_codes()(GH 23752)從
MultiIndex.set_codes()、MultiIndex.copy()、MultiIndex.drop()中移除了之前已棄用的關鍵字 “labels”,請改用 “codes”(GH 23752)移除了對舊版 HDF5 格式的支援(GH 29787)
不再允許將 dtype 別名(例如 ‘datetime64[ns, UTC]’)傳遞給
DatetimeTZDtype,請改用DatetimeTZDtype.construct_from_string()(GH 23990)從
read_excel()中移除了之前已棄用的關鍵字 “skip_footer”;請改用 “skipfooter”(GH 18836)read_excel()不再允許為引數usecols傳遞整數值,請改用傳遞從 0 到usecols(包含)的整數列表(GH 23635)從
DataFrame.to_records()中移除了之前已棄用的關鍵字 “convert_datetime64”(GH 18902)移除了
IntervalIndex.from_intervals,請改用IntervalIndex建構函式(GH 19263)將
DatetimeIndex.to_series()中的預設 “keep_tz” 引數從None更改為True(GH 23739)移除了
api.types.is_period和api.types.is_datetimetz(GH 23917)移除了讀取包含 pandas 0.16 版本之前建立的
Categorical例項的 pickle 的能力(GH 27538)移除了
pandas.tseries.plotting.tsplot(GH 18627)從
DataFrame.apply()中移除了之前已棄用的關鍵字 “reduce” 和 “broadcast”(GH 18577)從
pandas._testing中移除了之前已棄用的assert_raises_regex函式(GH 29174)從
pandas.core.indexes.frozen中移除了之前已棄用的FrozenNDArray類(GH 29335)從
read_feather()中移除了之前已棄用的關鍵字 “nthreads”,請改用 “use_threads”(GH 23053)移除了
Index.is_lexsorted_for_tuple(GH 29305)移除了對
DataFrame.aggregate()、Series.aggregate()、core.groupby.DataFrameGroupBy.aggregate()、core.groupby.SeriesGroupBy.aggregate()、core.window.rolling.Rolling.aggregate()中巢狀重新命名(nested renaming)的支援(GH 29608)移除了
Series.valid;請改用Series.dropna()(GH 18800)移除了
DataFrame.is_copy、Series.is_copy(GH 18812)移除了
DataFrame.get_ftype_counts、Series.get_ftype_counts(GH 18243)移除了
DataFrame.ftypes、Series.ftypes、Series.ftype(GH 26744)移除了
Index.get_duplicates,請改用idx[idx.duplicated()].unique()(GH 20239)移除了
Series.clip_upper、Series.clip_lower、DataFrame.clip_upper、DataFrame.clip_lower(GH 24203)移除了修改
DatetimeIndex.freq、TimedeltaIndex.freq或PeriodIndex.freq的能力(GH 20772)移除了
DatetimeIndex.offset(GH 20730)移除了
DatetimeIndex.asobject、TimedeltaIndex.asobject、PeriodIndex.asobject,請改用astype(object)(GH 29801)從
factorize()中移除了之前已棄用的關鍵字 “order”(GH 19751)從
read_stata()和DataFrame.to_stata()中移除了之前已棄用的關鍵字 “encoding”(GH 21400)從
DataFrame.update()中移除了之前已棄用的關鍵字 “raise_conflict”,請改用 “errors”(GH 23585)從
DatetimeIndex.shift()、TimedeltaIndex.shift()、PeriodIndex.shift()中移除了之前已棄用的關鍵字 “n”,請改用 “periods”(GH 22458)從
DataFrame.resample()中移除了之前已棄用的關鍵字 “how”、“fill_method” 和 “limit”(GH 30139)將
timedelta64[ns]資料型別與Series.fillna()或DataFrame.fillna()一起傳遞整數值現在會引發TypeError(GH 24694)不再支援向
DataFrame.dropna()傳遞多個軸(GH 20995)移除了
Series.nonzero,請改用to_numpy().nonzero()(GH 24048)不再支援將浮點 dtype 的
codes傳遞給Categorical.from_codes(),請改用codes.astype(np.int64)(GH 21775)從
Series.str.partition()和Series.str.rpartition()中移除了之前已棄用的關鍵字 “pat”,請改用 “sep”(GH 23767)移除了
Series.put(GH 27106)移除了
Series.real、Series.imag(GH 27106)移除了
Series.to_dense、DataFrame.to_dense(GH 26684)移除了
Index.dtype_str,請改用str(index.dtype)(GH 27106)Categorical.ravel()返回Categorical而不是ndarray(GH 27199)不再支援 Numpy ufuncs 的“outer”方法,例如作用於
Series物件的np.subtract.outer,該操作將引發NotImplementedError(GH 27198)移除了
Series.get_dtype_counts和DataFrame.get_dtype_counts(GH 27145)將
Categorical.take()中的預設 “fill_value” 引數從True更改為False(GH 20841)將
Series.rolling().apply()、DataFrame.rolling().apply()、Series.expanding().apply()和DataFrame.expanding().apply()中的raw引數的預設值從None更改為False(GH 20584)移除了
Series.argmin()和Series.argmax()已棄用的行為;使用Series.idxmin()和Series.idxmax()來獲取舊的行為(GH 16955)將帶時區的
datetime.datetime或Timestamp物件與tz引數一起傳遞給Timestamp建構函式現在會引發ValueError(GH 23621)移除了
Series.base、Index.base、Categorical.base、Series.flags、Index.flags、PeriodArray.flags、Series.strides、Index.strides、Series.itemsize、Index.itemsize、Series.data、Index.data(GH 20721)將
Timedelta.resolution()的行為更改為與標準庫datetime.timedelta.resolution保持一致;對於舊行為,請使用Timedelta.resolution_string()(GH 26839)移除了
Timestamp.weekday_name、DatetimeIndex.weekday_name和Series.dt.weekday_name(GH 18164)從
Timestamp.tz_localize()、DatetimeIndex.tz_localize()和Series.tz_localize()中移除了之前已棄用的關鍵字 “errors”(GH 22644)將
CategoricalDtype中的預設 “ordered” 引數從None更改為False(GH 26336)Series.set_axis()和DataFrame.set_axis()現在要求 “labels” 作為第一個引數,並將 “axis” 作為可選的命名引數(GH 30089)移除了
to_msgpack、read_msgpack、DataFrame.to_msgpack、Series.to_msgpack(GH 27103)已刪除
Series.compress(GH 21930)已從
Categorical.fillna()中移除先前已棄用的關鍵字 “fill_value”,請使用 “value” (GH 19269)已從
andrews_curves()中移除先前已棄用的關鍵字 “data”,請使用 “frame” (GH 6956)已從
parallel_coordinates()中移除先前已棄用的關鍵字 “data”,請使用 “frame” (GH 6956)已從
parallel_coordinates()中移除先前已棄用的關鍵字 “colors”,請使用 “color” (GH 6956)已從
read_gbq()中移除先前已棄用的關鍵字 “verbose” 和 “private_key” (GH 30200)現在,對時區感知的
Series和DatetimeIndex呼叫np.array和np.asarray將返回一個包含時區感知Timestamp的物件陣列 (GH 24596)
效能改進#
在索引具有非唯一
IntervalIndex時效能有所提高 (GH 27489)在
MultiIndex.is_monotonic中效能有所提高 (GH 27495)當
bins是IntervalIndex時,cut()的效能有所提高 (GH 27668)當
method是"spearman"時,DataFrame.corr()的效能有所提高 (GH 28139)當提供要替換的值列表時,
DataFrame.replace()的效能有所提高 (GH 28099)透過使用向量化而不是迭代迴圈,
DataFrame.select_dtypes()的效能有所提高 (GH 28317)Categorical.searchsorted()和CategoricalIndex.searchsorted()的效能有所提高 (GH 28795)當比較一個
Categorical和一個標量,並且該標量不在類別中時,效能有所提高 (GH 29750)在檢查
Categorical中的值是否等於、大於等於或大於給定標量時,效能有所提高。如果檢查Categorical是否小於或小於等於標量,則沒有效能提升 (GH 29820)Index.equals()和MultiIndex.equals()的效能有所提高 (GH 29134)當
skipna為True時,infer_dtype()的效能有所提高 (GH 28814)
Bug 修復#
分類#
已新增測試以斷言,當值不是類別中的值時,
fillna()會引發正確的ValueError訊息 (GH 13628)中的錯誤,當轉換為 int 時,`NaN` 值被錯誤地處理 (GH 28406)Categorical.astype()當目標包含重複項時,使用具有
CategoricalIndex的DataFrame.reindex()會失敗,而如果源包含重複項則不會失敗 (GH 28107)中的錯誤,不允許轉換為擴充套件 dtypes (GH 28668)Categorical.astype()無法連線分類和擴充套件 dtype 列的錯誤 (GH 28668)merge()和Categorical.searchsorted()CategoricalIndex.searchsorted()現在也適用於無序分類 (GH 21667)已新增測試以斷言,透過
DataFrame.to_parquet()或read_parquet()進行往返 parquet 操作會保留字串型別的 Categorical dtypes (GH 27955)已更改
Categorical.remove_categories()中的錯誤訊息,使其始終將無效移除顯示為集合 (GH 28669)在具有 datetime 的分類 dtype 的
Series上使用日期訪問器時,其返回的物件型別與在具有該型別的Series上使用str.()/dt.()時不同。例如,當在具有重複項的Categorical上訪問Series.dt.tz_localize()時,訪問器會跳過重複項 (GH 27952)和DataFrame.replace()Series.replace()中的錯誤,在處理分類資料時會產生不正確的結果 (GH 26988)對空分類呼叫
Categorical.min()或Categorical.max()時會引發 numpy 異常的錯誤 (GH 30227)以下方法現在透過
groupby(..., observed=False)呼叫時,也能正確輸出未觀察到的類別的返回值 (GH 17605) *core.groupby.SeriesGroupBy.count()*core.groupby.SeriesGroupBy.size()*core.groupby.SeriesGroupBy.nunique()*core.groupby.SeriesGroupBy.nth()
日期時間型別#
中的錯誤,在將Series.__setitem__()np.timedelta64("NaT")插入到具有 datetime64 dtype 的Series時,會錯誤地將其轉換為np.datetime64("NaT")(GH 27311)在底層資料為只讀的情況下,
Series.dt()屬性查詢中的錯誤 (GH 27529)中的錯誤,錯誤地讀取了在 Python 2 中建立的時區屬性 (GH 26443)HDFStore.__getitem__在
to_datetime()中,當使用 errors=”coerce” 傳遞格式錯誤的str陣列時,可能會錯誤地引發ValueError的錯誤 (GH 28299)中的錯誤,core.groupby.SeriesGroupBy.nunique()NaT值干擾了唯一值計數 (GH 27951)在
Timestamp減法中,當從np.datetime64物件中減去Timestamp時,會錯誤地引發TypeError的錯誤 (GH 28286)整數或整數 dtype 陣列與
Timestamp的加法和減法現在將引發NullFrequencyError而不是ValueError(GH 28268)具有整數 dtype 的
Series和DataFrame中,在新增或減去np.datetime64物件時未能引發TypeError的錯誤 (GH 28080),Series.astype()Index.astype(), 和DataFrame.astype()中,在轉換為整數 dtype 時未能處理NaT的錯誤 (GH 28492)中,當Weekweekday新增或減去無效型別時,會錯誤地引發AttributeError而不是TypeError的錯誤 (GH 28530)在
DataFrame的算術運算中,當與 dtype 為'timedelta64[ns]'的Series進行操作時出現錯誤 (GH 28049)中,當原始 DataFrame 中的列是 datetime 且列標籤不是標準整數時,會引發core.groupby.generic.SeriesGroupBy.apply()ValueError的錯誤 (GH 28247)中的錯誤,其中 `locales -a` 將 locales 列表編碼為 windows-1252 (GH 23638, GH 24760, GH 27368)pandas._config.localization.get_locales()中,當與Series.var()timedelta64[ns]dtype 呼叫時,未能引發TypeError的錯誤 (GH 28289)和DatetimeIndex.strftime()Series.dt.strftime()中的錯誤,其中 `NaT` 被轉換為字串 `'NaT'` 而不是 `np.nan` (GH 29578)使用長度不正確的布林掩碼對 datetime 類陣列進行掩碼時,未能引發
IndexError的錯誤 (GH 30308)屬性被視為屬性而不是類屬性的錯誤 (GH 29910)Timestamp.resolution在
pandas.to_datetime()中,當使用None呼叫時,會引發TypeError而不是返回NaT的錯誤 (GH 30011)在
pandas.to_datetime()中,當使用deque物件並且使用cache=True(預設值)時失敗的錯誤 (GH 29403)(具有 datetime64 或 timedelta64 dtype)、Series.item()DatetimeIndex.item()和TimedeltaIndex.item()中,返回整數而不是Timestamp或Timedelta的錯誤 (GH 30175)在
DatetimeIndex加法中,當新增一個非最佳化DateOffset時,錯誤地丟棄了時區資訊的錯誤 (GH 30336)在
DataFrame.drop()中,當嘗試從 DatetimeIndex 中刪除不存在的值時,會產生一個令人困惑的錯誤訊息的錯誤 (GH 30399)中的錯誤,會移除新資料的時區感知性 (GH 30238)DataFrame.append()和Series.cummin()Series.cummax()中,當具有時區感知的 dtype 時,錯誤地丟棄了其時區的錯誤 (GH 15553),DatetimeArrayTimedeltaArray, 和PeriodArray中,就地加法和減法實際上並未就地操作的錯誤 (GH 24115)在
pandas.to_datetime()中,當使用儲存IntegerArray的Series呼叫時,會引發TypeError而不是返回Series的錯誤 (GH 30050)在
date_range()中,當使用自定義工作日作為freq並給定periods數量時出現的錯誤 (GH 30593)在
PeriodIndex比較中,錯誤地將整數轉換為Period物件,與Period比較行為不一致的錯誤 (GH 30722)在
DatetimeIndex.insert()中,當嘗試將時區感知的Timestamp插入到時區感知的DatetimeIndex中(反之亦然),會引發ValueError而不是TypeError的錯誤 (GH 30806)
時間差#
從
np.datetime64物件中減去TimedeltaIndex或TimedeltaArray時的錯誤 (GH 29558)
時區#
數值#
具有零列的
DataFrame呼叫DataFrame.quantile()時錯誤地引發異常 (GH 23925)具有物件 dtype 和
complex條目的DataFrame的靈活不等式比較方法(DataFrame.lt()、DataFrame.le()、DataFrame.gt()、DataFrame.ge())未能像其Series對應項那樣引發TypeError(GH 28079)的邏輯運算(DataFrame&,|,^)未能透過填充 NA 值來匹配Series的行為的錯誤 (GH 28741)在
DataFrame.interpolate()中,透過名稱指定 axis 時,引用了尚未賦值的變數的錯誤 (GH 29142)中,當使用可為空的整數 dtype series 時,未透過 ddof 引數計算正確值(或未計算正確值)的錯誤 (GH 29128)Series.var()使用 `frac` > 1 和 `replace` = False 時,錯誤訊息已改進 (GH 27451)
數字索引中的錯誤,導致可以例項化具有無效 dtype(例如 datetime 類)的
Int64Index、UInt64Index或Float64Index(GH 29539)在從包含 `np.uint64` 範圍內的值的列表中構造時發生精度損失的錯誤 (GH 29526)UInt64Index構造中的錯誤,導致在使用 `np.uint64` 範圍內的整數進行索引時索引失敗 (GH 28023)NumericIndex構造中的錯誤,導致在使用 `np.uint64` 範圍內的整數索引NumericIndexDataFrame時,將UInt64Index轉換為Float64Index(GH 28279)在
Series.interpolate()中,當使用 `method='index'` 且索引未排序時,之前會返回不正確的結果 (GH 21037)在
DataFrame.round()中,當DataFrame具有CategoricalIndex的IntervalIndex列時,會錯誤地引發TypeError的錯誤 (GH 30063)在存在重複索引時,
Series.pct_change()和DataFrame.pct_change()中的錯誤 (GH 30463)DataFrame 的累積操作(例如 cumsum、cummax)中存在一個錯誤,該錯誤會導致錯誤地轉換為 object-dtype(GH 19296)
DataFrame.diff 中存在一個錯誤,該錯誤會丟失擴充套件型別的 dtype(GH 30889)
DataFrame.diff 中存在一個錯誤,當其中一個列是可為空的整數 dtype 時,會引發 IndexError(GH 30967)
轉換#
字串#
在空的 Series 上呼叫 Series.str.isalnum()(以及其他“is 方法”)會返回 object dtype 而不是 bool(GH 29624)
Interval#
IntervalIndex.get_indexer() 中存在一個錯誤,其中 Categorical 或 CategoricalIndex target 會錯誤地引發 TypeError(GH 30063)
pandas.core.dtypes.cast.infer_dtype_from_scalar 中存在一個錯誤,當 passing pandas_dtype=True 時,不會推斷出 IntervalDtype(GH 30337)
Series 建構函式中存在一個錯誤,當從 Interval 物件列表構造 Series 時,會得到 object dtype 而不是 IntervalDtype(GH 23563)
IntervalDtype 中存在一個錯誤,其中 kind 屬性被錯誤地設定為 None 而不是 "O"(GH 30568)
IntervalIndex、IntervalArray 和包含 interval 資料的 Series 中存在一個錯誤,其中相等性比較不正確(GH 24112)
索引#
使用反向切片器進行賦值時存在一個錯誤(GH 26939)
DataFrame.explode() 中存在一個錯誤,當索引中存在重複項時,會複製 DataFrame(GH 28010)
使用包含 Period 的其他型別索引重新索引 PeriodIndex() 時存在一個錯誤(GH 28323, GH 28337)
修復透過 .loc 使用 numpy 非 ns datetime 型別進行列賦值(GH 27395)
Float64Index.astype() 中存在一個錯誤,當轉換為整數 dtype 時,np.inf 未被正確處理(GH 28475)
Index.union() 在左側包含重複項時可能失敗(GH 28257)
使用 .loc 進行索引時存在一個錯誤,其中 CategoricalIndex(非字串類別)不起作用(GH 17569, GH 30225)
Index.get_indexer_non_unique() 在某些情況下可能會因 TypeError 而失敗,例如在字串索引中搜索 ints 時(GH 28257)
Float64Index.get_loc() 中存在一個錯誤,會錯誤地引發 TypeError 而不是 KeyError(GH 29189)
DataFrame.loc() 中存在一個錯誤,當在單行 DataFrame 中設定 Categorical 值時,dtype 不正確(GH 25495)
MultiIndex.get_loc() 在輸入包含缺失值時,無法找到缺失值(GH 19132)
Series.__setitem__() 中存在一個錯誤,當新資料的長度與 True 值的數量匹配且新資料不是 Series 或 np.array 時,使用布林索引器進行賦值不正確(GH 30567)
使用 PeriodIndex 進行索引時存在一個錯誤,錯誤地接受了表示年份的整數,應使用 ser.loc["2007"] 而不是 ser.loc[2007](GH 30763)
Missing#
MultiIndex#
IO#
read_csv() 現在在使用 Python csv 引擎時接受二進位制模式檔案緩衝區(GH 23779)
DataFrame.to_json() 中存在一個錯誤,當使用 Tuple 作為列或索引值並使用 orient="columns" 或 orient="index" 時,會產生無效的 JSON(GH 20500)
改進了無窮大的解析。read_csv() 現在將 Infinity、+Infinity、-Infinity 解釋為浮點值(GH 10065)
DataFrame.to_csv() 中存在一個錯誤,當 na_rep 的長度短於文字輸入資料時,值會被截斷。(GH 25099)
DataFrame.to_string() 中存在一個錯誤,其中值被截斷,使用了顯示選項而不是輸出完整內容(GH 9784)
DataFrame.to_json() 中存在一個錯誤,當使用 orient="table" 時,datetime 列標籤不會以 ISO 格式寫入(GH 28130)
DataFrame.to_parquet() 中存在一個錯誤,當檔案不存在時,使用 engine='fastparquet' 寫入 GCS 會失敗(GH 28326)
read_hdf() 在引發異常時關閉了它未開啟的 store,存在一個錯誤(GH 28699)
DataFrame.read_json() 中存在一個錯誤,當使用 orient="index" 時,不會保持順序(GH 28557)
DataFrame.to_html() 中存在一個錯誤,其中未驗證 formatters 引數的長度(GH 28469)
DataFrame.read_excel() 使用 engine='ods' 時存在一個錯誤,當 sheet_name 引數引用不存在的工作表時(GH 27676)
pandas.io.formats.style.Styler() 格式化浮點值時存在一個錯誤,未能正確顯示小數(GH 13257)
DataFrame.to_html() 在使用 formatters=
- 和 max_cols 一起時存在一個錯誤。(GH 25955)
Styler.background_gradient() 中存在一個錯誤,無法處理 Int64 dtype(GH 28869)
DataFrame.to_clipboard() 中存在一個錯誤,該錯誤在 ipython 中不能可靠地工作(GH 22707)
read_json() 中存在一個錯誤,預設編碼未設定為 utf-8(GH 29565)
PythonParser 中存在一個錯誤,在處理 decimal 欄位時,str 和 bytes 被混合使用(GH 29650)
read_gbq() 現在接受 progress_bar_type,以便在資料下載時顯示進度條。(GH 29857)
pandas.io.json.json_normalize() 中存在一個錯誤,當 record_path 指定的位置出現缺失值時,會引發 TypeError(GH 30148)
read_excel() 現在接受二進位制資料(GH 15914)
read_csv() 中存在一個錯誤,其中編碼處理僅限於 C 引擎的 utf-16 字串(GH 24130)
繪圖#
Series.plot() 中存在一個錯誤,無法繪製布林值(GH 23719)
DataFrame.plot() 在沒有行時無法繪製,存在一個錯誤(GH 27758)
DataFrame.plot() 中存在一個錯誤,在同一軸上繪製多個系列時,會產生不正確的圖例標記(GH 18222)
DataFrame.plot() 當 kind='box' 且資料包含 datetime 或 timedelta 資料時存在一個錯誤。這些型別現在會自動刪除(GH 22799)
DataFrame.plot.line() 和 DataFrame.plot.area() 中存在一個錯誤,會在 x 軸上產生錯誤的 xlim(GH 27686, GH 25160, GH 24784)
DataFrame.boxplot() 不接受 color 引數,而 DataFrame.plot.box() 可以,存在一個錯誤(GH 26214)
DataFrame.plot.bar() 的 xticks 引數被忽略,存在一個錯誤(GH 14119)
set_option() 現在會驗證提供給 'plotting.backend' 的繪圖後端是否實現了後端,而不是在建立繪圖時進行驗證(GH 28163)
DataFrame.plot() 現在允許使用 backend 關鍵字引數,以便在一個會話中在後端之間切換(GH 28619)。
顏色驗證中存在一個錯誤,錯誤地為非顏色樣式引發了錯誤(GH 29122)。
允許 DataFrame.plot.scatter() 繪製 objects 和 datetime 型別的資料(GH 18755, GH 30391)
DataFrame.hist() 中存在一個錯誤,xrot=0 在與 by 和 subplots 一起使用時不起作用(GH 30288)。
GroupBy/resample/rolling
core.groupby.DataFrameGroupBy.apply() 中存在一個錯誤,當函式返回 Index 時,只顯示來自單個組的輸出(GH 28652)
DataFrame.groupby() 中存在一個錯誤,當有多個組時,如果任何組包含所有 NA 值,則會引發 IndexError(GH 20519)
Resampler.size() 和 Resampler.count() 中存在一個錯誤,當與空的 Series 或 DataFrame 一起使用時,返回錯誤的 dtype(GH 28427)
DataFrame.rolling() 中存在一個錯誤,當 axis=1 時,不允許對 datetimes 進行滾動(GH 28192)
DataFrame.rolling() 中存在一個錯誤,不允許在 multi-index 級別上滾動(GH 15584)。
DataFrame.rolling() 中存在一個錯誤,不允許在單調遞減時間索引上滾動(GH 19248)。
DataFrame.groupby() 中存在一個錯誤,當 axis=1 時,不提供按列名選擇(GH 27614)
core.groupby.DataFrameGroupby.agg() 中存在一個錯誤,無法在命名聚合中使用 lambda 函式(GH 27519)
DataFrame.groupby() 在按分類列分組時丟失列名資訊,存在一個錯誤(GH 28787)
移除了在 DataFrame.groupby() 和 Series.groupby() 的命名聚合中因重複輸入函式而引發的錯誤。以前如果對同一列應用相同的函式會引發錯誤,現在如果新的分配名稱不同則允許。(GH 28426)
core.groupby.SeriesGroupBy.value_counts() 在 Grouper 產生空組時也能處理這種情況(GH 28479)
core.window.rolling.Rolling.quantile() 中存在一個錯誤,在使用 groupby 時忽略了 interpolation 關鍵字引數(GH 28779)
DataFrame.groupby() 中存在一個錯誤,當使用 any、all、nunique 和 transform 函式時,會錯誤地處理重複的列標籤(GH 21668)
core.groupby.DataFrameGroupBy.agg() 中存在一個錯誤,當使用時區感知的 datetime64 列時,會錯誤地將結果強制轉換為原始 dtype(GH 29641)
DataFrame.groupby() 在使用 axis=1 且具有單層列索引時存在一個錯誤(GH 30208)
DataFrame.groupby() 在 axis=1 上使用 nunique 時存在一個錯誤(GH 30253)
DataFrameGroupBy.quantile() 和 SeriesGroupBy.quantile() 在使用多個列表類 q 值和整數列名時存在一個錯誤(GH 30289)
DataFrameGroupBy.pct_change() 和 SeriesGroupBy.pct_change() 中存在一個錯誤,當 fill_method 為 None 時會導致 TypeError(GH 30463)
Rolling.count() 和 Expanding.count() 引數中存在一個錯誤,min_periods 被忽略了(GH 26996)
Reshaping#
DataFrame.apply() 中存在一個錯誤,導致空 DataFrame 輸出不正確(GH 28202, GH 21959)
DataFrame.stack() 在建立 MultiIndex 時處理非唯一索引不正確,存在一個錯誤(GH 28301)
pivot_table() 中存在一個錯誤,當 margins=True 且 aggfunc='mean' 時,未返回正確的 float 型別(GH 24893)
merge_asof() 無法使用 datetime.timedelta 作為 tolerance kwarg,存在一個錯誤(GH 28098)
merge() 中存在一個錯誤,當使用 MultiIndex 時,suffixes 未正確附加(GH 28518)
qcut() 和 cut() 現在可以處理布林輸入(GH 20303)
修復了在使用容差值時,確保所有 int dtypes 都可以用於 merge_asof()。之前所有非 int64 型別都會引發錯誤的 MergeError(GH 28870)。
get_dummies() 當 columns 不是列表類值時,提供了更好的錯誤訊息(GH 28383)
Index.join() 中存在一個錯誤,該錯誤導致了 mismatched MultiIndex 名稱順序的無限遞迴錯誤。(GH 25760, GH 28956)
Bug:在 Series.pct_change() 中提供錨定頻率會導致 ValueError (GH 28664)
Bug:當兩個 DataFrame 的列順序不同但內容相同時,DataFrame.equals() 錯誤地返回 True (GH 28839)
Bug:DataFrame.replace() 中未尊重非數字替換器的 dtype (GH 26632)
Bug:melt() 中為 id_vars 或 value_vars 提供混合字串和數值會導致錯誤地引發 ValueError (GH 29718)
轉置 DataFrame 時,當每列都是相同的擴充套件 dtype 時,dtype 現在會被保留 (GH 30091)
Bug:merge_asof() 在對 tz-aware left_index 和 tz-aware 列的 right_on 進行合併時出現問題 (GH 29864)
cut() 和 qcut() 中當 labels=True 時的錯誤訊息和 docstring 得到改進 (GH 13318)
Bug:DataFrame.unstack() 在使用級別列表時缺少 fill_na 引數 (GH 30740)
Sparse#
ExtensionArray#
其他#
Bug:使用 set_option() 設定 display.precision、display.max_rows 或 display.max_columns 為 None 或正整數以外的值將引發 ValueError (GH 23348)
Bug:DataFrame.replace() 使用巢狀字典中重疊的鍵將不再引發錯誤,現在與扁平字典的行為一致 (GH 27660)
DataFrame.to_csv() 和 Series.to_csv() 現在支援將字典作為 compression 引數,其中 'method' 鍵是壓縮方法,其他鍵是附加的壓縮選項(當壓縮方法為 'zip' 時)。(GH 26023)
Bug:Series.diff() 中布林序列會錯誤地引發 TypeError (GH 17294)
Bug:Series.append() 在傳遞 Series 的元組時不再引發 TypeError (GH 28410)
修復了在 0d 陣列上呼叫 pandas.libs._json.encode() 時損壞的錯誤訊息 (GH 18878)
DataFrame.query() 和 DataFrame.eval() 中的反引號引用現在也可以用於使用無效識別符號,例如以數字開頭的名稱、Python 關鍵字或使用單字元運算子的名稱。(GH 27017)
Bug:pd.core.util.hashing.hash_pandas_object 中包含元組的陣列被錯誤地視為不可雜湊 (GH 28969)
Bug:DataFrame.append() 在追加空列表時引發 IndexError (GH 28769)
修復了 AbstractHolidayCalendar 在 2030 年後的年份(現在支援到 2200 年)返回結果不正確的問題 (GH 27790)
修復了 IntegerArray 在除以 0 的操作時返回 inf 而不是 NaN 的問題 (GH 27398)
修復了 IntegerArray 中當另一個值為 0 或 1 時的 pow 運算 (GH 29997)
Bug:Series.count() 在啟用 use_inf_as_na 時會引發錯誤 (GH 29478)
Bug:Index 建構函式在允許設定非雜湊名稱而未引發 TypeError 時出現問題 (GH 29069)
Bug:DataFrame 建構函式在傳遞 2D ndarray 和擴充套件 dtype 時出現問題 (GH 12513)
Bug:DataFrame.to_csv() 在提供具有 dtype="string" 和 na_rep 的 Series 時,na_rep 被截斷為 2 個字元。(GH 29975)
Bug:DataFrame.itertuples() 錯誤地確定了具有 255 列的 DataFrame 是否可以使用 namedtuples (GH 28282)
在 testing.assert_series_equal() 中處理巢狀的 NumPy object 陣列,以支援 ExtensionArray 實現 (GH 30841)
貢獻者#
本次釋出共有 308 人貢獻了補丁。名字旁邊有“+”號的人是首次貢獻補丁。
Aaditya Panikath +
Abdullah İhsan Seçer
Abhijeet Krishnan +
Adam J. Stewart
Adam Klaum +
Addison Lynch
Aivengoe +
Alastair James +
Albert Villanova del Moral
Alex Kirko +
Alfredo Granja +
Allen Downey
Alp Arıbal +
Andreas Buhr +
Andrew Munch +
Andy
Angela Ambroz +
Aniruddha Bhattacharjee +
Ankit Dhankhar +
Antonio Andraues Jr +
Arda Kosar +
Asish Mahapatra +
Austin Hackett +
Avi Kelman +
AyowoleT +
Bas Nijholt +
Ben Thayer
Bharat Raghunathan
Bhavani Ravi
Bhuvana KA +
Big Head
Blake Hawkins +
Bobae Kim +
Brett Naul
Brian Wignall
Bruno P. Kinoshita +
Bryant Moscon +
Cesar H +
Chris Stadler
Chris Zimmerman +
Christopher Whelan
Clemens Brunner
Clemens Tolboom +
Connor Charles +
Daniel Hähnke +
Daniel Saxton
Darin Plutchok +
Dave Hughes
David Stansby
DavidRosen +
Dean +
Deepan Das +
Deepyaman Datta
DorAmram +
Dorothy Kabarozi +
Drew Heenan +
Eliza Mae Saret +
Elle +
Endre Mark Borza +
Eric Brassell +
Eric Wong +
Eunseop Jeong +
Eyden Villanueva +
Felix Divo
ForTimeBeing +
Francesco Truzzi +
Gabriel Corona +
Gabriel Monteiro +
Galuh Sahid +
Georgi Baychev +
Gina
GiuPassarelli +
Grigorios Giannakopoulos +
Guilherme Leite +
Guilherme Salomé +
Gyeongjae Choi +
Harshavardhan Bachina +
Harutaka Kawamura +
Hassan Kibirige
Hielke Walinga
Hubert
Hugh Kelley +
Ian Eaves +
Ignacio Santolin +
Igor Filippov +
Irv Lustig
Isaac Virshup +
Ivan Bessarabov +
JMBurley +
Jack Bicknell +
Jacob Buckheit +
Jan Koch
Jan Pipek +
Jan Škoda +
Jan-Philip Gehrcke
Jasper J.F. van den Bosch +
Javad +
Jeff Reback
Jeremy Schendel
Jeroen Kant +
Jesse Pardue +
Jethro Cao +
Jiang Yue
Jiaxiang +
Jihyung Moon +
Jimmy Callin
Jinyang Zhou +
Joao Victor Martinelli +
Joaq Almirante +
John G Evans +
John Ward +
Jonathan Larkin +
Joris Van den Bossche
Josh Dimarsky +
Joshua Smith +
Josiah Baker +
Julia Signell +
Jung Dong Ho +
Justin Cole +
Justin Zheng
Kaiqi Dong
Karthigeyan +
Katherine Younglove +
Katrin Leinweber
Kee Chong Tan +
Keith Kraus +
Kevin Nguyen +
Kevin Sheppard
Kisekka David +
Koushik +
Kyle Boone +
Kyle McCahill +
Laura Collard, PhD +
LiuSeeker +
Louis Huynh +
Lucas Scarlato Astur +
Luiz Gustavo +
Luke +
Luke Shepard +
MKhalusova +
Mabel Villalba
Maciej J +
Mak Sze Chun
Manu NALEPA +
Marc
Marc Garcia
Marco Gorelli +
Marco Neumann +
Martin Winkel +
Martina G. Vilas +
Mateusz +
Matthew Roeschke
Matthew Tan +
Max Bolingbroke
Max Chen +
MeeseeksMachine
Miguel +
MinGyo Jung +
Mohamed Amine ZGHAL +
Mohit Anand +
MomIsBestFriend +
Naomi Bonnin +
Nathan Abel +
Nico Cernek +
Nigel Markey +
Noritada Kobayashi +
Oktay Sabak +
Oliver Hofkens +
Oluokun Adedayo +
Osman +
Oğuzhan Öğreden +
Pandas Development Team +
Patrik Hlobil +
Paul Lee +
Paul Siegel +
Petr Baev +
Pietro Battiston
Prakhar Pandey +
Puneeth K +
Raghav +
Rajat +
Rajhans Jadhao +
Rajiv Bharadwaj +
Rik-de-Kort +
Roei.r
Rohit Sanjay +
Ronan Lamy +
Roshni +
Roymprog +
Rushabh Vasani +
Ryan Grout +
Ryan Nazareth
Samesh Lakhotia +
Samuel Sinayoko
Samyak Jain +
Sarah Donehower +
Sarah Masud +
Saul Shanabrook +
Scott Cole +
SdgJlbl +
Seb +
Sergei Ivko +
Shadi Akiki
Shorokhov Sergey
Siddhesh Poyarekar +
Sidharthan Nair +
Simon Gibbons
Simon Hawkins
Simon-Martin Schröder +
Sofiane Mahiou +
Sourav kumar +
Souvik Mandal +
Soyoun Kim +
Sparkle Russell-Puleri +
Srinivas Reddy Thatiparthy (శ్రీనివాస్ రెడ్డి తాటిపర్తి)
Stuart Berg +
Sumanau Sareen
Szymon Bednarek +
Tambe Tabitha Achere +
Tan Tran
Tang Heyi +
Tanmay Daripa +
Tanya Jain
Terji Petersen
Thomas Li +
Tirth Jain +
Tola A +
Tom Augspurger
Tommy Lynch +
Tomoyuki Suzuki +
Tony Lorenzo
Unprocessable +
Uwe L. Korn
Vaibhav Vishal
Victoria Zdanovskaya +
Vijayant +
Vishwak Srinivasan +
WANG Aiyong
Wenhuan
Wes McKinney
Will Ayd
Will Holmgren
William Ayd
William Blan +
Wouter Overmeire
Wuraola Oyewusi +
YaOzI +
Yash Shukla +
Yu Wang +
Yusei Tahara +
alexander135 +
alimcmaster1
avelineg +
bganglia +
bolkedebruin
bravech +
chinhwee +
cruzzoe +
dalgarno +
daniellebrown +
danielplawrence
est271 +
francisco souza +
ganevgv +
garanews +
gfyoung
h-vetinari
hasnain2808 +
ianzur +
jalbritt +
jbrockmendel
jeschwar +
jlamborn324 +
joy-rosie +
kernc
killerontherun1
krey +
lexy-lixinyu +
lucyleeow +
lukasbk +
maheshbapatu +
mck619 +
nathalier
naveenkaushik2504 +
nlepleux +
nrebena
ohad83 +
pilkibun
pqzx +
proost +
pv8493013j +
qudade +
rhstanton +
rmunjal29 +
sangarshanan +
sardonick +
saskakarsi +
shaido987 +
ssikdar1
steveayers124 +
tadashigaki +
timcera +
tlaytongoogle +
tobycheese
tonywu1999 +
tsvikas +
yogendrasoni +
zys5945 +