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 的所有 levelscodes,這在視覺上不美觀,並且使輸出更難導航。例如(限制範圍為 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 將列表類值拆分為行#

SeriesDataFrame 獲得了 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() 的關鍵字 logylogxloglog 現在可以接受值 'sym' 用於 symlog 縮放。(GH 24867)

  • 在使用 to_datetime() 解析日期時間時,添加了對 ISO 週年份格式(‘%G-%V-%u’)的支援 (GH 16607)。

  • 現在,DataFrameSeries 的索引可以接受零維 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,則始終返回一個未排序的 Int64Indexsort=None 是預設值,如果可能,則返回一個單調遞增的 RangeIndex,否則返回一個已排序的 Int64Index (GH 24471)。

  • TimedeltaIndex.intersection() 現在也支援 sort 關鍵字 (GH 24471)。

  • DataFrame.rename() 現在支援 errors 引數,以在嘗試重新命名不存在的鍵時引發錯誤 (GH 13473)。

  • 為處理稀疏值 DataFrame 添加了 稀疏訪問器 (GH 25681)。

  • RangeIndex 獲得了 startstopstep 屬性 (GH 25710)。

  • 現在支援將 datetime.timezone 物件作為時區方法和建構函式的引數 (GH 25065)。

  • DataFrame.query()DataFrame.eval() 現在支援使用反引號引用列名,以引用包含空格的名稱 (GH 6508)。

  • merge_asof() 現在會為類別合併鍵不相等的情況提供更清晰的錯誤訊息 (GH 26136)。

  • Rolling() 支援指數(或泊松)視窗型別 (GH 21303)。

  • 缺少必需匯入的錯誤訊息現在包含原始匯入錯誤的文字 (GH 23868)。

  • DatetimeIndexTimedeltaIndex 現在有一個 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)。

  • IntervalIntervalIndexIntervalArray 獲得了 is_empty 屬性,用於指示給定的區間是否為空 (GH 27219)。

向後不相容的 API 更改#

使用帶 UTC 偏移量的日期字串進行索引#

以前,使用帶 UTC 偏移量的日期字串索引 DataFrameSeries 會忽略 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() 現在會返回一個具有稀疏值的 SeriesDataFrame,而不是 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() 提供任何 SparseSeriesSparseDataFrame 將像以前一樣導致返回 SparseSeriesSparseDataFrame

.str 訪問器執行更嚴格的型別檢查#

由於缺乏更精細的資料型別,Series.str 到目前為止只檢查資料是否為 object 資料型別。現在,Series.str 將推斷 Series 內部的資料型別;特別是,僅包含 'bytes' 的資料將引發異常(除了 Series.str.decode()Series.str.get()Series.str.len()Series.str.slice()),請參閱 GH 23163GH 23011GH 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 不再返回組標籤#

DataFrameGroupByffillbfillpadbackfill 方法以前會將組標籤包含在返回值中,這與其他 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 索引來查詢 SeriesDataFrame

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__)或 locSeriesDataFrame 中進行選擇,現在僅為 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 25725GH 24942GH 25752)。此外,還更新了一些依賴項的最低支援版本(GH 23519GH 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

有關更多資訊,請參閱DependenciesOptional dependencies

其他 API 更改#

棄用#

稀疏子類#

SparseSeriesSparseDataFrame 子類已棄用。它們的功能可以透過具有稀疏值的 SeriesDataFrame 來更好地提供。

以前的方式

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

其他棄用#

移除先前版本的棄用/更改#

效能改進#

  • 顯著加速了 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() 產生了一個錯誤的警告,提示未來將丟擲 KeyErrorGH 22252)。

  • 當使用單層 MultiIndex 的重索引資料框呼叫 DataFrame.to_csv() 時,導致了段錯誤(GH 26303)。

  • 修復了將 arrays.PandasArray 賦值給 DataFrame 時會引發錯誤的問題(GH 26390)。

  • 允許在 DataFrame.query() 字串中使用可呼叫區域性引用的關鍵字引數(GH 26426)。

  • 修復了使用包含單個缺失標籤的列表索引 MultiIndex 級別時出現的 KeyError 錯誤(GH 27148)。

  • MultiIndex 中部分匹配 Timestamp 時,產生 AttributeError 的錯誤(GH 26944)。

  • CategoricalCategoricalIndex 中,使用 in 運算子(__contains)進行 Interval 值比較時,與 Interval 中的值不相容的物件進行比較,錯誤地引發了異常(GH 23705)。

  • 在具有單個時區感知 datetime64[ns] 列的 DataFrame 上使用 DataFrame.loc()DataFrame.iloc() 時,錯誤地返回標量而不是 SeriesGH 27110)。

  • CategoricalIndexCategorical 中,當使用 in 運算子(__contains__)傳入列表時,錯誤地引發了 ValueError 而不是 TypeErrorGH 21729)。

  • Series 中設定具有 Timedelta 物件的新值時,錯誤地將值強制轉換為整數(GH 22717)。

  • Series 中使用時區感知日期時間設定新鍵(__setitem__)時,錯誤地引發了 ValueErrorGH 12862)。

  • 在使用只讀索引器索引 DataFrame.iloc() 時出現錯誤(GH 17192)。

  • Series 中使用時區感知日期時間設定現有元組鍵(__setitem__)時,錯誤地引發了 TypeErrorGH 20441)。

Missing#

MultiIndex#

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.nanGH 25468)。

  • DataFrame.to_html() 現在在使用 classes 引數時,如果傳入無效型別,會引發 TypeError 而不是 AssertionErrorGH 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 的限制時,會引發 ValueErrorGH 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() 會引發 TypeErrorGH 11926)。

  • to_msgpack()read_msgpack() 中,對於無效路徑會引發 ValueError 而不是 FileNotFoundError 的錯誤(GH 27160)。

  • 修復了 DataFrame.to_parquet() 中,當資料幀沒有列時會引發 ValueError 的錯誤(GH 27339)。

  • 允許在 read_csv() 中解析 PeriodDtype 列(GH 26934)。

繪圖#

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)。

  • 在使用 groupbyMultiIndex Series 進行分組,並且傳入的標籤列表長度等於 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, WindowExponentialMovingWindow 函式,使其從結果中排除無關的列而不是引發錯誤,並且僅當所有列都無關時才引發 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,兩條具有相同 freqDatetimeIndex 會丟失其 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)。

  • DataFrame 建構函式中,傳遞非空元組會導致段錯誤 (GH 25691)

  • 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_sentinelExtensionArray 時 (GH 25696)。

  • Series.count() 錯誤地計算了 ExtensionArrays 中的 NA 值 (GH 26835)

  • 添加了 Series.__array_ufunc__ 以更好地處理應用於基於擴充套件陣列的 Series 的 NumPy ufuncs (GH 23293)。

  • ExtensionArray.copy() 中移除了關鍵字引數 deep (GH 27083)

其他#

  • 從 vendored UltraJSON 實現中移除了未使用的 C 函式 (GH 26198)

  • 允許將 IndexRangeIndex 傳遞給 numpy 的 minmax 函式 (GH 26125)

  • Series 子類的空物件 repr 中使用實際類名 (GH 27001)。

  • DataFrame 中存在一個 bug,當傳遞一個包含時區感知 datetime 物件的物件陣列時,會錯誤地引發 ValueError (GH 13287)

貢獻者#

總共有 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 +