These are the changes in pandas 1.5.0. See Release notes for a full changelog
including other versions of pandas.
Enhancements
pandas-stubs
The pandas-stubs library is now supported by the pandas development team, providing type stubs for the pandas API. Please visit
pandas-dev/pandas-stubs for more information.
We thank VirtusLab and Microsoft for their initial, significant contributions to pandas-stubs
Native PyArrow-backed ExtensionArray
With Pyarrow installed, users can now create pandas objects
that are backed by a pyarrow.ChunkedArray and pyarrow.DataType.
The dtype argument can accept a string of a pyarrow data type
with pyarrow in brackets e.g. "int64[pyarrow]" or, for pyarrow data types that take parameters, a ArrowDtype
initialized with a pyarrow.DataType.
Most operations are supported and have been implemented using pyarrow compute functions.
We recommend installing the latest version of PyArrow to access the most recently implemented compute functions.
New method DataFrame.__dataframe__() which produces the interchange object.
It effectively “exports” the pandas dataframe as an interchange object so
any other library which has the protocol implemented can “import” that dataframe
without knowing anything about the producer except that it makes an interchange object.
New function pandas.api.interchange.from_dataframe() which can take
an arbitrary interchange object from any conformant library and construct a
pandas DataFrame out of it.
Styler
The most notable development is the new method Styler.concat() which
allows adding customised footer rows to visualise additional calculations on the data,
e.g. totals and counts etc. (GH 43875, GH 46186)
Additionally there is an alternative output method Styler.to_string(),
which allows using the Styler’s formatting methods to create, for example, CSVs (GH 44502).
A new feature Styler.relabel_index() is also made available to provide full customisation of the display of
index or column headers (GH 47864)
Minor feature improvements are:
Adding the ability to render border and border-{side} CSS properties in Excel (GH 42276)
Making keyword arguments consist: Styler.highlight_null() now accepts color and deprecates null_color although this remains backwards compatible (GH 45907)
In [11]: importpandasaspdIn [12]: df=pd.DataFrame({"col1_a":[1,0,1],"col1_b":[0,1,0], ....: "col2_a":[0,1,0],"col2_b":[1,0,0], ....: "col2_c":[0,0,1]}) ....: In [13]: pd.from_dummies(df,sep="_")Out[13]: col1 col20 a b1 b a2 a c
This supports .tar, .tar.gz, .tar.bz and .tar.xz2 archives.
The used compression method is inferred from the filename.
If the compression method cannot be inferred, use the compression argument:
For very large XML files that can range in hundreds of megabytes to gigabytes, pandas.read_xml()
now supports parsing such sizeable files using lxml’s iterparse and etree’s iterparse
which are memory-efficient methods to iterate through XML trees and extract specific elements
and attributes without holding entire tree in memory (GH 45442).
In [1]: df=pd.read_xml(... "/path/to/downloaded/enwikisource-latest-pages-articles.xml",... iterparse = {"page": ["title", "ns", "id"]})... )dfOut[2]: title ns id0 Gettysburg Address 0 214501 Main Page 0 429502 Declaration by United Nations 0 84353 Constitution of the United States of America 0 84354 Declaration of Independence (Israel) 0 17858... ... ... ...3578760 Page:Black cat 1897 07 v2 n10.pdf/17 104 2196493578761 Page:Black cat 1897 07 v2 n10.pdf/43 104 2196493578762 Page:Black cat 1897 07 v2 n10.pdf/44 104 2196493578763 The History of Tom Jones, a Foundling/Book IX 0 120842913578764 Page:Shakespeare of Stratford (1926) Yale.djvu/91 104 21450[3578765 rows x 3 columns]
Copy on Write
A new feature copy_on_write was added (GH 46958). Copy on write ensures that
any DataFrame or Series derived from another in any way always behaves as a copy.
Copy on write disallows updating any other object than the object the method
was applied to.
Series.map() now raises when arg is dict but na_action is not either None or 'ignore' (GH 46588)
MultiIndex.to_frame() now supports the argument allow_duplicates and raises on duplicate labels if it is missing or False (GH 45245)
StringArray now accepts array-likes containing nan-likes (None, np.nan) for the values parameter in its constructor in addition to strings and pandas.NA. (GH 40839)
DataFrame.plot() will now allow the subplots parameter to be a list of iterables specifying column groups, so that columns may be grouped together in the same subplot (GH 29688).
to_numeric() now preserves float64 arrays when downcasting would generate values not representable in float32 (GH 43693)
Implemented a bool-dtype Index, passing a bool-dtype array-like to pd.Index will now retain bool dtype instead of casting to object (GH 45061)
Implemented a complex-dtype Index, passing a complex-dtype array-like to pd.Index will now retain complex dtype instead of casting to object (GH 45845)
DatetimeIndex.astype() now supports casting timezone-naive indexes to datetime64[s], datetime64[ms], and datetime64[us], and timezone-aware indexes to the corresponding datetime64[unit,tzname] dtypes (GH 47579)
Series reducers (e.g. min, max, sum, mean) will now successfully operate when the dtype is numeric and numeric_only=True is provided; previously this would raise a NotImplementedError (GH 47500)
RangeIndex.union() now can return a RangeIndex instead of a Int64Index if the resulting values are equally spaced (GH 47557, GH 43885)
DataFrame.compare() now accepts an argument result_names to allow the user to specify the result’s names of both left and right DataFrame which are being compared. This is by default 'self' and 'other' (GH 44354)
DataFrame.quantile() gained a method argument that can accept table to evaluate multi-column quantiles (GH 43881)
Interval now supports checking whether one interval is contained by another interval (GH 46613)
The Dockerfile now installs a dedicated pandas-dev virtual environment for pandas development instead of using the base environment (GH 48427)
Notable bug fixes
These are bug fixes that might have notable behavior changes.
Using dropna=True with groupby transforms
A transform is an operation whose result has the same size as its input. When the
result is a DataFrame or Series, it is also required that the
index of the result matches that of the input. In pandas 1.4, using
DataFrameGroupBy.transform() or SeriesGroupBy.transform() with null
values in the groups and dropna=True gave incorrect results. Demonstrated by the
examples below, the incorrect results either contained incorrect values, or the result
did not have the same index as the input.
In [24]: df=pd.DataFrame({'a':[1,1,np.nan],'b':[2,3,4]})
Old behavior:
In [3]: # Value in the last row should be np.nan df.groupby('a', dropna=True).transform('sum')Out[3]: b0 51 52 5In [3]: # Should have one additional row with the value np.nan df.groupby('a', dropna=True).transform(lambda x: x.sum())Out[3]: b0 51 5In [3]: # The value in the last row is np.nan interpreted as an integer df.groupby('a', dropna=True).transform('ffill')Out[3]: b0 21 32 -9223372036854775808In [3]: # Should have one additional row with the value np.nan df.groupby('a', dropna=True).transform(lambda x: x)Out[3]: b
New behavior:
In [25]: df.groupby('a',dropna=True).transform('sum')Out[25]: b0 5.01 5.02 NaNIn [26]: df.groupby('a',dropna=True).transform(lambdax
Serializing tz-naive Timestamps with to_json() with iso_dates=True
Some minimum supported versions of dependencies were updated.
If installed, we now require:
Package
Minimum Version
Required
Changed
numpy
1.20.3
X
X
mypy (dev)
0.971
X
beautifulsoup4
4.9.3
X
blosc
1.21.0
X
bottleneck
1.3.2
X
fsspec
2021.07.0
X
hypothesis
6.13.0
X
gcsfs
2021.07.0
X
jinja2
3.0.0
X
lxml
4.6.3
X
numba
0.53.1
X
numexpr
2.7.3
X
openpyxl
3.0.7
X
pandas-gbq
0.15.0
X
psycopg2
2.8.6
X
pymysql
1.0.2
X
pyreadstat
1.1.2
X
pyxlsb
1.0.8
X
s3fs
2021.08.0
X
scipy
1.7.1
X
sqlalchemy
1.4.16
X
tabulate
0.8.9
X
xarray
0.19.0
X
xlsxwriter
1.4.3
X
For optional libraries the general recommendation is to use the latest version.
The following table lists the lowest version per library that is currently being tested throughout the development of pandas.
Optional libraries below the lowest tested version may still work, but are not considered supported.
BigQuery I/O methods read_gbq() and DataFrame.to_gbq() default to
auth_local_webserver=True. Google has deprecated the
auth_local_webserver=False“out of band” (copy-paste) flow.
The auth_local_webserver=False option is planned to stop working in
October 2022. (GH 46312)
now raises (previously ) when input is a string ending in , , , etc. but no such file exists. ()
Deprecations
Label-based integer slicing on a Series with an Int64Index or RangeIndex
In a future version, integer slicing on a Series with a Int64Index or RangeIndex will be treated as label-based, not positional. This will make the behavior consistent with other Series.__getitem__() and Series.__setitem__() behaviors (GH 45162).
For example:
In [29]: ser=pd.Series([1,2,3,4,5],index=[2,3,5,7,11])
In the old behavior, ser[2:4] treats the slice as positional:
Old behavior:
In [3]: ser[2:4]Out[3]:5 37 4dtype: int64
In a future version, this will be treated as label-based:
Future behavior:
In [4]: ser.loc[2:4]Out[4]:2 13 2dtype: int64
To retain the old behavior, use series.iloc[i:j]. To get the future behavior,
use series.loc[i:j].
All attributes of ExcelWriter were previously documented as not
public. However some third party Excel engines documented accessing
ExcelWriter.book or ExcelWriter.sheets, and users were utilizing these
and possibly other attributes. Previously these attributes were not safe to use;
e.g. modifications to ExcelWriter.book would not update ExcelWriter.sheets
and conversely. In order to support this, pandas has made some attributes public
and improved their implementations so that they may now be safely used. (GH 45572)
The following attributes are now public and considered safe to access.
In previous versions of pandas, if it was inferred that the function passed to
DataFrameGroupBy.apply() or SeriesGroupBy.apply() was a transformer (i.e. the resulting index was equal to
the input index), the argument of and
was ignored and the group keys would never be added to
the index of the result. In the future, the group keys will be added to the index
when the user specifies .
Inplace operation when setting values with loc and iloc
Most of the time setting values with DataFrame.iloc() attempts to set values
inplace, only falling back to inserting a new array if necessary. There are
some cases where this rule is not followed, for example when setting an entire
column from an array with different dtype:
In [30]: df=pd.DataFrame({'price':[11.1,12.2]},index=
numeric_only default value
Across the DataFrame, DataFrameGroupBy, and Resampler operations such as
min, sum, and idxmax, the default
value of the numeric_only argument, if it exists at all, was inconsistent.
Furthermore, operations with the default value None can lead to surprising
results. (GH 46560)
Deprecated behavior of SparseArray.astype(), , and with when passing a non-sparse . In a future version, this will cast to that non-sparse dtype instead of wrapping it in a ()
Performance improvements
Performance improvement in DataFrame.corrwith() for column-wise (axis=0) Pearson and Spearman correlation when other is a Series (GH 46174)
Performance improvement in MultiIndex.is_monotonic_increasing() (GH 47458)
Performance improvement in BusinessHourstr and repr (GH 44764)
Performance improvement in datetime arrays string formatting when one of the default strftime formats "%Y-%m-%d%H:%M:%S" or "%Y-%m-%d%H:%M:%S.%f" is used. (GH 44764)
Bug in Categorical.view() not accepting integer dtypes (GH 25464)
Bug in CategoricalIndex.union() when the index’s categories are integer-dtype and the index contains NaN values incorrectly raising instead of casting to float64 (GH 45362)
Bug in concat() when concatenating two (or more) unordered CategoricalIndex variables, whose categories are permutations, yields incorrect index values (GH 24845)
Datetimelike
Bug in DataFrame.quantile() with datetime-like dtypes and no rows incorrectly returning float64 dtype instead of retaining datetime-like dtype (GH 41544)
Bug in to_datetime() with sequences of np.str_ objects incorrectly raising (GH 32264)
Bug in Timestamp construction when passing datetime components as positional arguments and as a keyword argument incorrectly raising ()
Timedelta
Bug in astype_nansafe() astype(“timedelta64[ns]”) fails when np.nan is included (GH 45798)
Bug in constructing a Timedelta with a np.timedelta64 object and a unit sometimes silently overflowing and returning incorrect results instead of raising OutOfBoundsTimedelta (GH 46827)
Bug in constructing a Timedelta from a large integer or float with silently overflowing and returning incorrect results instead of raising ()
Time Zones
Bug in Timestamp constructor raising when passed a ZoneInfo tzinfo object (GH 46425)
Numeric
Bug in operations with array-likes with dtype="boolean" and NA incorrectly altering the array in-place (GH 45421)
Bug in arithmetic operations with nullable types without NA values not matching the same operation with non-nullable types (GH 48223)
Bug in floordiv when dividing by IntegerDtype0 would return instead of ()
Bug in constructing a Series from a float-containing list or a floating-dtype ndarray-like (e.g. dask.Array) and an integer dtype raising instead of casting like we would with an np.ndarray (GH 40110)
Bug in Float64Index.astype() to unsigned integer dtype incorrectly casting to np.int64 dtype ()
Bug in Series.str.zfill() when strings contain leading signs, padding ‘0’ before the sign character rather than after as str.zfill from standard library (GH 20868)
Interval
Bug in IntervalArray.__setitem__() when setting np.nan into an integer-backed array raising ValueError instead of TypeError (GH 45484)
Bug in DataFrame.iloc() where indexing a single row on a DataFrame with a single ExtensionDtype column gave a copy instead of a view on the underlying data (GH 45241)
Bug in DataFrame.__getitem__() returning copy when DataFrame has duplicated columns even if a unique column is selected (GH 45316, GH 41062)
Bug in does not create with union of levels when both MultiIndexes intersections are identical ()
Bug in and with produced incorrect results when ()
Reshaping
Bug in concat() between a Series with integer dtype and another with CategoricalDtype with integer categories and containing NaN values casting to object dtype instead of float64 (GH 45359)
Bug in that selected object and categorical dtypes but not string ()
Operations with Timestamp or Timedelta that would previously raise OverflowError instead raise OutOfBoundsDatetime or OutOfBoundsTimedelta where appropriate (GH 47268)
DataFrame constructor raises if index or columns arguments are sets (GH 47215)
book
check_extension
close
date_format
datetime_format
engine
if_sheet_exists
sheets
supported_extensions
The following attributes have been deprecated. They now raise a FutureWarning
when accessed and will be removed in a future version. Users should be aware
that their usage is considered unsafe, and can lead to unexpected results.
cur_sheet
handles
path
save
write_cells
See the documentation of ExcelWriter for further details.
As group_keys=True is the default value of DataFrame.groupby() and
Series.groupby(), not specifying group_keys with a transformer will
raise a FutureWarning. This can be silenced and the previous behavior
retained by specifying group_keys=False.
To get the old behaviour when df.columns is not unique and you want to
change a single column by index, you can use DataFrame.isetitem(), which
has been added in pandas 1.5:
In [1]: df=pd.DataFrame({"a":[1,2],"b":["x","y"]})In [2]: # Reading the next line without knowing the contents of df, one would # expect the result to contain the products for both columns a and b. df[["a", "b"]].prod()Out[2]:a 2dtype: int64
To avoid this behavior, the specifying the value numeric_only=None has been
deprecated, and will be removed in a future version of pandas. In the future,
all operations with a numeric_only argument will default to False. Users
should either call the operation only with columns that can be operated on, or
specify numeric_only=True to operate only on Boolean, integer, and float columns.
In order to support the transition to the new behavior, the following methods have
gained the numeric_only argument.
Deprecated behavior of DatetimeIndex.intersection() and DatetimeIndex.symmetric_difference() (union behavior was already deprecated in version 1.3.0) with mixed time zones; in a future version both will be cast to UTC instead of object dtype (GH 39328, GH 45357)
Deprecated behavior of DatetimeIndex.astype(), TimedeltaIndex.astype(), PeriodIndex.astype() when converting to an integer dtype other than int64. In a future version, these will convert to exactly the specified dtype (instead of always int64) and will raise if the conversion overflows (GH 45034)
Deprecated the __array_wrap__ method of DataFrame and Series, rely on standard numpy ufuncs instead (GH 45451)
Deprecated treating float-dtype data as wall-times when passed with a timezone to Series or DatetimeIndex (GH 45573)
Deprecated the behavior of Series.fillna() and DataFrame.fillna() with timedelta64[ns] dtype and incompatible fill value; in a future version this will cast to a common dtype (usually object) instead of raising, matching the behavior of other dtypes (GH 45746)
Deprecated treating all-bool object-dtype columns as bool-like in DataFrame.any() and DataFrame.all() with bool_only=True, explicitly cast to bool instead (GH 46188)
Deprecated behavior of method DataFrame.quantile(), attribute numeric_only will default False. Including datetime/timedelta columns in the result (GH 7308).
Deprecated Timedelta.freq and Timedelta.is_populated (GH 46430)
Deprecated the methods DataFrame.mad(), Series.mad(), and the corresponding groupby methods (GH 11787)
Deprecated positional arguments to Index.join() except for other, use keyword-only arguments instead of positional arguments (GH 46518)
Deprecated positional arguments to StringMethods.rsplit() and StringMethods.split() except for pat, use keyword-only arguments instead of positional arguments (GH 47423)
Deprecated indexing on a timezone-naive DatetimeIndex using a string representing a timezone-aware datetime (GH 46903, GH 36148)
Deprecated allowing unit="M" or unit="Y" in Timestamp constructor with a non-round float value (GH 47267)
Deprecated the display.column_space global configuration option (GH 7576)
Deprecated the argument na_sentinel in factorize(), Index.factorize(), and ExtensionArray.factorize(); pass use_na_sentinel=True instead to use the sentinel -1 for NaN values and use_na_sentinel=False instead of na_sentinel=None to encode NaN values (GH 46910)
Clarified warning from to_datetime() when delimited dates can’t be parsed in accordance to specified dayfirst argument (GH 46210)
Emit warning from to_datetime() when delimited dates can’t be parsed in accordance to specified dayfirst argument even for dates where leading zero is omitted (e.g. 31/1/2001) (GH 47880)
Deprecated Series and Resampler reducers (e.g. min, max, sum, mean) raising a NotImplementedError when the dtype is non-numric and numeric_only=True is provided; this will raise a TypeError in a future version (GH 47500)
Deprecated Series.rank() returning an empty result when the dtype is non-numeric and numeric_only=True is provided; this will raise a TypeError in a future version (GH 47500)
Deprecated producing a single element when iterating over a DataFrameGroupBy or a SeriesGroupBy that has been grouped by a list of length 1; A tuple of length one will be returned instead (GH 42795)
Fixed up warning message of deprecation of MultiIndex.lesort_depth() as public method, as the message previously referred to MultiIndex.is_lexsorted() instead (GH 38701)
Deprecated the mangle_dupe_cols argument in read_csv(), read_fwf(), read_table() and read_excel(). The argument was never implemented, and a new argument where the renaming pattern can be specified will be added instead (GH 47718)
Deprecated allowing dtype='datetime64' or dtype=np.datetime64 in Series.astype(), use “datetime64[ns]” instead (GH 47844)
Bug in Index.astype() when casting from object dtype to timedelta64[ns] dtype incorrectly casting np.datetime64("NaT") values to np.timedelta64("NaT") instead of raising (GH 45722)
Bug in division, pow and mod operations on array-likes with dtype="boolean" not being like their np.bool_ counterparts (GH 46063)
Bug in multiplying a Series with IntegerDtype or FloatingDtype by an array-like with timedelta64[ns] dtype incorrectly raising (GH 45622)
Bug in mean() where the optional dependency bottleneck causes precision loss linear in the length of the array. bottleneck has been disabled for mean() improving the loss to log-linear but may result in a performance decrease. (GH 42878)
Bug when inferring the dtype from an iterable that is not a NumPy ndarray consisting of all NumPy unsigned integer scalars did not result in an unsigned integer dtype (GH 47294)
Bug in setting a NA value (None or np.nan) into a Series with int-based IntervalDtype incorrectly casting to object dtype instead of a float-based IntervalDtype (GH 45568)
Bug in indexing setting values into an ExtensionDtype column with df.iloc[:,i]=values with values having the same dtype as df.iloc[:,i] incorrectly inserting a new array instead of setting in-place (GH 33457)
Bug in Series.__setitem__() with a non-integer Index when using an integer key to set a value that cannot be set inplace where a ValueError was raised instead of casting to a common dtype (GH 45070)
Bug in Series.__setitem__() when setting incompatible values into a PeriodDtype or IntervalDtypeSeries raising when indexing with a boolean mask but coercing when indexing with otherwise-equivalent indexers; these now consistently coerce, along with Series.mask() and Series.where() (GH 45768)
Bug in DataFrame.where() with multiple columns with datetime-like dtypes failing to downcast results consistent with other dtypes (GH 45837)
Bug in isin() upcasting to float64 with unsigned integer dtype and list-like argument without a dtype (GH 46485)
Bug in Series.loc.__setitem__() and Series.loc.__getitem__() not raising when using multiple keys without using a MultiIndex (GH 13831)
Bug when setting a value too large for a Series dtype failing to coerce to a common type (GH 26049, GH 32878)
Bug in loc.__setitem__() treating range keys as positional instead of label-based (GH 45479)
Bug in DataFrame.__setitem__() casting extension array dtypes to object when setting with a scalar key and DataFrame as value (GH 46896)
Bug in Series.__setitem__() when setting a scalar to a nullable pandas dtype would not raise a TypeError if the scalar could not be cast (losslessly) to the nullable type (GH 45404)
Bug in Series.__setitem__() when setting boolean dtype values containing NA incorrectly raising instead of casting to boolean dtype (GH 45462)
Bug in Series.__setitem__() where setting NA into a numeric-dtype Series would incorrectly upcast to object-dtype rather than treating the value as np.nan (GH 44199)
Bug in DataFrame.loc() when setting values to a column and right hand side is a dictionary (GH 47216)
Bug in Series.__setitem__() with datetime64[ns] dtype, an all-False boolean mask, and an incompatible value incorrectly casting to object instead of retaining datetime64[ns] dtype (GH 45967)
Bug in Index.__getitem__() raising ValueError when indexer is from boolean dtype with NA (GH 45806)
Bug in Series.__setitem__() losing precision when enlarging Series with scalar (GH 32346)
Bug in Series.mask() with inplace=True or setting values with a boolean mask with small integer dtypes incorrectly raising (GH 45750)
Bug in DataFrame.mask() with inplace=True and ExtensionDtype columns incorrectly raising (GH 45577)
Bug in getting a column from a DataFrame with an object-dtype row index with datetime-like values: the resulting Series now preserves the exact object-dtype Index from the parent DataFrame (GH 42950)
Bug in DataFrame.__getattribute__() raising AttributeError if columns have "string" dtype (GH 46185)
Bug in DataFrame.compare() returning all NaN column when comparing extension array dtype and numpy dtype (GH 44014)
Bug in indexing on a DatetimeIndex with a np.str_ key incorrectly raising (GH 45580)
Bug in CategoricalIndex.get_indexer() when index contains NaN values, resulting in elements that are in target but not present in the index to be mapped to the index of the NaN element, instead of -1 (GH 45361)
Bug in setting large integer values into Series with float32 or float16 dtype incorrectly altering these values instead of coercing to float64 dtype (GH 45844)
Bug in inferring an incorrect freq when passing a string to Period microseconds that are a multiple of 1000 (GH 46811)
Bug in constructing a Period from a Timestamp or np.datetime64 object with non-zero nanoseconds and freq="ns" incorrectly truncating the nanoseconds (GH 46811)
Bug in adding np.timedelta64("NaT","ns") to a Period with a timedelta-like freq incorrectly raising IncompatibleFrequency instead of returning NaT (GH 47196)
Bug in adding an array of integers to an array with PeriodDtype giving incorrect results when dtype.freq.n>1 (GH 47209)
Bug in subtracting a Period from an array with PeriodDtype returning incorrect results instead of raising OverflowError when the operation overflows (GH 47538)
Bug in DataFrameGroupBy.resample() raises KeyError when getting the result from a key list which misses the resample key (GH 47362)
Bug in DataFrame.groupby() would lose index columns when the DataFrame is empty for transforms, like fillna (GH 47787)
Bug in DataFrame.groupby() and Series.groupby() with dropna=False and sort=False would put any null groups at the end instead the order that they are encountered (GH 46584)
Bug in concatenation with IntegerDtype, or FloatingDtype arrays where the resulting dtype did not mirror the behavior of the non-nullable dtypes (GH 46379)
Bug in concat() losing dtype of columns when join="outer" and sort=True (GH 47329)
Bug in concat() not sorting the column names when None is included (GH 47331)