This is a major release from 0.22.0 and includes a number of API changes,
deprecations, new features, enhancements, and performance improvements along
with a large number of bug fixes. We recommend that all users upgrade to this
version.
JSON read/write round-trippable with orient='table'
A DataFrame can now be written to and subsequently read back via JSON while preserving metadata through usage of the orient='table' argument (see GH 18912 and GH 9146). Previously, none of the available orient values guaranteed the preservation of dtypes and index names, amongst other metadata.
In [1]: df=pd.DataFrame({'foo':[1,2,3,4], ...: 'bar':['a','b','c','d'], ...: 'baz':pd.date_range('2018-01-01',freq='d',periods=4), ...: 'qux':pd.Categorical(['a','b','c','c'])}, ...: index=pd.Index(range(4),name='idx')) ...: In [2]: dfOut[2]: foo bar baz quxidx 0 1 a 2018-01-01 a1 2 b 2018-01-02 b2 3 c 2018-01-03 c3 4 d 2018-01-04 c[4 rows x 4 columns]In [3]: df.dtypesOut[3]: foo int64bar objectbaz datetime64[ns]qux categoryLength: 4, dtype: objectIn [4]: df.to_json('test.json',orient='table')In [5]: new_df=pd.read_json('test.json',orient='table')In [6]: new_dfOut[6]: foo bar baz quxidx 0 1 a 2018-01-01 a1 2 b 2018-01-02 b2 3 c 2018-01-03 c3 4 d 2018-01-04 c[4 rows x 4 columns]In [7]: new_df.dtypesOut[7]: foo int64bar objectbaz datetime64[ns]qux categoryLength: 4, dtype: object
Please note that the string index is not supported with the round trip format, as it is used by default in write_json to indicate a missing index name.
In [8]: df.index.name='index'In [9]: df.to_json('test.json',orient='table')In [10]: new_df=pd.read_json('test.json',orient='table')In [11]: new_dfOut[11]: foo bar baz qux
Method .assign() accepts dependent arguments
The DataFrame.assign() now accepts dependent keyword arguments for python version later than 3.6 (see also PEP 468). Later keyword arguments may now refer to earlier ones if the argument is a callable. See the
documentation here (GH 14207)
In [13]: df=pd.DataFrame({'A':[1
Merging on a combination of columns and index levels
Strings passed to DataFrame.merge() as the on, left_on, and right_on
parameters may now refer to either column names or index level names.
This enables merging DataFrame instances on a combination of index levels
and columns without resetting indexes. See the Merge on columns and
levels documentation section.
(GH 14355)
In [17]: left_index
Sorting by a combination of columns and index levels
Strings passed to DataFrame.sort_values() as the by parameter may
now refer to either column names or index level names. This enables sorting
DataFrame instances by a combination of index levels and columns without
resetting indexes. See the Sorting by Indexes and Values documentation section.
(GH 14353)
# Build MultiIndexIn [22]: idx=pd.MultiIndex.
Extending pandas with custom types (experimental)
pandas now supports storing array-like objects that aren’t necessarily 1-D NumPy
arrays as columns in a DataFrame or values in a Series. This allows third-party
libraries to implement extensions to NumPy’s types, similar to how pandas
implemented categoricals, datetimes with timezones, periods, and intervals.
As a demonstration, we’ll use cyberpandas, which provides an IPArray type
for storing ip addresses.
In [1]: fromcyberpandasimportIPArrayIn [2]: values=IPArray([ ...: 0, ...: 3232235777, ...:
New observed keyword for excluding unobserved categories in GroupBy
Grouping by a categorical includes the unobserved categories in the output.
When grouping by multiple categorical columns, this means you get the cartesian product of all the
categories, including combinations where there are no observations, which can result in a large
number of groups. We have added a keyword observed to control this behavior, it defaults to
observed=False for backward-compatibility. (GH 14942, GH 8138, GH 15217, GH 17594, GH 8669, GH 20583, GH 20902)
Rolling/Expanding.apply() accepts raw=False to pass a Series to the function
Series.rolling().apply(), DataFrame.rolling().apply(),
Series.expanding().apply(), and DataFrame.expanding().apply() have gained a raw=None parameter.
This is similar to DataFame.apply(). This parameter, if True allows one to send a np.ndarray to the applied function. If a will be passed. The
default is , which preserves backward compatibility, so this will default to , sending an .
In a future version the default will be changed to , sending a . (, )
DataFrame.interpolate has gained the limit_area kwarg
DataFrame.interpolate() has gained a limit_area parameter to allow further control of which NaN s are replaced.
Use limit_area='inside' to fill only NaNs surrounded by valid values or use limit_area='outside' to fill only NaN s
outside the existing valid values while preserving those inside. (GH 16284) See the .
Function get_dummies now supports dtype argument
The get_dummies() now accepts a dtype argument, which specifies a dtype for the new columns. The default remains uint8. (GH 18330)
In [47]: df=pd.DataFrame({'a':[1
Timedelta mod method
mod (%) and divmod operations are now defined on Timedelta objects
when operating with either timedelta-like or with numeric arguments.
See the documentation here. (GH 19365)
In [50]: td=pd.Timedelta(hours=37)In [51]: td%
Method .rank() handles inf values when NaN are present
In previous versions, .rank() would assign inf elements NaN as their ranks. Now ranks are calculated properly. (GH 6945)
In [52]: s=pd.Series([-np
Series.str.cat has gained the join kwarg
Previously, Series.str.cat() did not – in contrast to most of pandas – align Series on their index before concatenation (see GH 18657).
The method has now gained a keyword join to control the manner of alignment, see examples below and here.
In v.0.23 will default to None (meaning no alignment), but this default will change to in a future version of pandas.
DataFrame.astype performs column-wise conversion to Categorical
DataFrame.astype() can now perform column-wise conversion to Categorical by supplying the string 'category' or
a CategoricalDtype. Previously, attempting this would raise a NotImplementedError. See the
Object creation section of the documentation for more details and examples. (GH 12860, GH 18099)
Other enhancements
Unary + now permitted for Series and DataFrame as numeric operator (GH 16073)
Better support for to_excel() output with the xlsxwriter engine. (GH 16149)
now accepts leading ‘+’ signs e.g. ‘+1h’. ()
Backwards incompatible API changes
Dependencies have increased minimum versions
We have updated our minimum supported versions of dependencies (GH 15184).
If installed, we now require:
Instantiation from dicts preserves dict insertion order for Python 3.6+
Until Python 3.6, dicts in Python had no formally defined ordering. For Python
version 3.6 and later, dicts are ordered by insertion order, see
PEP 468.
pandas will use the dict’s insertion order, when creating a Series or
DataFrame from a dict and you’re using Python version 3.6 or
higher. (GH 19884)
Previous behavior (and current behavior if on Python < 3.6):
In [16]: pd.Series({'Income':2000, ....: 'Expenses':-1500
Deprecate Panel
Panel was deprecated in the 0.20.x release, showing as a DeprecationWarning. Using Panel will now show a FutureWarning. The recommended way to represent 3-D data are
with a MultiIndex on a DataFrame via the to_frame() or with the xarray package. pandas
provides a to_xarray() method to automate this conversion (GH 13563, GH 18324).
pandas.core.common removals
The following error & warning messages are removed from pandas.core.common (GH 13634, GH 19769):
PerformanceWarning
UnsupportedFunctionCall
UnsortedIndexError
AbstractMethodError
These are available from import from pandas.errors (since 0.19.0).
Changes to make output of DataFrame.apply consistent
DataFrame.apply() was inconsistent when applying an arbitrary user-defined-function that returned a list-like with axis=1. Several bugs and inconsistencies
are resolved. If the applied function returns a Series, then pandas will return a DataFrame; otherwise a Series will be returned, this includes the case
where a list-like (e.g. tuple or list is returned) (GH 16353, GH 17437, GH 17970, GH 17348, GH 17892, ,
, , , ).
Concatenation will no longer sort
In a future version of pandas pandas.concat() will no longer sort the non-concatenation axis when it is not already aligned.
The current behavior is the same as the previous (sorting), but now a warning is issued when sort is not specified and the non-concatenation axis is not aligned (GH 4588).
In [81]: df1=pd.DataFrame({"a":[1,2],"b":
Build changes
Building pandas for development now requires cython>=0.24 (GH 18613)
Building from source now explicitly requires setuptools in setup.py (GH 18113)
Updated conda recipe to be in compliance with conda-build 3.0+ (GH 18002)
Index division by zero fills correctly
Division operations on Index and subclasses will now fill division of positive numbers by zero with np.inf, division of negative numbers by zero with -np.inf and 0/0 with np.nan. This matches existing Series behavior. (GH 19322, GH 19347)
Previous behavior:
In [6]: index
Extraction of matching patterns from strings
By default, extracting matching patterns from strings with str.extract() used to return a
Series if a single group was being extracted (a DataFrame if more than one group was
extracted). As of pandas 0.23.0 str.extract() always returns a DataFrame, unless
expand is set to False. Finally, None was an accepted value for
the expand parameter (which was equivalent to False), but now raises a . ()
Default value for the ordered parameter of CategoricalDtype
The default value of the ordered parameter for CategoricalDtype has changed from False to None to allow updating of categories without impacting ordered. Behavior should remain consistent for downstream objects, such as Categorical (GH 18790)
Better pretty-printing of DataFrames in a terminal
Previously, the default value for the maximum number of columns was
pd.options.display.max_columns=20. This meant that relatively wide data
frames would not fit within the terminal width, and pandas would introduce line
breaks to display these 20 columns. This resulted in an output that was
relatively difficult to read:
If Python runs in a terminal, the maximum number of columns is now determined
automatically so that the printed data frame fits within the current terminal
width (pd.options.display.max_columns=0) (GH 17023). If Python runs
as a Jupyter kernel (such as the Jupyter QtConsole or a Jupyter notebook, as
well as in many IDEs), this value cannot be inferred automatically and is thus
set to 20 as in previous versions. In a terminal, this results in a much
nicer output:
Note that if you don’t like the new default, you can always set this option
yourself. To revert to the old setting, you can run this line:
Datetimelike API changes
The default Timedelta constructor now accepts an ISO8601Duration string as an argument (GH 19040)
Subtracting NaT from a Series with dtype='datetime64[ns]' returns a Series with dtype='timedelta64[ns]' instead of dtype='datetime64[ns]' ()
Series construction with an object dtyped tz-aware datetime and dtype=object specified, will now return an dtyped , previously this would infer the datetime dtype ()
Deprecations
Series.from_array and SparseSeries.from_array are deprecated. Use the normal constructor Series(..) and SparseSeries(..) instead (GH 18213).
DataFrame.as_matrix is deprecated. Use DataFrame.values instead (GH 18458).
Series.asobject, DatetimeIndex.asobject, PeriodIndex.asobject and TimeDeltaIndex.asobject have been deprecated. Use .astype(object) instead (GH 18572)
Grouping by a tuple of keys now emits a FutureWarning and is deprecated.
In the future, a tuple passed to 'by' will always refer to a single key
that is the actual tuple, instead of treating the tuple as multiple keys. To
retain the previous behavior, use a list instead of a tuple (GH 18314)
The is_copy attribute is deprecated and will be removed in a future version (GH 18801).
IntervalIndex.from_intervals is deprecated in favor of the IntervalIndex constructor (GH 19263)
DataFrame.from_items is deprecated. Use DataFrame.from_dict() instead, or DataFrame.from_dict(OrderedDict()) if you wish to preserve the key order (GH 17320, GH 17312)
Indexing a MultiIndex or a FloatIndex with a list containing some missing keys will now show a FutureWarning, which is consistent with other types of indexes (GH 17758).
The broadcast parameter of .apply() is deprecated in favor of result_type='broadcast' (GH 18577)
The reduce parameter of .apply() is deprecated in favor of result_type='reduce' (GH 18577)
The order parameter of factorize() is deprecated and will be removed in a future release (GH 19727)
Index.summary() is deprecated and will be removed in a future version (GH 18217)
NDFrame.get_ftype_counts() is deprecated and will be removed in a future version (GH 18243)
The convert_datetime64 parameter in DataFrame.to_records() has been deprecated and will be removed in a future version. The NumPy bug motivating this parameter has been resolved. The default value for this parameter has also changed from True to None (GH 18160).
Series.rolling().apply(), DataFrame.rolling().apply(), Series.expanding().apply(), and DataFrame.expanding().apply() have deprecated passing an np.array by default. One will need to pass the new raw parameter to be explicit about what is passed (GH 20584)
The data, base, strides, flags and itemsize properties
of the Series and Index classes have been deprecated and will be
removed in a future version (GH 20419).
DatetimeIndex.offset is deprecated. Use DatetimeIndex.freq instead (GH 20716)
Setting PeriodIndex.freq (which was not guaranteed to work correctly) is deprecated. Use PeriodIndex.asfreq() instead (GH 20678)
Index.get_duplicates() is deprecated and will be removed in a future version (GH 20239)
The previous default behavior of negative indices in Categorical.take is deprecated. In a future version it will change from meaning missing values to meaning positional indices from the right. The future behavior is consistent with Series.take() (GH 20664).
Passing multiple axes to the axis parameter in DataFrame.dropna() has been deprecated and will be removed in a future version (GH 20987)
Removal of prior version deprecations/changes
Warnings against the obsolete usage Categorical(codes,categories), which were emitted for instance when the first two arguments to Categorical() had different dtypes, and recommended the use of Categorical.from_codes, have now been removed (GH 8074)
The levels and labels attributes of a MultiIndex can no longer be set directly (GH 4039).
pd.tseries.util.pivot_annual has been removed (deprecated since v0.19). Use pivot_table instead (GH 18370)
pd.tseries.util.isleapyear has been removed (deprecated since v0.19). Use .is_leap_year property in Datetime-likes instead (GH 18370)
pd.ordered_merge has been removed (deprecated since v0.19). Use pd.merge_ordered instead (GH 18459)
The pandas.io.wb and pandas.io.data stub modules have been removed (GH 13735)
Categorical.from_array has been removed (GH 13854)
The freq and how parameters have been removed from the rolling/expanding/ewm methods of DataFrame
and Series (deprecated since v0.18). Instead, resample before calling the methods. (GH 18601 & GH 18668)
DatetimeIndex.to_datetime, Timestamp.to_datetime, PeriodIndex.to_datetime, and Index.to_datetime have been removed (GH 8254, GH 14096, GH 14113)
read_csv() has dropped the compact_ints and use_unsigned parameters (GH 13323)
The Timestamp class has dropped the offset attribute in favor of freq (GH 13593)
The Series, Categorical, and Index classes have dropped the reshape method (GH 13012)
pandas.tseries.frequencies.get_standard_freq has been removed in favor of pandas.tseries.frequencies.to_offset(freq).rule_code (GH 13874)
The freqstr keyword has been removed from pandas.tseries.frequencies.to_offset in favor of freq (GH 13874)
The Panel4D and PanelND classes have been removed (GH 13776)
The Panel class has dropped the to_long and toLong methods (GH 19077)
The options display.line_with and display.height are removed in favor of display.width and display.max_rows respectively (GH 4391, GH 19107)
The labels attribute of the Categorical class has been removed in favor of Categorical.codes (GH 7768)
The flavor parameter have been removed from to_sql() method (GH 13611)
The modules pandas.tools.hashing and pandas.util.hashing have been removed (GH 16223)
The top-level functions pd.rolling_*, pd.expanding_* and pd.ewm* have been removed (Deprecated since v0.18).
Instead, use the DataFrame/Series methods rolling, expanding and ewm (GH 18723)
Imports from pandas.core.common for functions such as is_datetime64_dtype are now removed. These are located in pandas.api.types. (GH 13634, GH 19769)
When .resample() was changed from an eager to a lazy operation, like .groupby() in v0.18.0, we put in place compatibility (with a FutureWarning),
so operations would continue to work. This is now fully removed, so a Resampler will no longer forward compat operations (GH 20554)
Remove long deprecated axis=None parameter from .replace() (GH 20271)
Performance improvements
Indexers on Series or DataFrame no longer create a reference cycle (GH 17956)
Added a keyword argument, cache, to to_datetime() that improved the performance of converting duplicate datetime arguments (GH 11665)
DateOffset arithmetic performance is improved (GH 18218)
Converting a Series of Timedelta objects to days, seconds, etc… sped up through vectorization of underlying methods (GH 18092)
Improved performance of .map() with a Series/dict input (GH 15081)
The overridden Timedelta properties of days, seconds and microseconds have been removed, leveraging their built-in Python versions instead (GH 18242)
Series construction will reduce the number of copies made of the input data in certain cases (GH 17449)
Improved performance of getattr(Series,attr) when the Series has certain index types. This manifested in slow printing of large Series with a DatetimeIndex (GH 19764)
Fixed a performance regression for GroupBy.nth() and GroupBy.last() with some object columns (GH 19283)
Improved performance of Categorical.from_codes() (GH 18501)
Documentation changes
Thanks to all of the contributors who participated in the pandas Documentation
Sprint, which took place on March 10th. We had about 500 participants from over
30 locations across the world. You should notice that many of the
API docstrings have greatly improved.
There were too many simultaneous contributions to include a release note for each
improvement, but this GitHub search should give you an idea of how many docstrings
were improved.
Special thanks to Marc Garcia for organizing the sprint. For more information,
read the NumFOCUS blogpost recapping the sprint.
Changed spelling of “numpy” to “NumPy”, and “python” to “Python”. (GH 19017)
Consistency when introducing code samples, using either colon or period.
Rewrote some sentences for greater clarity, added more dynamic references
to functions, methods and classes.
(GH 18941, GH 18948, GH 18973, GH 19017)
Added a reference to DataFrame.assign() in the concatenate section of the merging documentation (GH 18665)
Bug fixes
Categorical
Bug in Categorical.equals returning the wrong result when comparing two
unordered Categorical arrays with the same categories, but in a different
order (GH 16603)
Bug in pandas.merge() returning the wrong result when joining on an
unordered Categorical that had the same categories but in a different
order (GH 19551)
Bug in CategoricalIndex.get_indexer() returning the wrong result when
target was an unordered Categorical that had the same categories as
self but in a different order (GH 19551)
Bug in and where adding or subtracting an array-like of objects either raised (, ) or broadcast incorrectly () ()
Timedelta
Bug in Timedelta.__mul__() where multiplying by NaT returned NaT instead of raising a TypeError (GH 19819)
Bug in Series with dtype='timedelta64[ns]' where addition or subtraction of TimedeltaIndex had results cast to dtype='int64' (GH 17250)
Timezones
Bug in creating a Series from an array that contains both tz-naive and tz-aware values will result in a Series whose dtype is tz-aware instead of object (GH 16406)
Bug in comparison of timezone-aware DatetimeIndex against NaT incorrectly raising TypeError (GH 19276)
Bug in DatetimeIndex.astype() when converting between timezone aware dtypes, and converting from timezone aware to naive (GH 18951)
Offsets
Bug in WeekOfMonth and Week where addition and subtraction did not roll correctly (GH 18510, GH 18672, GH 18864)
Bug in WeekOfMonth and LastWeekOfMonth where default keyword arguments for constructor raised ValueError (GH 19142)
Bug in FY5253Quarter, where rollback and rollforward behavior was inconsistent with addition and subtraction behavior ()
Numeric
Bug in Series constructor with an int or float list where specifying dtype=str, dtype='str' or dtype='U' failed to convert the data elements to strings (GH 16605)
Bug in Index multiplication and division methods where operating with a Series would return an Index object instead of a object ()
Strings
Bug in Series.str.get() with a dictionary in the values and the index not in the keys, raising KeyError (GH 20671)
Indexing
Bug in Index construction from list of mixed type tuples (GH 18505)
Bug in Index.drop() when passing a list of both tuples and non-tuples (GH 18304)
Bug in DataFrame.drop(), Panel.drop(), , where no is raised when dropping a non-existent element from an axis that contains duplicates ()
MultiIndex
Bug in MultiIndex.__contains__() where non-tuple keys would return True even if they had been dropped (GH 19027)
Bug in MultiIndex.set_labels() which would cause casting (and potentially clipping) of the new labels if the level argument is not 0 or a list like [0, 1, … ] (GH 19057)
read_html() now rewinds seekable IO objects after parse failure, before attempting to parse with a new parser. If a parser errors and the object is non-seekable, an informative error is raised suggesting the use of a different parser (GH 17975)
Bug in which casts int to float if is a with unused levels ()
Other
Improved error message when attempting to use a Python keyword as an identifier in a numexpr backed query (GH 18221)
Bug in accessing a pandas.get_option(), which raised KeyError rather than OptionError when looking up a non-existent option key in some cases (GH 19789)
In [27]: cat1=pd.Categorical(["a","a","b","b"], ....: categories=["a","b","z"],ordered=True) ....: In [28]: cat2=pd.Categorical(["c","d","c","d"], ....: categories=["c","d","y"],ordered=True) ....: In [29]: df=pd.DataFrame({"A":cat1,"B":cat2,"values":[1,2,3,4]})In [30]: df['C']=['foo','bar']*2In [31]: dfOut[31]: A B values C0 a c 1 foo1 a d 2 bar2 b c 3 foo3 b d 4 bar[4 rows x 4 columns]
To show all values, the previous behavior:
In [32]: df.groupby(['A','B','C'],observed=False).count()Out[32]: valuesA B C a c bar 0 foo 1 d bar 1 foo 0 y bar 0... ...z c foo 0 d bar 0 foo 0 y bar 0 foo 0[18 rows x 1 columns]
To show only observed values:
In [33]: df.groupby(['A','B','C'],observed=True).count()Out[33]: valuesA B C a c foo 1 d bar 1b c foo 1 d bar 1[4 rows x 1 columns]
For pivoting operations, this behavior is already controlled by the dropna keyword:
In [34]: cat1=pd.Categorical(["a","a","b","b"], ....: categories=["a","b","z"],ordered=True) ....: In [35]: cat2=pd.Categorical(["c","d","c","d"], ....: categories=["c","d","y"],ordered=True) ....: In [36]: df=pd.DataFrame({"A":cat1,"B":cat2,"values":[1,2,3,4]})In [37]: dfOut[37]: A B values0 a c 11 a d 22 b c 33 b d 4[4 rows x 3 columns]
In [1]: pd.pivot_table(df,values='values',index=['A','B'],dropna=True)Out[1]: valuesA Ba c 1.0 d 2.0b c 3.0 d 4.0In [2]: pd.pivot_table(df,values='values',index=['A','B'],dropna=False)Out[2]: valuesA Ba c 1.0 d 2.0 y NaNb c 3.0 d 4.0 y NaNz c NaN d NaN y NaN
Furthermore, previously if you rank inf or -inf values together with NaN values, the calculation won’t distinguish NaN from infinity when using ‘top’ or ‘bottom’ argument.
Bug in DataFrame.rank() and Series.rank() when method='dense' and pct=True in which percentile ranks were not being used with the number of distinct observations (GH 15630)
Improved wording of ValueError raised in to_datetime() when unit= is passed with a non-convertible value (GH 14350)
Series.fillna() now accepts a Series or a dict as a value for a categorical dtype (GH 17033)
pandas.read_clipboard() updated to use qtpy, falling back to PyQt5 and then PyQt4, adding compatibility with Python3 and multiple python-qt bindings (GH 17722)
Improved wording of ValueError raised in read_csv() when the usecols argument cannot match all columns. (GH 17301)
DataFrame.corrwith() now silently drops non-numeric columns when passed a Series. Before, an exception was raised (GH 18570).
IntervalIndex.to_tuples() has gained the na_tuple parameter to control whether NA is returned as a tuple of NA, or NA itself (GH 18756)
Categorical.rename_categories, CategoricalIndex.rename_categories and Series.cat.rename_categories
can now take a callable as their argument (GH 18862)
IntervalIndex.astype now supports conversions between subtypes when passed an IntervalDtype (GH 19197)
IntervalIndex and its associated constructor methods (from_arrays, from_breaks, from_tuples) have gained a dtype parameter (GH 19262)
Added SeriesGroupBy.is_monotonic_increasing() and SeriesGroupBy.is_monotonic_decreasing() (GH 17015)
For subclassed DataFrames, DataFrame.apply() will now preserve the Series subclass (if defined) when passing the data to the applied function (GH 19822)
DataFrame.from_dict() now accepts a columns argument that can be used to specify the column names when orient='index' is used (GH 18529)
Added option display.html.use_mathjax so MathJax can be disabled when rendering tables in Jupyter notebooks (GH 19856, GH 19824)
DataFrame.replace() now supports the method parameter, which can be used to specify the replacement method when to_replace is a scalar, list or tuple and value is None (GH 19632)
DataFrame.to_sql() now performs a multi-value insert if the underlying connection supports itk rather than inserting row by row.
SQLAlchemy dialects supporting multi-value inserts include: mysql, postgresql, sqlite and any dialect with supports_multivalues_insert. (GH 14315, GH 8953)
read_html() now accepts a displayed_only keyword argument to controls whether or not hidden elements are parsed (True by default) (GH 20027)
read_html() now reads all <tbody> elements in a <table>, not just the first. (GH 20690)
DataFrame and Series now support matrix multiplication (@) operator (GH 10259) for Python>=3.5
Updated DataFrame.to_gbq() and pandas.read_gbq() signature and documentation to reflect changes from
the pandas-gbq library version 0.4.0. Adds intersphinx mapping to pandas-gbq
library. (GH 20564)
Added new writer for exporting Stata dta files in version 117, StataWriter117. This format supports exporting strings with lengths up to 2,000,000 characters (GH 16450)
to_hdf() and read_hdf() now accept an errors keyword argument to control encoding error handling (GH 20835)
cut() has gained the duplicates='raise'|'drop' option to control whether to raise on duplicated edges (GH 20947)
Note the Series above is ordered alphabetically by the index values.
New behavior (for Python >= 3.6):
In [72]: pd.Series({'Income':2000, ....: 'Expenses':-1500, ....: 'Taxes':-200, ....: 'Net result':300}) ....: Out[72]: Income 2000Expenses -1500Taxes -200Net result 300Length: 4, dtype: int64
Notice that the Series is now ordered by insertion order. This new behavior is
used for all relevant pandas types (Series, DataFrame, SparseSeries
and SparseDataFrame).
If you wish to retain the old behavior while using Python >= 3.6, you can use
.sort_index():
In [75]: importpandas._testingastmIn [76]: p=tm.makePanel()In [77]: pOut[77]:<class 'pandas.core.panel.Panel'>Dimensions: 3 (items) x 3 (major_axis) x 4 (minor_axis)Items axis: ItemA to ItemCMajor_axis axis: 2000-01-03 00:00:00 to 2000-01-05 00:00:00Minor_axis axis: A to D
Convert to a MultiIndex DataFrame
In [78]: p.to_frame()Out[78]: ItemA ItemB ItemCmajor minor2000-01-03 A 0.469112 0.721555 0.404705 B -1.135632 0.271860 -1.039268 C 0.119209 0.276232 -1.344312 D -2.104569 0.113648 -0.1090502000-01-04 A -0.282863 -0.706771 0.577046 B 1.212112 -0.424972 -0.370647 C -1.044236 -1.087401 0.844885 D -0.494929 -1.478427 1.6435632000-01-05 A -1.509059 -1.039575 -1.715002 B -0.173215 0.567020 -1.157892 C -0.861849 -0.673690 1.075770 D 1.071804 0.524988 -1.469388[12 rows x 3 columns]
In [74]: df=pd.DataFrame(np.tile(np.arange(3),6).reshape(6,-1)+1, ....: columns=['A','B','C']) ....: In [75]: dfOut[75]: A B C0 1 2 31 1 2 32 1 2 33 1 2 34 1 2 35 1 2 3[6 rows x 3 columns]
Previous behavior: if the returned shape happened to match the length of original columns, this would return a DataFrame.
If the return shape did not match, a Series with lists was returned.
To broadcast the result across the original columns (the old behaviour for
list-likes of the correct length), you can use result_type='broadcast'.
The shape must match the original columns.
In [79]: df.apply(lambdax:[1,2,3],axis=1,result_type='broadcast')Out[79]: A B C0 1 2 31 1 2 32 1 2 33 1 2 34 1 2 35 1 2 3[6 rows x 3 columns]
Returning a Series allows one to control the exact return structure and column names:
In [80]: df.apply(lambdax:pd.Series([1,2,3],index=['D','E','F']),axis=1)Out[80]: D E F0 1 2 31 1 2 32 1 2 33 1 2 34 1 2 35 1 2 3[6 rows x 3 columns]
[
1
,
2
]},
columns
=
[
'b'
,
'a'
])
In [82]:
df2
=
pd
.
DataFrame
({
"a"
:
[
4
,
5
]})
In [83]:
pd
.
concat
([
df1
,
df2
])
Out[83]:
b a
0 1.0 1
1 2.0 2
0 NaN 4
1 NaN 5
[4 rows x 2 columns]
To keep the previous behavior (sorting) and silence the warning, pass sort=True
In [84]: pd.concat([df1,df2],sort=True)Out[84]: a b0 1 1.01 2 2.00 4 NaN1 5 NaN[4 rows x 2 columns]
To accept the future behavior (no sorting), pass sort=False
Note that this change also applies to DataFrame.append(), which has also received a sort keyword for controlling this behavior.
=
pd
.
Int64Index
([
-
1
,
0
,
1
])
In [7]:
index
/
0
Out[7]:
Int64Index([0, 0, 0], dtype='int64')
# Previous behavior yielded different results depending on the type of zero in the divisor
In [8]:
index
/
0.0
Out[8]:
Float64Index([-inf, nan, inf], dtype='float64')
In [9]:
index
=
pd
.
UInt64Index
([
0
,
1
])
In [10]:
index
/
np
.
array
([
0
,
0
],
dtype
=
np
.
uint64
)
Out[10]:
UInt64Index([0, 0], dtype='uint64')
In [11]:
pd
.
RangeIndex
(
1
,
5
)
/
0
ZeroDivisionError: integer division or modulo by zero
Current behavior:
In [12]: index=pd.Int64Index([-1,0,1])# division by zero gives -infinity where negative,# +infinity where positive, and NaN for 0 / 0In [13]: index/0# The result of division by zero should not depend on# whether the zero is int or floatIn [14]: index/0.0In [15]: index=pd.UInt64Index([0,1])In [16]: index/np.array([0,0],dtype=np.uint64)In [17]: pd.RangeIndex(1,5)/0
In previous versions, the default value for the ordered parameter was False. This could potentially lead to the ordered parameter unintentionally being changed from True to False when users attempt to update categories if ordered is not explicitly specified, as it would silently default to False. The new behavior for ordered=None is to retain the existing value of ordered.
New behavior:
In [2]: frompandas.api.typesimportCategoricalDtypeIn [3]: cat=pd.Categorical(list('abcaba'),ordered=True,categories=list('cba'))In [4]: catOut[4]:[a, b, c, a, b, a]Categories (3, object): [c < b < a]In [5]: cdt=CategoricalDtype(categories=list('cbad'))In [6]: cat.astype(cdt)Out[6]:[a, b, c, a, b, a]Categories (4, object): [c < b < a < d]
Notice in the example above that the converted Categorical has retained ordered=True. Had the default value for ordered remained as False, the converted Categorical would have become unordered, despite ordered=False never being explicitly specified. To change the value of ordered, explicitly pass it to the new dtype, e.g. CategoricalDtype(categories=list('cbad'),ordered=False).
Note that the unintentional conversion of ordered discussed above did not arise in previous versions due to separate bugs that prevented astype from doing any type of category to category conversion (GH 10696, GH 18593). These bugs have been fixed in this release, and motivated changing the default value of ordered.
Addition or subtraction of NaT from TimedeltaIndex will return TimedeltaIndex instead of DatetimeIndex (GH 19124)
DatetimeIndex.shift() and TimedeltaIndex.shift() will now raise NullFrequencyError (which subclasses ValueError, which was raised in older versions) when the index object frequency is None (GH 19147)
Addition and subtraction of NaN from a Series with dtype='timedelta64[ns]' will raise a TypeError instead of treating the NaN as NaT (GH 19274)
Restricted DateOffset keyword arguments. Previously, DateOffset subclasses allowed arbitrary keyword arguments which could lead to unexpected behavior. Now, only valid arguments will be accepted. (GH 17176, GH 18226).
pandas.merge() provides a more informative error message when trying to merge on timezone-aware and timezone-naive columns (GH 15800)
For DatetimeIndex and TimedeltaIndex with freq=None, addition or subtraction of integer-dtyped array or Index will raise NullFrequencyError instead of TypeError (GH 19895)
Timestamp constructor now accepts a nanosecond keyword or positional argument (GH 18898)
DatetimeIndex will now raise an AttributeError when the tz attribute is set after instantiation (GH 3746)
DatetimeIndex with a pytz timezone will now return a consistent pytz timezone (GH 18595)
A Series of dtype=category constructed from an empty dict will now have categories of dtype=object rather than dtype=float64, consistently with the case in which an empty list is passed (GH 18515)
All-NaN levels in a MultiIndex are now assigned float rather than object dtype, promoting consistency with Index (GH 17929).
Levels names of a MultiIndex (when not None) are now required to be unique: trying to create a MultiIndex with repeated names will raise a ValueError (GH 18872)
Both construction and renaming of Index/MultiIndex with non-hashable name/names will now raise TypeError (GH 20527)
IntervalIndex constructor will raise if the closed parameter conflicts with how the input data is inferred to be closed (GH 18421)
Inserting missing values into indexes will work for all types of indexes and automatically insert the correct type of missing value (NaN, NaT, etc.) regardless of the type passed in (GH 18295)
When created with duplicate labels, MultiIndex now raises a ValueError. (GH 17464)
Series.fillna() now raises a TypeError instead of a ValueError when passed a list, tuple or DataFrame as a value (GH 18293)
The options html.border and mode.use_inf_as_null were deprecated in prior versions, these will now show FutureWarning rather than a DeprecationWarning (GH 19003)
IntervalIndex and IntervalDtype no longer support categorical, object, and string subtypes (GH 19016)
IntervalDtype now returns True when compared against 'interval' regardless of subtype, and IntervalDtype.name now returns 'interval' regardless of subtype (GH 18980)
KeyError now raises instead of ValueError in drop(), drop(), drop(), drop() when dropping a non-existent element in an axis with duplicates (GH 19186)
Set operations (union, difference…) on IntervalIndex with incompatible index types will now raise a TypeError rather than a ValueError (GH 19329)
DateOffset objects render more simply, e.g. <DateOffset:days=1> instead of <DateOffset:kwds={'days':1}> (GH 19403)
Categorical.fillna now validates its value and method keyword arguments. It now raises when both or none are specified, matching the behavior of Series.fillna() (GH 19682)
pd.to_datetime('today') now returns a datetime, consistent with pd.Timestamp('today'); previously pd.to_datetime('today') returned a .normalized() datetime (GH 19935)
Series.str.replace() now takes an optional regex keyword which, when set to False, uses literal string replacement rather than regex replacement (GH 16808)
Constructing a Series from a list of length 1 no longer broadcasts this list when a longer index is specified (GH 19714, GH 20391).
DataFrame.to_dict() with orient='index' no longer casts int columns to float for a DataFrame with only int and float columns (GH 18580)
A user-defined-function that is passed to Series.rolling().aggregate(), DataFrame.rolling().aggregate(), or its expanding cousins, will now always be passed a Series, rather than a np.array; .apply() only has the raw keyword, see here. This is consistent with the signatures of .aggregate() across pandas (GH 20584)
Rolling and Expanding types raise NotImplementedError upon iteration (GH 11704).
Bug in pct_change() using periods and freq returned different length outputs (GH 7292)
Bug in comparison of DatetimeIndex against None or datetime.date objects raising TypeError for == and != comparisons instead of all-False and all-True, respectively (GH 19301)
Bug in Timestamp and to_datetime() where a string representing a barely out-of-bounds timestamp would be incorrectly rounded down instead of raising OutOfBoundsDatetime (GH 19382)
Bug in to_datetime() where passing an out-of-bounds datetime with errors='coerce' and utc=True would raise OutOfBoundsDatetime instead of parsing to NaT (GH 19612)
Bug in DatetimeIndex and TimedeltaIndex addition and subtraction where name of the returned object was not always set consistently. (GH 19744)
Bug in Series with dtype='timedelta64[ns]' where addition or subtraction of TimedeltaIndex could return a Series with an incorrect name (GH 19043)
Bug in Timedelta.__floordiv__() and Timedelta.__rfloordiv__() dividing by many incompatible numpy objects was incorrectly allowed (GH 18846)
Bug where dividing a scalar timedelta-like object with TimedeltaIndex performed the reciprocal operation (GH 19125)
Bug in TimedeltaIndex where division by a Series would return a TimedeltaIndex instead of a Series (GH 19042)
Bug in Timedelta.__add__(), Timedelta.__sub__() where adding or subtracting a np.timedelta64 object would return another np.timedelta64 instead of a Timedelta (GH 19738)
Bug in Timedelta.__floordiv__(), Timedelta.__rfloordiv__() where operating with a Tick object would raise a TypeError instead of returning a numeric value (GH 19738)
Bug in Timedelta.total_seconds() causing precision errors, for example Timedelta('30S').total_seconds()==30.000000000000004 (GH 19458)
Bug in Timedelta.__rmod__() where operating with a numpy.timedelta64 returned a timedelta64 object instead of a Timedelta (GH 19820)
Multiplication of TimedeltaIndex by TimedeltaIndex will now raise TypeError instead of raising ValueError in cases of length mismatch (GH 19333)
Bug in indexing a TimedeltaIndex with a np.timedelta64 object which was raising a TypeError (GH 20393)
Bug in comparing DatetimeIndex, which failed to raise TypeError when attempting to compare timezone-aware and timezone-naive datetimelike objects (GH 18162)
Bug in localization of a naive, datetime string in a Series constructor with a datetime64[ns,tz] dtype (GH 174151)
Bug in tz-aware DatetimeIndex where addition/subtraction with a TimedeltaIndex or array with dtype='timedelta64[ns]' was incorrect (GH 17558)
Bug in DatetimeIndex.insert() where inserting NaT into a timezone-aware index incorrectly raised (GH 16357)
Bug in DataFrame constructor, where tz-aware Datetimeindex and a given column name will result in an empty DataFrame (GH 19157)
Bug in Timestamp.tz_localize() where localizing a timestamp near the minimum or maximum valid values could overflow and return a timestamp with an incorrect nanosecond value (GH 12677)
Bug when iterating over DatetimeIndex that was localized with fixed timezone offset that rounded nanosecond precision to microseconds (GH 19603)
Bug in the DataFrame constructor in which data containing very large positive or very large negative numbers was causing OverflowError (GH 18584)
Bug in Index constructor with dtype='uint64' where int-like floats were not coerced to UInt64Index (GH 18400)
Bug in DataFrame flex arithmetic (e.g. df.add(other,fill_value=foo)) with a fill_value other than None failed to raise NotImplementedError in corner cases where either the frame or other has length zero (GH 19522)
Multiplication and division of numeric-dtyped Index objects with timedelta-like scalars returns TimedeltaIndex instead of raising TypeError (GH 19333)
Bug in formatting tick labels with datetime.time() and fractional seconds (GH 18478).
Series.plot.kde() has exposed the args ind and bw_method in the docstring (GH 18461). The argument ind may now also be an integer (number of sample points).
Bug in DataFrame.groupby() where transformations using np.all and np.any were raising a ValueError (GH 20653)
Bug in DataFrame.resample() where ffill, bfill, pad, backfill, fillna, interpolate, and asfreq were ignoring loffset. (GH 20744)
Bug in DataFrame.groupby() when applying a function that has mixed data types and the user supplied function can fail on the grouping column (GH 20949)
Bug in DataFrameGroupBy.rolling().apply() where operations performed against the associated DataFrameGroupBy object could impact the inclusion of the grouped item(s) in the result (GH 14013)
Bug in DataFrame.unstack() which raises an error if index is a MultiIndex with unused labels on the unstacked level (GH 18562)
Fixed construction of a Series from a dict containing NaN as key (GH 18480)
Fixed construction of a DataFrame from a dict containing NaN as key (GH 18455)
Disabled construction of a Series where len(index) > len(data) = 1, which previously would broadcast the data item, and now raises a ValueError (GH 18819)
Suppressed error in the construction of a DataFrame from a dict containing scalar values when the corresponding keys are not included in the passed index (GH 18600)
Fixed (changed from object to float64) dtype of DataFrame initialized with axes, no data, and dtype=int (GH 19646)
Bug in Series.rank() where Series containing NaT modifies the Series inplace (GH 18521)
Bug in cut() which fails when using readonly arrays (GH 18773)
Bug in DataFrame.pivot_table() which fails when the aggfunc arg is of type string. The behavior is now consistent with other methods like agg and apply (GH 18713)
Bug in DataFrame.merge() in which merging using Index objects as vectors raised an Exception (GH 19038)
Bug in timezone comparisons, manifesting as a conversion of the index to UTC in .concat() (GH 18523)
Bug in concat() when concatenating sparse and dense series it returns only a SparseDataFrame. Should be a DataFrame. (GH 18914, GH 18686, and GH 16874)
Bug in DataFrame.join() which does an outer instead of a left join when being called with multiple DataFrames and some have non-unique indices (GH 19624)