These are the changes in pandas 2.2.0. See Release notes for a full changelog
including other versions of pandas.
Upcoming changes in pandas 3.0
pandas 3.0 will bring two bigger changes to the default behavior of pandas.
Copy-on-Write
The currently optional mode Copy-on-Write will be enabled by default in pandas 3.0. There
won’t be an option to keep the current behavior enabled. The new behavioral semantics are
explained in the user guide about Copy-on-Write.
The new behavior can be enabled since pandas 2.0 with the following option:
pd.options.mode
.
copy_on_write
=
True
This change brings different changes in behavior in how pandas operates with respect to
copies and views. Some of these changes allow a clear deprecation, like the changes in
chained assignment. Other changes are more subtle and thus, the warnings are hidden behind
an option that can be enabled in pandas 2.2.
pd.options.mode.copy_on_write="warn"
This mode will warn in many different scenarios that aren’t actually relevant to
most queries. We recommend exploring this mode, but it is not necessary to get rid
of all of these warnings. The migration guide
explains the upgrade process in more detail.
Dedicated string data type (backed by Arrow) by default
Historically, pandas represented string columns with NumPy object data type. This
representation has numerous problems, including slow performance and a large memory
footprint. This will change in pandas 3.0. pandas will start inferring string columns
as a new string data type, backed by Arrow, which represents strings contiguous in memory. This brings
a huge performance and memory improvement.
Old behavior:
In [1]: ser=pd.Series(["a","b"])Out[1]:0 a1 bdtype: object
New behavior:
In [1]: ser=pd.Series(["a","b"])Out[1]:0 a1 bdtype: string
The string data type that is used in these scenarios will mostly behave as NumPy
object would, including missing value semantics and general operations on these
columns.
This change includes a few additional changes across the API:
Currently, specifying dtype="string" creates a dtype that is backed by Python strings
which are stored in a NumPy array. This will change in pandas 3.0, this dtype
will create an Arrow backed string column.
The column names and the Index will also be backed by Arrow strings.
PyArrow will become a required dependency with pandas 3.0 to accommodate this change.
This future dtype inference logic can be enabled with:
pd.options.future.infer_string=True
Enhancements
ADBC Driver support in to_sql and read_sql
read_sql() and to_sql() now work with Apache Arrow ADBC drivers. Compared to
traditional drivers used via SQLAlchemy, ADBC drivers should provide
significant performance improvements, better type support and cleaner
nullability handling.
importadbc_driver_postgresql.dbapiaspg_dbapidf=pd.DataFrame([[1,2,3],[4,5,6],],columns=['a','b','c'])uri="postgresql://postgres:postgres@localhost/postgres"withpg_dbapi.connect(uri)asconn:df.to_sql("pandas_table",conn,index=False)# for round-trippingwithpg_dbapi.connect(uri)asconn:df2=pd.read_sql("pandas_table",conn)
The Arrow type system offers a wider array of types that can more closely match
what databases like PostgreSQL can offer. To illustrate, note this (non-exhaustive)
listing of types available in different databases and pandas backends:
numpy/pandas
arrow
postgres
sqlite
int16/Int16
int16
SMALLINT
INTEGER
int32/Int32
int32
Footnotes
If you are interested in preserving database types as best as possible
throughout the lifecycle of your DataFrame, users are encouraged to
leverage the dtype_backend="pyarrow" argument of read_sql()
# for round-trippingwithpg_dbapi.connect(uri)asconn:df2=pd.read_sql("pandas_table",conn,dtype_backend="pyarrow")
This will prevent your data from being converted to the traditional pandas/NumPy
type system, which often converts SQL types in ways that make them impossible to
round-trip.
Create a pandas Series based on one or more conditions
The Series.case_when() function has been added to create a Series object based on one or more conditions. (GH 39154)
In [1]: importpandasaspdIn [2]: df=pd.DataFrame(dict(a=[1,
to_numpy for NumPy nullable and Arrow types converts to suitable NumPy dtype
to_numpy for NumPy nullable and Arrow types will now convert to a
suitable NumPy dtype instead of object dtype for nullable and PyArrow backed extension dtypes.
Old behavior:
In [1]: ser=pd.Series([1,2,3],dtype="Int64")In [2]:
Series.struct accessor for PyArrow structured data
The Series.struct accessor provides attributes and methods for processing
data with struct[pyarrow] dtype Series. For example,
Series.struct.explode() converts PyArrow structured data to a pandas
DataFrame. (GH 54938)
In [9]: importpyarrowaspaIn [10]: series=pd.Series
Series.list accessor for PyArrow list data
The Series.list accessor provides attributes and methods for processing
data with list[pyarrow] dtype Series. For example,
Series.list.__getitem__() allows indexing pyarrow lists in
a Series. (GH 55323)
In [13]: importpyarrowaspaIn [14]: series=pd.Series
The calamine engine was added to read_excel().
It uses python-calamine, which provides Python bindings for the Rust library calamine.
This engine supports Excel files (.xlsx, .xlsm, .xls, .xlsb) and OpenDocument spreadsheets () ().
Other enhancements
to_sql() with method parameter set to multi works with Oracle on the backend
In previous versions of pandas, merge() and DataFrame.join() did not
always return a result that followed the documented sort behavior. pandas now
follows the documented sort behavior in merge and join operations (GH 54611, GH 56426, GH 56443).
As documented, sort=True sorts the join keys lexicographically in the resulting
DataFrame. With sort=False, the order of the join keys depends on the
join type (how keyword):
how="left": preserve the order of the left keys
how="right": preserve the order of the right keys
how="inner": preserve the order of the left keys
how="outer": sort keys lexicographically
One example with changing behavior is inner joins with non-unique left join keys
and sort=False:
In [16]: left=pd.DataFrame({"a":[1,2,1]})In [17]: right=pd.DataFrame({"a":[1,2]})In [18]: result=pd.merge(
In previous versions of pandas, merge() and DataFrame.join() would reorder
index levels when joining on two indexes with different levels (GH 34133).
In [20]:
Increased minimum versions for dependencies
For optional dependencies the general recommendation is to use the latest version.
Optional dependencies below the lowest tested version may still work but are not considered supported.
The following table lists the optional dependencies that have had their minimum tested version increased.
Package
New Minimum Version
beautifulsoup4
4.11.2
blosc
1.21.3
Other API changes
The hash values of nullable extension dtypes changed to improve the performance of the hashing operation (GH 56507)
In preparation of larger upcoming changes to the copy / view behaviour in pandas 3.0
(Copy-on-Write (CoW), PDEP-7), we started deprecating chained assignment.
Chained assignment occurs when you try to update a pandas DataFrame or Series through
two subsequent indexing operations. Depending on the type and order of those operations
this currently does or does not work.
A typical example is as follows:
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 SettingWithCopyWarningdf[df["bar"]>5]["foo"]=100# first selecting the column, and then assigning to a subset of that column# -> this currently worksdf["foo"][df["bar"]>5]=100
This second example of chained assignment currently works to update the original df.
This will no longer work in pandas 3.0, and therefore we started deprecating this:
>>> df["foo"][df["bar"]>5]=100FutureWarning: 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] = valueUse `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.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy
You can fix this warning and ensure your code is ready for pandas 3.0 by removing
the usage of chained assignment. Typically, this can be done by doing the assignment
in a single step using for example .loc. For the example above, we can do:
df.loc[df["bar"]>5,"foo"]=100
The same deprecation applies to inplace methods that are done in a chained manner, such as:
>>> 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.
When the goal is to update the column in the DataFrame df, the alternative here is
to call the method on df itself, such as df.fillna({"foo":0},inplace=True).
Deprecate aliases M, Q, Y, etc. in favour of ME, QE, YE, etc. for offsets
Deprecated the following frequency aliases (GH 9586):
offsets
deprecated aliases
Deprecated automatic downcasting
Deprecated the automatic downcasting of object dtype results in a number of
methods. These would silently change the dtype in a hard to predict manner since the
behavior was value dependent. Additionally, pandas is moving away from silent dtype
changes (GH 54710, GH 54261).
Changed Timedelta.resolution_string() to return h, min, s, ms, us, and ns instead of H, T, S, L, , and , for compatibility with respective deprecations in frequency aliases ()
Bug in CategoricalDtype.__eq__() returning False for unordered categorical data with mixed types (GH 55468)
Bug when casting pa.dictionary to CategoricalDtype using a pa.DictionaryArray as categories (GH 56672)
Datetimelike
Bug in DatetimeIndex construction when passing both a tz and either dayfirst or yearfirst ignoring dayfirst/yearfirst (GH 55813)
Bug in DatetimeIndex when passing an object-dtype ndarray of float objects and a tz incorrectly localizing the result (GH 55780)
Bug in with dtype and comparison values that are all incorrectly returning all- even if the series contains entries ()
Timedelta
Bug in Timedelta construction raising OverflowError instead of OutOfBoundsTimedelta (GH 55503)
Bug in rendering (__repr__) of TimedeltaIndex and Series with timedelta64 values with non-nanosecond resolution entries that are all multiples of 24 hours failing to use the compact representation used in the nanosecond cases (GH 55405)
Timezones
Bug in AbstractHolidayCalendar where timezone data was not propagated when computing holiday observances (GH 54580)
Bug in Timestamp construction with an ambiguous value and a pytz timezone failing to raise pytz.AmbiguousTimeError (GH 55657)
Bug in Interval__repr__ not displaying UTC offsets for Timestamp bounds. Additionally the hour, minute and second components will now be shown (GH 55015)
Bug in IntervalIndex.factorize() and Series.factorize() with with datetime64 or timedelta64 intervals not preserving non-nanosecond units ()
Calamine is often faster than other engines, some benchmarks show results up to 5x faster than ‘openpyxl’, 20x - ‘odf’, 4x - ‘pyxlsb’, and 1.5x - ‘xlrd’.
But, ‘openpyxl’ and ‘pyxlsb’ are faster in reading a few rows from large files because of lazy iteration over rows.
Calamine supports the recognition of datetime in .xlsb files, unlike ‘pyxlsb’ which is the only other engine in pandas that can read .xlsb files.
read_csv() now supports on_bad_lines parameter with engine="pyarrow" (GH 54480)
read_sas() returns datetime64 dtypes with resolutions better matching those stored natively in SAS, and avoids returning object-dtype in cases that cannot be stored with datetime64[ns] dtype (GH 56127)
Improved error message that appears in DatetimeIndex.to_period() with frequencies which are not supported as period frequencies, such as "BMS" (GH 56243)
Improved error message when constructing Period with invalid offsets such as "QS" (GH 55785)
The dtypes string[pyarrow] and string[pyarrow_numpy] now both utilize the large_string type from PyArrow to avoid overflow for long columns (GH 56259)
left
,
right
,
how
=
"inner"
,
on
=
"a"
,
sort
=
False
)
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
)
Old Behavior
In [5]: resultOut[5]: left rightB A C1 x 1 1 22 x 2 1 2
New Behavior
In [25]: resultOut[25]: left rightA B C x 1 1 1 2 2 2 1 2
Deprecated pandas.api.types.is_interval() and pandas.api.types.is_period(), use isinstance(obj,pd.Interval) and isinstance(obj,pd.Period) instead (GH 55264)
Deprecated allowing passing BlockManager objects to DataFrame or SingleBlockManager objects to Series (GH 52419)
Deprecated behavior of Index.insert() with an object-dtype index silently performing type inference on the result, explicitly call result.infer_objects(copy=False) for the old behavior instead (GH 51363)
Deprecated dtype inference in Index, Series and DataFrame constructors when giving a pandas input, call .infer_objects on the input to keep the current behavior (GH 56012)
Deprecated dtype inference when setting a Index into a DataFrame, cast explicitly instead (GH 56102)
Deprecated indexing an Index with a boolean indexer of length zero (GH 55820)
Deprecated not passing a tuple to DataFrameGroupBy.get_group or SeriesGroupBy.get_group when grouping by a length-1 list-like (GH 25971)
Deprecated string AS denoting frequency in YearBegin and strings AS-DEC, AS-JAN, etc. denoting annual frequencies with various fiscal year starts (GH 54275)
Deprecated string A denoting frequency in YearEnd and strings A-DEC, A-JAN, etc. denoting annual frequencies with various fiscal year ends (GH 54275)
Deprecated string BAS denoting frequency in BYearBegin and strings BAS-DEC, BAS-JAN, etc. denoting annual frequencies with various fiscal year starts (GH 54275)
Deprecated string BA denoting frequency in BYearEnd and strings BA-DEC, BA-JAN, etc. denoting annual frequencies with various fiscal year ends (GH 54275)
Deprecated strings H, BH, and CBH denoting frequencies in Hour, BusinessHour, CustomBusinessHour (GH 52536)
Deprecated the behavior of DataFrame.replace() and Series.replace() with CategoricalDtype; in a future version replace will change the values while preserving the categories. To change the categories, use ser.cat.rename_categories instead (GH 55147)
Deprecated the behavior of Series.value_counts() and Index.value_counts() with object dtype; in a future version these will not perform dtype inference on the resulting Index, do result.index=result.index.infer_objects() to retain the old behavior (GH 56161)
Bug in to_datetime() and DatetimeIndex when passing mixed-type objects with a mix of timezones or mix of timezone-awareness failing to raise ValueError (GH 55693)
Bug in Tick.delta() with very large ticks raising OverflowError instead of OutOfBoundsTimedelta (GH 55503)
Bug in DatetimeIndex.shift() with non-nanosecond resolution incorrectly returning with nanosecond resolution (GH 56117)
Bug in DatetimeIndex.union() returning object dtype for tz-aware indexes with the same timezone but different units (GH 55238)
Bug in Index.view() to a datetime64 dtype with non-supported resolution incorrectly raising (GH 55710)
Bug in Series.dt.round() with non-nanosecond resolution and NaT entries incorrectly raising OverflowError (GH 56158)
Bug in Series.fillna() with non-nanosecond resolution dtypes and higher-resolution vector values returning incorrect (internally-corrupted) results (GH 56410)
Bug in Timestamp.unit() being inferred incorrectly from an ISO8601 format string with minute or hour resolution and a timezone offset (GH 56208)
Bug in .astype converting from a higher-resolution datetime64 dtype to a lower-resolution datetime64 dtype (e.g. datetime64[us]->datetime64[ms]) silently overflowing with values near the lower implementation bound (GH 55979)
Bug in adding or subtracting a Week offset to a datetime64Series, Index, or DataFrame column with non-nanosecond resolution returning incorrect results (GH 55583)
Bug in addition or subtraction of BusinessDay offset with offset attribute to non-nanosecond Index, Series, or DataFrame column giving incorrect results (GH 55608)
Bug in addition or subtraction of DateOffset objects with microsecond components to datetime64Index, Series, or DataFrame columns with non-nanosecond resolution (GH 55595)
Bug in addition or subtraction of very large Tick objects with Timestamp or Timedelta objects raising OverflowError instead of OutOfBoundsTimedelta (GH 55503)
Bug in creating a Index, Series, or DataFrame with a non-nanosecond DatetimeTZDtype and inputs that would be out of bounds with nanosecond resolution incorrectly raising OutOfBoundsDatetime (GH 54620)
Bug in creating a Index, Series, or DataFrame with a non-nanosecond datetime64 (or DatetimeTZDtype) from mixed-numeric inputs treating those as nanoseconds instead of as multiples of the dtype’s unit (which would happen with non-mixed numeric inputs) (GH 56004)
Bug in creating a Index, Series, or DataFrame with a non-nanosecond datetime64 dtype and inputs that would be out of bounds for a datetime64[ns] incorrectly raising OutOfBoundsDatetime (GH 55756)
Bug in parsing datetime strings with nanosecond resolution with non-ISO8601 formats incorrectly truncating sub-microsecond components (GH 56051)
Bug in parsing datetime strings with sub-second resolution and trailing zeros incorrectly inferring second or millisecond resolution (GH 55737)
Bug in the results of to_datetime() with an floating-dtype argument with unit not matching the pointwise results of Timestamp (GH 56037)
Fixed regression where concat() would raise an error when concatenating datetime64 columns with differing resolutions (GH 53641)
Bug in :meth:DataFrame.loc was not throwing “incompatible dtype warning” (see PDEP6) when assigning a Series with a different dtype using a full column setter (e.g. df.loc[:,'a']=incompatible_value) (GH 39584)
Bug in IntervalIndex.from_arrays() when passed datetime64 or timedelta64 arrays with mismatched resolutions constructing an invalid IntervalArray object (GH 55714)
Bug in read_csv() where on_bad_lines="warn" would write to stderr instead of raising a Python warning; this now yields a errors.ParserWarning (GH 54296)
Bug in read_csv() with engine="pyarrow" where quotechar was ignored (GH 52266)
Bug in read_csv() with engine="pyarrow" where usecols wasn’t working with a CSV with no headers (GH 54459)
Bug in read_excel(), with engine="xlrd" (xls files) erroring when the file contains NaN or Inf (GH 54564)
Bug in read_json() not handling dtype conversion properly if infer_string is set (GH 56195)
Bug in read_excel() with engine="odf" (ods files) when a string cell contains an annotation (GH 55200)
Bug in read_excel() with an ODS file without cached formatted cell for float values (GH 55219)
Bug where DataFrame.to_json() would raise an OverflowError instead of a TypeError with unsupported NumPy types (GH 55403)
Bug in casting from PeriodDtype with astype to datetime64 or DatetimeTZDtype with non-nanosecond unit incorrectly returning with nanosecond unit (GH 55958)
Bug in DataFrame.rolling() and Series.rolling() where duplicate datetimelike indexes are treated as consecutive rather than equal with closed='left' and closed='neither' (GH 20712)