2.2.0 版本新增內容(2024 年 1 月 19 日)#

以下是 pandas 2.2.0 中的更改。請參閱 發行說明 獲取包含其他 pandas 版本的完整變更日誌。

pandas 3.0 的即將進行的更改#

pandas 3.0 將為 pandas 的預設行為帶來兩項重大更改。

寫時複製#

當前可選的寫時複製模式將在 pandas 3.0 中預設啟用。將不再提供保留當前行為的選項。新的行為語義在 關於寫時複製的使用者指南 中進行了說明。

自 pandas 2.0 起,可以使用以下選項啟用新行為:

pd.options.mode.copy_on_write = True

此更改帶來了 pandas 在副本和檢視處理方式上的行為差異。其中一些更改允許進行明確的棄用,例如鏈式賦值的更改。其他更改則更為微妙,因此警告被隱藏在一個可以在 pandas 2.2 中啟用的選項後面。

pd.options.mode.copy_on_write = "warn"

此模式會在許多與大多數查詢無關的場景中發出警告。我們建議您探索此模式,但並非必須消除所有這些警告。 遷移指南 詳細解釋了升級過程。

預設情況下使用專用的字串資料型別(基於 Arrow)#

過去,pandas 使用 NumPy 的 object 資料型別來表示字串列。這種表示方法存在許多問題,包括效能低下和記憶體佔用量大。在 pandas 3.0 中,這種情況將有所改變。pandas 將開始將字串列推斷為新的 string 資料型別,該型別基於 Arrow,能在記憶體中連續地表示字串。這將帶來巨大的效能和記憶體改進。

舊行為

In [1]: ser = pd.Series(["a", "b"])
Out[1]:
0    a
1    b
dtype: object

新行為

In [1]: ser = pd.Series(["a", "b"])
Out[1]:
0    a
1    b
dtype: string

在這些場景中使用的字串資料型別在很大程度上將表現得像 NumPy object 一樣,包括缺失值語義和這些列上的通用操作。

此更改在 API 中包含一些額外的更改。

  • 目前,指定 dtype="string" 會建立一個由 Python 字串支援的資料型別,這些字串儲存在 NumPy 陣列中。在 pandas 3.0 中,這種情況將發生改變,此資料型別將建立一個由 Arrow 支援的字串列。

  • 列名和索引也將由 Arrow 字串支援。

  • 為適應此更改,PyArrow 將成為 pandas 3.0 的必需依賴項。

可以使用以下方法啟用此未來的資料型別推斷邏輯:

pd.options.future.infer_string = True

增強功能#

to_sql 和 read_sql 支援 ADBC 驅動程式#

read_sql()to_sql() 現在可以與 Apache Arrow ADBC 驅動程式一起使用。與透過 SQLAlchemy 使用的傳統驅動程式相比,ADBC 驅動程式應能提供顯著的效能改進、更好的型別支援和更清晰的 nullability 處理。

import adbc_driver_postgresql.dbapi as pg_dbapi

df = pd.DataFrame(
    [
        [1, 2, 3],
        [4, 5, 6],
    ],
    columns=['a', 'b', 'c']
)
uri = "postgresql://postgres:postgres@localhost/postgres"
with pg_dbapi.connect(uri) as conn:
    df.to_sql("pandas_table", conn, index=False)

# for round-tripping
with pg_dbapi.connect(uri) as conn:
    df2 = pd.read_sql("pandas_table", conn)

Arrow 型別系統提供了更廣泛的型別,可以更緊密地匹配 PostgreSQL 等資料庫提供的型別。為了說明這一點,請注意以下(非詳盡的)資料庫型別和 pandas 後端可用型別列表:

numpy/pandas

arrow

postgres

sqlite

int16/Int16

int16

SMALLINT

INTEGER

int32/Int32

int32

INTEGER

INTEGER

int64/Int64

int64

BIGINT

INTEGER

float32

float32

REAL

REAL

float64

float64

DOUBLE PRECISION

REAL

物件

string

TEXT

TEXT

bool

bool_

BOOLEAN

datetime64[ns]

timestamp(us)

TIMESTAMP

datetime64[ns,tz]

timestamp(us,tz)

TIMESTAMPTZ

date32

DATE

month_day_nano_interval

INTERVAL

binary

BINARY

BLOB

decimal128

DECIMAL [1]

list

ARRAY [1]

struct

COMPOSITE TYPE

[1]

腳註

如果您希望在 DataFrame 的整個生命週期中儘可能保留資料庫型別,鼓勵使用者利用 read_sql()dtype_backend="pyarrow" 引數。

# for round-tripping
with pg_dbapi.connect(uri) as conn:
    df2 = pd.read_sql("pandas_table", conn, dtype_backend="pyarrow")

這將防止您的資料被轉換為傳統的 pandas/NumPy 型別系統,後者經常以無法進行往返轉換的方式轉換 SQL 型別。

有關 ADBC 驅動程式的完整列表及其開發狀態,請參閱 ADBC 驅動程式實現狀態 文件。

基於一個或多個條件建立 pandas Series#

添加了 Series.case_when() 函式,用於基於一個或多個條件建立 Series 物件。(GH 39154

In [1]: import pandas as pd

In [2]: df = pd.DataFrame(dict(a=[1, 2, 3], b=[4, 5, 6]))

In [3]: default=pd.Series('default', index=df.index)

In [4]: default.case_when(
   ...:      caselist=[
   ...:          (df.a == 1, 'first'),                              # condition, replacement
   ...:          (df.a.gt(1) & df.b.eq(5), 'second'),  # condition, replacement
   ...:      ],
   ...: )
   ...: 
Out[4]: 
0      first
1     second
2    default
dtype: str

to_numpy 用於 NumPy 可空型別和 Arrow 型別,轉換為合適的 NumPy dtype#

對於 NumPy 可空型別和 Arrow 型別,to_numpy 現在將轉換為合適的 NumPy dtype,而不是可空型別和 PyArrow 後備擴充套件 dtype 的 object dtype。

舊行為

In [1]: ser = pd.Series([1, 2, 3], dtype="Int64")
In [2]: ser.to_numpy()
Out[2]: array([1, 2, 3], dtype=object)

新行為

In [5]: ser = pd.Series([1, 2, 3], dtype="Int64")

In [6]: ser.to_numpy()
Out[6]: array([1, 2, 3])

In [7]: ser = pd.Series([1, 2, 3], dtype="timestamp[ns][pyarrow]")

In [8]: ser.to_numpy()
Out[8]: 
array(['1970-01-01T00:00:00.000000001', '1970-01-01T00:00:00.000000002',
       '1970-01-01T00:00:00.000000003'], dtype='datetime64[ns]')

預設 NumPy dtype(不帶任何引數)確定如下:

  • 浮點數 dtype 將被轉換為 NumPy 浮點數。

  • 不包含缺失值的整數 dtype 將被轉換為 NumPy 整數 dtype。

  • 包含缺失值的整數 dtype 將被轉換為 NumPy 浮點數 dtype,並使用 NaN 作為缺失值指示符。

  • 不包含缺失值的布林值 dtype 將被轉換為 NumPy bool dtype。

  • 包含缺失值的布林值 dtype 將保留 object dtype。

  • 日期時間和時間差型別分別被轉換為 NumPy datetime64 和 timedelta64 型別,並使用 NaT 作為缺失值指示符。

Series.struct 訪問器,用於 PyArrow 結構化資料#

Series.struct 訪問器提供了用於處理具有 struct[pyarrow] dtype 的 Series 的屬性和方法。例如,Series.struct.explode() 將 PyArrow 結構化資料轉換為 pandas DataFrame。(GH 54938

In [9]: import pyarrow as pa

In [10]: series = pd.Series(
   ....:     [
   ....:         {"project": "pandas", "version": "2.2.0"},
   ....:         {"project": "numpy", "version": "1.25.2"},
   ....:         {"project": "pyarrow", "version": "13.0.0"},
   ....:     ],
   ....:     dtype=pd.ArrowDtype(
   ....:         pa.struct([
   ....:             ("project", pa.string()),
   ....:             ("version", pa.string()),
   ....:         ])
   ....:     ),
   ....: )
   ....: 

In [11]: series.struct.explode()
Out[11]: 
   project version
0   pandas   2.2.0
1    numpy  1.25.2
2  pyarrow  13.0.0

使用 Series.struct.field() 來索引(可能巢狀的)結構欄位。

In [12]: series.struct.field("project")
Out[12]: 
0     pandas
1      numpy
2    pyarrow
Name: project, dtype: string[pyarrow]

Series.list 訪問器,用於 PyArrow 列表資料#

Series.list 訪問器提供了用於處理具有 list[pyarrow] dtype 的 Series 的屬性和方法。例如,Series.list.__getitem__() 允許索引 Series 中的 pyarrow 列表。(GH 55323

In [13]: import pyarrow as pa

In [14]: series = pd.Series(
   ....:     [
   ....:         [1, 2, 3],
   ....:         [4, 5],
   ....:         [6],
   ....:     ],
   ....:     dtype=pd.ArrowDtype(
   ....:         pa.list_(pa.int64())
   ....:     ),
   ....: )
   ....: 

In [15]: series.list[0]
Out[15]: 
0    1
1    4
2    6
dtype: int64[pyarrow]

read_excel() 的 Calamine 引擎#

read_excel() 添加了 calamine 引擎。它使用 python-calamine,該庫提供了 Rust 庫 calamine 的 Python 繫結。該引擎支援 Excel 檔案(.xlsx, .xlsm, .xls, .xlsb)和 OpenDocument 電子表格(.ods)(GH 50395)。

此引擎有兩個優點:

  1. Calamine 通常比其他引擎更快,一些基準測試顯示其速度比 'openpyxl' 快 5 倍,比 'odf' 快 20 倍,比 'pyxlsb' 快 4 倍,比 'xlrd' 快 1.5 倍。但是,'openpyxl' 和 'pyxlsb' 由於對行進行惰性迭代,在讀取大型檔案的前幾行時速度更快。

  2. Calamine 支援識別 .xlsb 檔案中的日期時間,而 'pyxlsb' 是 pandas 中唯一可以讀取 .xlsb 檔案的引擎。

pd.read_excel("path_to_file.xlsb", engine="calamine")

更多資訊請參閱使用者指南 IO 工具中的 Calamine(Excel 和 ODS 檔案)

其他增強功能#

重要的 bug 修復#

這些 bug 修復可能帶來行為上的顯著變化。

merge 和 DataFrame.join 現在一致遵循文件化的排序行為#

在之前的 pandas 版本中,merge()DataFrame.join() 並不能總是返回符合文件化排序行為的結果。pandas 現在在 merge 和 join 操作中遵循文件化的排序行為。(GH 54611, GH 56426, GH 56443)。

如文件所述,sort=True 會在生成的 DataFrame 中按字典順序對連線鍵進行排序。當 sort=False 時,連線鍵的順序取決於連線型別(how 引數)。

  • how="left":保留左鍵的順序。

  • how="right":保留右鍵的順序。

  • how="inner":保留左鍵的順序。

  • how="outer":按字典順序排序鍵。

一個具有行為變化的示例是,當左連線鍵非唯一且 sort=False 時進行內連線:

In [16]: left = pd.DataFrame({"a": [1, 2, 1]})

In [17]: right = pd.DataFrame({"a": [1, 2]})

In [18]: result = pd.merge(left, right, how="inner", on="a", sort=False)

舊行為

In [5]: result
Out[5]:
   a
0  1
1  1
2  2

新行為

In [19]: result
Out[19]: 
   a
0  1
1  2
2  1

merge 和 DataFrame.join 在級別不同時不再重新排序級別#

在之前的 pandas 版本中,merge()DataFrame.join() 會在連線兩個級別不同的索引時重新排序索引級別。(GH 34133)。

In [20]: left = pd.DataFrame({"left": 1}, index=pd.MultiIndex.from_tuples([("x", 1), ("x", 2)], names=["A", "B"]))

In [21]: right = pd.DataFrame({"right": 2}, index=pd.MultiIndex.from_tuples([(1, 1), (2, 2)], names=["B", "C"]))

In [22]: left
Out[22]: 
     left
A B      
x 1     1
  2     1

In [23]: right
Out[23]: 
     right
B C       
1 1      2
2 2      2

In [24]: result = left.join(right)

舊行為

In [5]: result
Out[5]:
       left  right
B A C
1 x 1     1      2
2 x 2     1      2

新行為

In [25]: result
Out[25]: 
       left  right
A B C             
x 1 1     1      2
  2 2     1      2

提高了依賴項的最低版本#

對於 可選依賴項,通用建議是使用最新版本。低於最低測試版本的可選依賴項可能仍然有效,但未被視為受支援。下表列出了最低測試版本已提高的可選依賴項。

新最低版本

beautifulsoup4

4.11.2

blosc

1.21.3

bottleneck

1.3.6

fastparquet

2022.12.0

fsspec

2022.11.0

gcsfs

2022.11.0

lxml

4.9.2

matplotlib

3.6.3

numba

0.56.4

numexpr

2.8.4

qtpy

2.3.0

openpyxl

3.1.0

psycopg2

2.9.6

pyreadstat

1.2.0

pytables

3.8.0

pyxlsb

1.0.10

s3fs

2022.11.0

scipy

1.10.0

sqlalchemy

2.0.0

tabulate

0.9.0

xarray

2022.12.0

xlsxwriter

3.0.5

zstandard

0.19.0

pyqt5

5.15.8

tzdata

2022.7

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

其他 API 更改#

棄用#

鏈式賦值#

為準備 pandas 3.0 中對副本/檢視行為的更大更改(寫時複製(CoW),PDEP-7),我們開始棄用 *鏈式賦值*。

鏈式賦值發生在您嘗試透過兩次連續的索引操作來更新 pandas DataFrame 或 Series 時。根據這些操作的型別和順序,目前它有時有效,有時無效。

一個典型的例子如下:

df = pd.DataFrame({"foo": [1, 2, 3], "bar": [4, 5, 6]})

# first selecting rows with a mask, then assigning values to a column
# -> this has never worked and raises a SettingWithCopyWarning
df[df["bar"] > 5]["foo"] = 100

# first selecting the column, and then assigning to a subset of that column
# -> this currently works
df["foo"][df["bar"] > 5] = 100

這個鏈式賦值的第二個例子目前可以更新原始 df。這在 pandas 3.0 中將不再有效,因此我們開始棄用此行為。

>>> df["foo"][df["bar"] > 5] = 100
FutureWarning: ChainedAssignmentError: behaviour will change in pandas 3.0!
You are setting values through chained assignment. Currently this works in certain cases, but when using Copy-on-Write (which will become the default behaviour in pandas 3.0) this will never work to update the original DataFrame or Series, because the intermediate object on which we are setting values will behave as a copy.
A typical example is when you are setting values in a column of a DataFrame, like:

df["col"][row_indexer] = value

Use `df.loc[row_indexer, "col"] = values` instead, to perform the assignment in a single step and ensure this keeps updating the original `df`.

See the caveats in the documentation: https://pandas.numpy.tw/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy

您可以透過移除鏈式賦值的使用來修復此警告並確保您的程式碼為 pandas 3.0 做好準備。通常,可以透過一次性完成賦值來做到這一點,例如使用 .loc。對於上面的例子,我們可以這樣做:

df.loc[df["bar"] > 5, "foo"] = 100

同樣的棄用也適用於以鏈式方式執行的原地方法,例如:

>>> df["foo"].fillna(0, inplace=True)
FutureWarning: A value is trying to be set on a copy of a DataFrame or Series through chained assignment using an inplace method.
The behavior will change in pandas 3.0. This inplace method will never work because the intermediate object on which we are setting values always behaves as a copy.

For example, when doing 'df[col].method(value, inplace=True)', try using 'df.method({col: value}, inplace=True)' or df[col] = df[col].method(value) instead, to perform the operation inplace on the original object.

當目標是更新 DataFrame df 中的列時,這裡的替代方法是直接在 df 本身上呼叫方法,例如 df.fillna({"foo": 0}, inplace=True)

更多詳情請參閱 遷移指南

棄用別名 M, Q, Y 等,轉而使用 ME, QE, YE 等作為偏移量#

棄用了以下頻率別名(GH 9586):

偏移量

已棄用的別名

新別名

MonthEnd

M

ME

BusinessMonthEnd

BM

BME

SemiMonthEnd

SM

SME

CustomBusinessMonthEnd

CBM

CBME

QuarterEnd

Q

QE

BQuarterEnd

BQ

BQE

YearEnd

Y

YE

BYearEnd

BY

BYE

例如:

先前行為:

In [8]: pd.date_range('2020-01-01', periods=3, freq='Q-NOV')
Out[8]:
DatetimeIndex(['2020-02-29', '2020-05-31', '2020-08-31'],
              dtype='datetime64[ns]', freq='Q-NOV')

未來行為:

In [26]: pd.date_range('2020-01-01', periods=3, freq='QE-NOV')
Out[26]: DatetimeIndex(['2020-02-29', '2020-05-31', '2020-08-31'], dtype='datetime64[us]', freq='QE-NOV')

棄用自動向下轉換#

棄用了在多種方法中對 object dtype 結果的自動向下轉換。這些轉換會因行為依賴於值而悄悄地以一種難以預測的方式改變 dtype。此外,pandas 正在逐步淘汰靜默的 dtype 更改(GH 54710, GH 54261)。

這些方法包括:

為了在未來複制當前行為,請顯式呼叫 DataFrame.infer_objects()

result = result.infer_objects(copy=False)

或者,使用 astype 顯式將所有浮點數轉換為整數。

設定以下選項以選擇未來的行為:

In [9]: pd.set_option("future.no_silent_downcasting", True)

其他棄用項#

  • 更改了 Timedelta.resolution_string(),使其返回 h, min, s, ms, us, 和 ns,而不是 H, T, S, L, U, 和 N,以相容頻率別名的相應棄用(GH 52536)。

  • 棄用了 offsets.Day.delta, offsets.Hour.delta, offsets.Minute.delta, offsets.Second.delta, offsets.Milli.delta, offsets.Micro.delta, offsets.Nano.delta,請改用 pd.Timedelta(obj)。(GH 55498

  • 棄用了 pandas.api.types.is_interval()pandas.api.types.is_period(),請改用 isinstance(obj, pd.Interval)isinstance(obj, pd.Period)。(GH 55264

  • 棄用了 read_gbq()DataFrame.to_gbq()。請改用 pandas_gbq.read_gbqpandas_gbq.to_gbq,請參閱 https://pandas-gbq.readthedocs.io/en/latest/api.html。(GH 55525

  • 已棄用 DataFrameGroupBy.fillna()SeriesGroupBy.fillna();使用 DataFrameGroupBy.ffill()DataFrameGroupBy.bfill() 進行向前填充和向後填充,或者使用 DataFrame.fillna() 進行單一值填充(或 Series 等效方法)(GH 55718

  • 已棄用 DateOffset.is_anchored(),對於非 Tick 子類,請使用 obj.n == 1(對於 Tick,此值始終為 False)(GH 55388

  • 已棄用 DatetimeArray.__init__()TimedeltaArray.__init__(),請使用 array() 代替(GH 55623

  • 已棄用 Index.format(),請使用 index.astype(str)index.map(formatter) 代替(GH 55413

  • 已棄用 Series.ravel(),底層陣列已經是 1D 的,因此 ravel 是不必要的(GH 52511

  • 已棄用使用 PeriodIndex(以及 'convention' 關鍵字)的 Series.resample()DataFrame.resample(),請在重取樣之前使用 .to_timestamp() 轉換為 DatetimeIndex 進行重取樣(GH 53481)。注意:此棄用在 pandas 2.3.3 中已撤銷(GH 57033

  • 已棄用 Series.view(),請使用 Series.astype() 來更改 dtype(GH 20251

  • 已棄用 offsets.Tick.is_anchored(),請使用 False 代替(GH 55388

  • 已棄用 core.internals 中的成員 BlockExtensionBlockDatetimeTZBlock,請使用公共 API 代替(GH 55139

  • 已棄用 PeriodIndex 建構函式中的 yearmonthquarterdayhourminutesecond 關鍵字,請使用 PeriodIndex.from_fields() 代替(GH 55960

  • 已棄用在 Index.view() 中將型別作為引數傳遞,請改用不帶任何引數的呼叫(GH 55709

  • 已棄用在 date_range()timedelta_range()period_range()interval_range() 中允許非整數 periods 引數(GH 56036

  • 已棄用在 DataFrame.to_clipboard() 中允許非關鍵字引數(GH 54229

  • 已棄用在 DataFrame.to_csv() 中允許非關鍵字引數,除了 path_or_bufGH 54229

  • 已棄用在 DataFrame.to_dict() 中允許非關鍵字引數(GH 54229

  • 已棄用在 DataFrame.to_excel() 中允許非關鍵字引數,除了 excel_writerGH 54229

  • 已棄用在 DataFrame.to_gbq() 中允許非關鍵字引數,除了 destination_tableGH 54229

  • 已棄用在 DataFrame.to_hdf() 中允許非關鍵字引數,除了 path_or_bufGH 54229

  • 已棄用在 DataFrame.to_html() 中允許非關鍵字引數,除了 bufGH 54229

  • 已棄用在 DataFrame.to_json() 中允許非關鍵字引數,除了 path_or_bufGH 54229

  • 已棄用在 DataFrame.to_latex() 中允許非關鍵字引數,除了 bufGH 54229

  • 已棄用在 DataFrame.to_markdown() 中允許非關鍵字引數,除了 bufGH 54229

  • 已棄用在 DataFrame.to_parquet() 中允許非關鍵字引數,除了 pathGH 54229

  • 已棄用在 DataFrame.to_pickle() 中允許非關鍵字引數,除了 pathGH 54229

  • 已棄用在 DataFrame.to_string() 中允許非關鍵字引數,除了 bufGH 54229

  • 已棄用在 DataFrame.to_xml() 中允許非關鍵字引數,除了 path_or_bufferGH 54229

  • 已棄用將 BlockManager 物件傳遞給 DataFrame 或將 SingleBlockManager 物件傳遞給 SeriesGH 52419

  • 已棄用 Index.insert() 在物件 dtype 索引上的行為,該行為會默默地對結果執行型別推斷,請改為顯式呼叫 result.infer_objects(copy=False) 以保留舊行為(GH 51363

  • 已棄用在 datetime64timedelta64PeriodDtype 資料型別上,使用 Series.isin()Index.isin() 將非日期時間類值(主要是字串)強制轉換為這些型別(GH 53111

  • 已棄用在 IndexSeriesDataFrame 建構函式中,當提供 pandas 輸入時進行 dtype 推斷,請改為在輸入上呼叫 .infer_objects 以保留當前行為(GH 56012

  • 已棄用在將 Index 設定到 DataFrame 時進行 dtype 推斷,請改為顯式轉換(GH 56102

  • DataFrameGroupBy.apply()DataFrameGroupBy.resample() 中,已棄用在計算時包含組的行為;請傳遞 include_groups=False 來排除組(GH 7155

  • 已棄用使用長度為零的布林索引器對 Index 進行索引(GH 55820

  • 已棄用當按長度為 1 的列表類進行分組時,將元組傳遞給 DataFrameGroupBy.get_groupSeriesGroupBy.get_group 的行為(GH 25971

  • 已棄用 YearBegin 中表示頻率的字串 AS,以及表示具有不同會計年度開始的年度頻率的字串 AS-DECAS-JAN 等(GH 54275

  • 已棄用 YearEnd 中表示頻率的字串 A,以及表示具有不同會計年度結束的年度頻率的字串 A-DECA-JAN 等(GH 54275

  • 已棄用 BYearBegin 中表示頻率的字串 BAS,以及表示具有不同會計年度開始的年度頻率的字串 BAS-DECBAS-JAN 等(GH 54275

  • 已棄用 BYearEnd 中表示頻率的字串 BA,以及表示具有不同會計年度結束的年度頻率的字串 BA-DECBA-JAN 等(GH 54275

  • 已棄用 HourBusinessHourCustomBusinessHour 中表示頻率的字串 HBHCBHGH 52536

  • 已棄用 to_timedelta() 中表示單位的字串 HSUNGH 52536

  • 已棄用 Timedelta 中表示單位的字串 HTSLUNGH 52536

  • 已棄用 MinuteSecondMilliMicroNano 中表示頻率的字串 TSLUNGH 52536

  • 已棄用在 read_csv() 中結合解析的日期時間列和 keep_date_col 關鍵字的行為(GH 55569

  • 已棄用 DataFrameGroupBy.grouperSeriesGroupBy.grouper;這些屬性將在 pandas 的未來版本中移除(GH 56521

  • 已棄用 Grouping 屬性 group_indexresult_indexgroup_arraylike;這些屬性將在 pandas 的未來版本中移除(GH 56148

  • 已棄用 read_csv()read_table() 中的 delim_whitespace 關鍵字,請使用 sep="\\s+" 代替(GH 55569

  • 已棄用 to_datetime()to_timedelta()to_numeric() 中的 errors="ignore" 選項,請改為顯式捕獲異常(GH 54467

  • 已棄用 Series 建構函式中的 fastpath 關鍵字(GH 20110

  • 已棄用 Series.resample()DataFrame.resample() 中的 kind 關鍵字,請改為顯式轉換物件的 indexGH 55895

  • 已棄用 PeriodIndex 中的 ordinal 關鍵字,請使用 PeriodIndex.from_ordinals() 代替(GH 55960

  • 已棄用 TimedeltaIndex 構造中的 unit 關鍵字,請使用 to_timedelta() 代替(GH 55499

  • 已棄用 read_csv()read_table() 中的 verbose 關鍵字(GH 55569

  • 已棄用 CategoricalDtypeDataFrame.replace()Series.replace() 結合的行為;在未來的版本中,replace 將在保留類別的同時更改值。要更改類別,請使用 ser.cat.rename_categories 代替(GH 55147

  • 已棄用 Series.value_counts()Index.value_counts() 與物件 dtype 結合時的行為;在未來的版本中,這些將不會對結果 Index 執行 dtype 推斷,請執行 result.index = result.index.infer_objects() 來保留舊行為(GH 56161

  • 已棄用 DataFrame.pivot_table()observed=False 的預設值;在未來版本中將為 TrueGH 56236

  • 已棄用擴充套件測試類 BaseNoReduceTestsBaseBooleanReduceTestsBaseNumericReduceTests,請使用 BaseReduceTests 代替(GH 54663

  • 已棄用選項 mode.data_managerArrayManager;未來版本中將只提供 BlockManagerGH 55043

  • 已棄用 DataFrame.stack 的先前實現;請指定 future_stack=True 以採用未來的版本(GH 53515

效能改進#

Bug 修復#

分類#

  • 錯誤:Categorical.isin() 在分類包含重疊 Interval 值時,會引發 InvalidIndexErrorGH 34974

  • 錯誤:在 CategoricalDtype.__eq__() 中,對於具有混合型別的未排序分類資料,返回 FalseGH 55468

  • 錯誤:使用 pa.DictionaryArray 作為類別,將 pa.dictionary 轉換為 CategoricalDtype 時(GH 56672

日期時間型別#

  • 錯誤:在構造 DatetimeIndex 時,同時傳入 tzdayfirstyearfirst,會忽略 dayfirst/yearfirstGH 55813

  • 錯誤:在 DatetimeIndex 中,傳入一個物件型別 ndarray 的浮點數物件和一個 tz,會導致不正確的本地化(GH 55780

  • 錯誤:在 Series.isin() 中,當 dtype 是 DatetimeTZDtype 並且比較值為全 NaT 時,會錯誤地返回全 False,即使 Series 包含 NaT 條目(GH 56427

  • 錯誤:在 concat() 中,當連線全 NA DataFrame 和 DatetimeTZDtype dtype DataFrame 時,會引發 AttributeErrorGH 52093

  • 錯誤:在 testing.assert_extension_array_equal() 中,比較解析度時可能使用了錯誤的單位(GH 55730

  • 錯誤:在 to_datetime()DatetimeIndex 中,當傳入混合字串和數字型別的列表時,會錯誤地引發異常(GH 55780

  • 錯誤:在 to_datetime()DatetimeIndex 中,當傳入具有混合時區或混合時區感知的混合型別物件時,未能引發 ValueErrorGH 55693

  • 錯誤:在 Tick.delta() 中,處理非常大的 tick 時,會引發 OverflowError 而不是 OutOfBoundsTimedeltaGH 55503

  • 錯誤:在 DatetimeIndex.shift() 中,處理非納秒解析度時,會錯誤地以納秒解析度返回結果(GH 56117

  • 錯誤:在 DatetimeIndex.union() 中,當處理具有相同 timezone 但不同單位的時區感知索引時,會返回 object dtype(GH 55238

  • 錯誤:在 Index.is_monotonic_increasing()Index.is_monotonic_decreasing() 中,當索引的第一個值是 NaT 時,會錯誤地將 Index.is_unique() 快取為 TrueGH 55755

  • 錯誤:在將 Index 檢視轉換為非支援解析度的 datetime64 dtype 時,會錯誤地引發異常(GH 55710

  • 錯誤:在 Series.dt.round() 中,當處理非納秒解析度和 NaT 條目時,會錯誤地引發 OverflowErrorGH 56158

  • 錯誤:在 Series.fillna() 中,當處理非納秒解析度 dtype 和更高解析度的向量值時,會返回不正確(內部損壞)的結果(GH 56410

  • 錯誤:在 Timestamp.unit() 中,從具有分鐘或小時解析度和時區偏移的 ISO8601 格式字串推斷單位不正確(GH 56208

  • 錯誤:在 .astype 將更高解析度的 datetime64 dtype 轉換為較低解析度的 datetime64 dtype(例如 datetime64[us]->datetime64[ms])時,會 silently 溢位接近下限的值(GH 55979

  • 錯誤:在向具有非納秒解析度的 datetime64 SeriesIndexDataFrame 列新增或減去 Week 偏移量時,會返回不正確的結果(GH 55583

  • 錯誤:在向非納秒 IndexSeriesDataFrame 列新增或減去具有 offset 屬性的 BusinessDay 偏移量時,會給出不正確的結果(GH 55608

  • 錯誤:在向具有非納秒解析度的 datetime64 IndexSeriesDataFrame 列新增或減去具有微秒元件的 DateOffset 物件時(GH 55595

  • 錯誤:在新增或減去非常大的 Tick 物件與 TimestampTimedelta 物件時,會引發 OverflowError 而不是 OutOfBoundsTimedeltaGH 55503

  • 錯誤:在建立具有非納秒 DatetimeTZDtypeIndexSeriesDataFrame 時,如果輸入會導致在納秒解析度下越界,則會錯誤地引發 OutOfBoundsDatetimeGH 54620

  • 錯誤:在建立具有非納秒 datetime64(或 DatetimeTZDtype)的 IndexSeriesDataFrame 時,將混合數字輸入視為納秒,而不是 dtype 單位的倍數(這在非混合數字輸入時會發生)(GH 56004

  • 錯誤:在建立具有非納秒 datetime64 dtype 的 IndexSeriesDataFrame 時,如果輸入對於 datetime64[ns] 超出範圍,則會錯誤地引發 OutOfBoundsDatetimeGH 55756

  • 錯誤:在解析具有非 ISO8601 格式的納秒解析度的日期時間字串時,會錯誤地截斷亞微秒分量(GH 56051

  • 錯誤:在解析具有亞秒解析度和尾隨零的日期時間字串時,會錯誤地推斷秒或毫秒解析度(GH 55737

  • 錯誤:在 to_datetime() 中,當傳入浮點數 dtype 引數且 unitTimestamp 的逐點結果不匹配時,結果不正確(GH 56037

  • 修復了迴歸問題:concat() 在連線具有不同解析度的 datetime64 列時會引發錯誤(GH 53641

時間差#

  • 錯誤:在 Timedelta 構造中,會引發 OverflowError 而不是 OutOfBoundsTimedeltaGH 55503

  • 錯誤:在渲染(__repr__)具有非納秒解析度 timedelta64 值的 TimedeltaIndexSeries 時,如果所有條目都是 24 小時的倍數,則未能使用納秒情況下的緊湊表示(GH 55405

時區#

  • 錯誤:在 AbstractHolidayCalendar 中,計算假期時未傳播時區資料(GH 54580

  • 錯誤:在 Timestamp 構造中,當傳入一個模稜兩可的值和 pytz 時區時,未能引發 pytz.AmbiguousTimeErrorGH 55657

  • 錯誤:在 Timestamp.tz_localize() 中,當 nonexistent="shift_forward" 並且在 DST 期間圍繞 UTC+0 時(GH 51501

數值#

轉換#

  • 錯誤:在 DataFrame.astype() 中,當使用 str 對解封(unpickled)的陣列呼叫時,陣列可能會原地更改(GH 54654

  • 錯誤:在 DataFrame.astype() 中,當 errors="ignore" 時,對於擴充套件型別無效(GH 54654

  • 錯誤:在 DataFrame.loc() 中,分配一個具有不同 dtype 的 Series(使用完整的列設定器,例如 df.loc[:, 'a'] = incompatible_value)時,未丟擲“不相容的 dtype 警告”(請參閱 PDEP6)(GH 39584

  • Series.convert_dtypes() 在將所有 NA 列轉換為 null[pyarrow] 時出現錯誤(GH 55346)

字串#

  • pandas.api.types.is_string_dtype() 在檢查不包含元素的 object 陣列是否為 string dtype 時出現錯誤(GH 54661)

  • DataFrame.apply() 在 engine="numba" 且列或索引具有 StringDtype 時出現錯誤(GH 56189)

  • DataFrame.reindex() 在匹配具有 string[pyarrow_numpy] dtype 的 Index 時出現錯誤(GH 56106)

  • Index.str.cat() 始終將結果強制轉換為 object dtype 時出現錯誤(GH 56157)

  • ArrowDtype 配合 pyarrow.string dtype 和 pyarrow 後端的 string[pyarrow] 的 Series.__mul__() 出現錯誤(GH 51970)

  • Series.str.find() 在 start < 0 且 dtype 為 pyarrow.string 的 ArrowDtype 時出現錯誤(GH 56411)

  • Series.str.fullmatch() 在 dtype=pandas.ArrowDtype(pyarrow.string()) 時,允許正則表示式在字面值 //$ 結尾時出現部分匹配,從而出現錯誤(GH 56652)

  • Series.str.replace() 在 n < 0 且 dtype 為 pyarrow.string 的 ArrowDtype 時出現錯誤(GH 56404)

  • Series.str.startswith() 和 Series.str.endswith() 在使用 tuple[str, ...] 型別的引數且 dtype 為 pyarrow.string 的 ArrowDtype 時出現錯誤(GH 56579)

  • Series.str.startswith() 和 Series.str.endswith() 在使用 tuple[str, ...] 型別的引數且 dtype 為 string[pyarrow] 時出現錯誤(GH 54942)

  • dtype="string[pyarrow_numpy]" 的比較操作在 dtypes 無法比較時引發錯誤(GH 56008)

Interval#

  • Interval __repr__ 未顯示 Timestamp 界限的 UTC 偏移量,並顯示時、分、秒元件(GH 55015)

  • IntervalIndex.factorize() 和 Series.factorize() 在具有 datetime64 或 timedelta64 間隔的 IntervalDtype 時,未保留非納秒單位(GH 56099)

  • IntervalIndex.from_arrays() 在傳入具有不匹配解析度的 datetime64 或 timedelta64 陣列時,構建無效的 IntervalArray 物件(GH 55714)

  • IntervalIndex.from_tuples() 在子型別是可空擴充套件 dtype 時引發錯誤(GH 56765)

  • IntervalIndex.get_indexer() 在具有 datetime 或 timedelta 間隔時,錯誤地匹配整數目標(GH 47772)

  • IntervalIndex.get_indexer() 在具有時區感知的 datetime 間隔時,錯誤地匹配無時區目標序列(GH 47772)

  • 在具有 IntervalIndex 的 Series 上使用切片設定值時出現錯誤(GH 54722)

索引#

  • DataFrame.loc() 在 DataFrame 具有 MultiIndex 時,修改布林索引器(GH 56635)

  • DataFrame.loc() 在將具有擴充套件 dtype 的 Series 設定為 NumPy dtype 時出現錯誤(GH 55604)

  • Index.difference() 在 other 為空或被視為不可比較時,未返回唯一值集(GH 55113)

  • 將 Categorical 值設定到具有 numpy dtypes 的 DataFrame 中時引發 RecursionError(GH 52927)

  • 修復了在設定單個字串值時,建立帶有缺失值的新列時出現的錯誤(GH 56204)

Missing#

  • DataFrame.update() 對於帶時區感知的 datetime64 dtypes 未就地更新(GH 56227)

MultiIndex#

  • MultiIndex.get_indexer() 在提供 method 且索引非單調時,未引發 ValueError(GH 53452)

I/O#

  • read_csv() 在 engine="python" 且指定了 skiprows 時,未遵守 chunksize 引數(GH 56323)

  • read_csv() 在 engine="python" 且指定了可呼叫 skiprows 和 chunk size 時,引發 TypeError(GH 55677)

  • read_csv() 在 on_bad_lines="warn" 時,將錯誤寫入 stderr 而非引發 Python 警告;現在會引發 errors.ParserWarning(GH 54296)

  • read_csv() 在 engine="pyarrow" 時,quotechar 被忽略(GH 52266)

  • read_csv() 在 engine="pyarrow" 時,usecols 在使用沒有頭的 CSV 時不起作用(GH 54459)

  • read_excel() 在 engine="xlrd"(xls 檔案)時,當檔案包含 NaN 或 Inf 時出錯(GH 54564)

  • read_json() 在 infer_string 設定為 True 時,未正確處理 dtype 轉換(GH 56195)

  • DataFrame.to_excel() 在 OdsWriter(ods 檔案)時,寫入布林/字串值(GH 54994)

  • DataFrame.to_hdf() 和 read_hdf() 在具有非納秒解析度的 datetime64 dtypes 時,未能正確地進行往返(GH 55622)

  • DataFrame.to_stata() 在擴充套件 dtype 時引發錯誤(GH 54671)

  • read_excel() 在 engine="odf"(ods 檔案)時,當字串單元格包含註釋時出現錯誤(GH 55200)

  • read_excel() 在沒有快取格式化單元格的 ODS 檔案(用於浮點值)時出現錯誤(GH 55219)

  • DataFrame.to_json() 在遇到不受支援的 NumPy 型別時,會引發 OverflowError 而非 TypeError(GH 55403)

Period#

  • PeriodIndex 建構函式在同時傳遞 data、ordinal 和 **fields 中的兩個以上時,未能引發 ValueError(GH 55961)

  • Period 加法會靜默地環繞,而不是引發 OverflowError(GH 55503)

  • 從具有非納秒單位的 PeriodDtype 使用 astype 強制轉換為 datetime64 或 DatetimeTZDtype 時,錯誤地以納秒單位返回(GH 55958)

繪圖#

  • DataFrame.plot.box() 在 vert=False 和使用 sharey=True 建立的 Matplotlib Axes 時出現錯誤(GH 54941)

  • DataFrame.plot.scatter() 丟棄字串列(GH 56142)

  • Series.plot() 重用 ax 物件時,在傳遞 how 關鍵字時未引發錯誤(GH 55953)

Groupby/resample/rolling#

  • DataFrameGroupBy.idxmin()、DataFrameGroupBy.idxmax()、SeriesGroupBy.idxmin() 和 SeriesGroupBy.idxmax() 在索引是包含 NA 值的 CategoricalIndex 時,不會保留 Categorical dtype(GH 54234)

  • DataFrameGroupBy.transform() 和 SeriesGroupBy.transform() 在 observed=False 且 f="idxmin" 或 f="idxmax" 時,會錯誤地對未觀察到的類別引發錯誤(GH 54234)

  • DataFrameGroupBy.value_counts() 和 SeriesGroupBy.value_counts() 在 DataFrame 的列或 Series 的名稱為整數時,可能導致排序不正確(GH 55951)

  • DataFrameGroupBy.value_counts() 和 SeriesGroupBy.value_counts() 未能在 DataFrame.groupby() 和 Series.groupby() 中遵守 sort=False(GH 55951)

  • DataFrameGroupBy.value_counts() 和 SeriesGroupBy.value_counts() 在 sort=True 和 normalize=True 時,會按比例而不是頻率排序(GH 55951)

  • DataFrame.asfreq() 和 Series.asfreq() 在具有非納秒解析度的 DatetimeIndex 時,錯誤地轉換為納秒解析度(GH 55958)

  • DataFrame.ewm() 在傳入具有非納秒 datetime64 或 DatetimeTZDtype 的 times 時出現錯誤(GH 56262)

  • DataFrame.groupby() 和 Series.groupby() 在按 Decimal 和 NA 值組合進行分組時,如果 sort=True 會出錯(GH 54847)

  • DataFrame.groupby() 對於 DataFrame 子類,在選擇子集列以應用函式時出現錯誤(GH 56761)

  • DataFrame.resample() 在 BusinessDay 時,未遵守 closed 和 label 引數(GH 55282)

  • DataFrame.resample() 在對 pyarrow.timestamp 或 pyarrow.duration 型別的 ArrowDtype 進行重取樣時出現錯誤(GH 55989)

  • DataFrame.resample() 在 BusinessDay 的 bin 邊緣不正確(GH 55281)

  • DataFrame.resample() 在 MonthBegin 的 bin 邊緣不正確(GH 55271)

  • DataFrame.rolling() 和 Series.rolling() 在 closed='left' 和 closed='neither' 時,重複的日期時間類索引被視為連續而不是相等(GH 20712)

  • DataFrame.rolling() 和 Series.rolling() 在 index 或 on 列是 ArrowDtype 且型別為 pyarrow.timestamp 時出現錯誤(GH 55849)

Reshaping#

Sparse#

  • arrays.SparseArray.take() 中,使用與陣列填充值不同的填充值時的錯誤 (GH 55181)

其他#

貢獻者#

本次釋出共有 162 位貢獻者提交了補丁。名字旁有“+”的表示首次貢獻補丁。

  • AG

  • Aaron Rahman +

  • Abdullah Ihsan Secer +

  • Abhijit Deo +

  • Adrian D’Alessandro

  • Ahmad Mustafa Anis +

  • Amanda Bizzinotto

  • Amith KK +

  • Aniket Patil +

  • Antonio Fonseca +

  • Artur Barseghyan

  • Ben Greiner

  • Bill Blum +

  • Boyd Kane

  • Damian Kula

  • Dan King +

  • Daniel Weindl +

  • Daniele Nicolodi

  • David Poznik

  • David Toneian +

  • Dea María Léon

  • Deepak George +

  • Dmitriy +

  • Dominique Garmier +

  • Donald Thevalingam +

  • Doug Davis +

  • Dukastlik +

  • Elahe Sharifi +

  • Eric Han +

  • Fangchen Li

  • Francisco Alfaro +

  • Gadea Autric +

  • Guillaume Lemaitre

  • Hadi Abdi Khojasteh

  • Hedeer El Showk +

  • Huanghz2001 +

  • Isaac Virshup

  • Issam +

  • Itay Azolay +

  • Itayazolay +

  • Jaca +

  • Jack McIvor +

  • JackCollins91 +

  • James Spencer +

  • Jay

  • Jessica Greene

  • Jirka Borovec +

  • JohannaTrost +

  • John C +

  • Joris Van den Bossche

  • José Lucas Mayer +

  • José Lucas Silva Mayer +

  • João Andrade +

  • Kai Mühlbauer

  • Katharina Tielking, MD +

  • Kazuto Haruguchi +

  • Kevin

  • Lawrence Mitchell

  • Linus +

  • Linus Sommer +

  • Louis-Émile Robitaille +

  • Luke Manley

  • Lumberbot (aka Jack)

  • Maggie Liu +

  • MainHanzo +

  • Marc Garcia

  • Marco Edward Gorelli

  • MarcoGorelli

  • Martin Šícho +

  • Mateusz Sokół

  • Matheus Felipe +

  • Matthew Roeschke

  • Matthias Bussonnier

  • Maxwell Bileschi +

  • Michael Tiemann

  • Michał Górny

  • Molly Bowers +

  • Moritz Schubert +

  • NNLNR +

  • Natalia Mokeeva

  • Nils Müller-Wendt +

  • Omar Elbaz

  • Pandas Development Team

  • Paras Gupta +

  • Parthi

  • Patrick Hoefler

  • Paul Pellissier +

  • Paul Uhlenbruck +

  • Philip Meier

  • Philippe THOMY +

  • Quang Nguyễn

  • Raghav

  • Rajat Subhra Mukherjee

  • Ralf Gommers

  • Randolf Scholz +

  • Richard Shadrach

  • Rob +

  • Rohan Jain +

  • Ryan Gibson +

  • Sai-Suraj-27 +

  • Samuel Oranyeli +

  • Sara Bonati +

  • Sebastian Berg

  • Sergey Zakharov +

  • Shyamala Venkatakrishnan +

  • StEmGeo +

  • Stefanie Molin

  • Stijn de Gooijer +

  • Thiago Gariani +

  • Thomas A Caswell

  • Thomas Baumann +

  • Thomas Guillet +

  • Thomas Lazarus +

  • Thomas Li

  • Tim Hoffmann

  • Tim Swast

  • Tom Augspurger

  • Toro +

  • Torsten Wörtwein

  • Ville Aikas +

  • Vinita Parasrampuria +

  • Vyas Ramasubramani +

  • William Andrea

  • William Ayd

  • Willian Wang +

  • Xiao Yuan

  • Yao Xiao

  • Yves Delley

  • Zemux1613 +

  • Ziad Kermadi +

  • aaron-robeson-8451 +

  • aram-cinnamon +

  • caneff +

  • ccccjone +

  • chris-caballero +

  • cobalt

  • color455nm +

  • denisrei +

  • dependabot[bot]

  • jbrockmendel

  • jfadia +

  • johanna.trost +

  • kgmuzungu +

  • mecopur +

  • mhb143 +

  • morotti +

  • mvirts +

  • omar-elbaz

  • paulreece

  • pre-commit-ci[bot]

  • raj-thapa

  • rebecca-palmer

  • rmhowe425

  • rohanjain101

  • shiersansi +

  • smij720

  • srkds +

  • taytzehao

  • torext

  • vboxuser +

  • xzmeng +

  • yashb +