This is a major release from 0.19.2 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.
Highlights include:
New .agg() API for Series/DataFrame similar to the groupby-rolling-resample API’s, see here
Integration with the feather-format, including a new top-level pd.read_feather() and DataFrame.to_feather() method, see here.
A new orient for JSON serialization, orient='table', that uses the Table Schema spec and that gives the possibility for a more interactive repr in the Jupyter Notebook, see here
Experimental support for exporting styled DataFrames (DataFrame.style) to Excel, see here
Window binary corr/cov operations now return a MultiIndexed DataFrame rather than a Panel, as Panel is now deprecated, see here
Series & DataFrame have been enhanced to support the aggregation API. This is a familiar API
from groupby, window operations, and resampling. This allows aggregation operations in a concise way
by using agg() and transform(). The full documentation
is here (GH 1623).
Here is a sample
In [1]: df=pd.DataFrame(np.random.randn(10,3),columns=['A','B','C'], ...: index=pd.date_range('1/1/2000',periods=10)) ...: In [2]: df.iloc[3:7]=np.nanIn [3]: dfOut[3]: A B C2000-01-01 0.469112 -0.282863 -1.5090592000-01-02 -1.135632 1.212112 -0.1732152000-01-03 0.119209 -1.044236 -0.8618492000-01-04 NaN NaN NaN2000-01-05 NaN NaN NaN2000-01-06 NaN NaN NaN2000-01-07 NaN NaN NaN2000-01-08 0.113648 -1.478427 0.5249882000-01-09 0.404705 0.577046 -1.7150022000-01-10 -1.039268 -0.370647 -1.157892[10 rows x 3 columns]
One can operate using string function names, callables, lists, or dictionaries of these.
Using a single function is equivalent to .apply.
In [4]: df.agg('sum')Out[4]: A -1.068226B -1.387015C -4.892029Length: 3, dtype: float64
Multiple aggregations with a list of functions.
In [5]: df.agg(['sum','min'])Out[5]: A B Csum -1.068226 -1.387015 -4.892029min -1.135632 -1.478427 -1.715002[2 rows x 3 columns]
Using a dict provides the ability to apply specific aggregations per column.
You will get a matrix-like output of all of the aggregators. The output has one column
per unique function. Those functions applied to a particular column will be NaN:
In [6]: df.agg({'A':['sum','min'],'B':['min','max']})Out[6]: A Bsum -1.068226 NaNmin -1.135632 -1.478427max NaN 1.212112[3 rows x 2 columns]
The API also supports a .transform() function for broadcasting results.
In [7]: df.transform(['abs',lambdax:x-x.min()])Out[7]: A B C abs <lambda> abs <lambda> abs <lambda>2000-01-01 0.469112 1.604745 0.282863 1.195563 1.509059 0.2059442000-01-02 1.135632 0.000000 1.212112 2.690539 0.173215 1.5417872000-01-03 0.119209 1.254841 1.044236 0.434191 0.861849 0.8531532000-01-04 NaN NaN NaN NaN NaN NaN2000-01-05 NaN NaN NaN NaN NaN NaN2000-01-06 NaN NaN NaN NaN NaN NaN2000-01-07 NaN NaN NaN NaN NaN NaN2000-01-08 0.113648 1.249281 1.478427 0.000000 0.524988 2.2399902000-01-09 0.404705 1.540338 0.577046 2.055473 1.715002 0.000000
When presented with mixed dtypes that cannot be aggregated, .agg() will only take the valid
aggregations. This is similar to how groupby .agg() works. (GH 15015)
In [8]: df=pd.DataFrame({'A':[1,2,3], ...: 'B':[1.,2.,3.], ...: 'C':['foo','bar','baz'],
The 'python' engine for read_csv(), as well as the read_fwf() function for parsing
fixed-width text files and read_excel() for parsing Excel files, now accept the dtype keyword argument for specifying the types of specific columns (GH 14295). See the io docs for more information.
Method .to_datetime() has gained an origin parameter
to_datetime() has gained a new parameter, origin, to define a reference date
from where to compute the resulting timestamps when parsing numerical values with a specific unit specified. (GH 11276, GH 11745)
For example, with 1960-01-01 as the starting date:
In [13]: pd.to_datetime
GroupBy enhancements
Strings passed to DataFrame.groupby() as the by parameter may now reference either column names or index level names. Previously, only column names could be referenced. This allows to easily group by a column and index level at the same time. (GH 5677)
In [15]: arrays=[['bar','bar','baz','baz','foo','foo','qux','qux'],
Better support for compressed URLs in read_csv
The compression code was refactored (GH 12688). As a result, reading
dataframes from URLs in read_csv() or read_table() now supports
additional compression methods: xz, bz2, and zip (GH 14570).
Previously, only gzip compression was supported. By default, compression of
URLs and paths are now inferred using their file extensions. Additionally,
support for bz2 compression in the python 2 C-engine improved ().
pandas has significantly improved support for operations involving unsigned,
or purely non-negative, integers. Previously, handling these integers would
result in improper rounding or data-type casting, leading to incorrect results.
Notably, a new numerical index, UInt64Index, has been created (GH 14937)
In [1]: idx=pd.UInt64Index([1,2,3])In [2]: df=pd.DataFrame({'A':
GroupBy on categoricals
In previous versions, .groupby(...,sort=False) would fail with a ValueError when grouping on a categorical series with some categories not appearing in the data. (GH 13179)
In [34]: chromosomes=np.r_[np.arange(1,23).astype(str),
Experimental support has been added to export DataFrame.style formats to Excel using the openpyxl engine. (GH 15530)
For example, after running the following, styled.xlsx renders as below:
In [41]: np.random.seed(24)In [42]: df=pd.DataFrame({'A'
IntervalIndex
pandas has gained an IntervalIndex with its own dtype, interval as well as the Interval scalar type. These allow first-class support for interval
notation, specifically as a return type for the categories in cut() and qcut(). The IntervalIndex allows some unique indexing, see the
docs. (GH 7640, GH 8625)
Other enhancements
DataFrame.rolling() now accepts the parameter closed='right'|'left'|'both'|'neither' to choose the rolling window-endpoint closedness. See the documentation (GH 13965)
Integration with the feather-format, including a new top-level pd.read_feather() and DataFrame.to_feather() method, see here.
Series.str.replace() now accepts a callable, as replacement, which is passed to ()
Backwards incompatible API changes
Possible incompatibility for HDF5 formats created with pandas < 0.13.0
pd.TimeSeries was deprecated officially in 0.17.0, though has already been an alias since 0.13.0. It has
been dropped in favor of pd.Series. (GH 15098).
This may cause HDF5 files that were created in prior versions to become unreadable if pd.TimeSeries
was used. This is most likely to be for pandas < 0.13.0. If you find yourself in this situation.
You can use a recent prior version of pandas to read in your HDF5 files,
then write them out again after applying the procedure below.
map on an Index now returns an Index, not a numpy array (GH 12766)
In [56]: idx=pd.Index([1,2])In [57]: idxOut[57]: Index([1, 2], dtype='int64')In [58]: mi=
Accessing datetime fields of Index now return Index
The datetime-related attributes (see here
for an overview) of DatetimeIndex, PeriodIndex and TimedeltaIndex previously
returned numpy arrays. They will now return a new Index object, except
in the case of a boolean field, where the result will still be a boolean ndarray. (GH 15022)
Previous behaviour:
In [1]: idx=pd.date_range("2015-01-01"
pd.unique will now be consistent with extension types
In prior versions, using Series.unique() and pandas.unique() on Categorical and tz-aware
data-types would yield different return types. These are now made consistent. (GH 15903)
Datetime tz-aware
Previous behaviour:
# SeriesIn [5]: pd.Series([pd
S3 file handling
pandas now uses s3fs for handling S3 connections. This shouldn’t break
any code. However, since s3fs is not a required dependency, you will need to install it separately, like boto
in prior versions of pandas. (GH 11915).
In [70]: df=pd.DataFrame({'a':[1,2,3]},pd.DatetimeIndex
Concat of different float dtypes will not automatically upcast
Previously, concat of multiple objects with different float dtypes would automatically upcast results to a dtype of float64.
Now the smallest acceptable dtype will be used (GH 13247)
In [71]: df1=pd.DataFrame(np.array([1.0],dtype=np.
pandas Google BigQuery support has moved
pandas has split off Google BigQuery support into a separate package pandas-gbq. You can condainstallpandas-gbq-cconda-forge or
pipinstallpandas-gbq to get it. The functionality of read_gbq() and DataFrame.to_gbq() remain the same with the
currently released version of pandas-gbq=0.1.4. Documentation is now hosted here (GH 15347)
Memory usage for Index is more accurate
In previous versions, showing .memory_usage() on a pandas structure that has an index, would only include actual index values and not include structures that facilitated fast indexing. This will generally be different for Index and MultiIndex and less-so for other index types. (GH 15237)
Previous behavior:
In [8]: index=pd.Index(['foo','bar','baz'])In [9]: index
DataFrame.sort_index changes
In certain cases, calling .sort_index() on a MultiIndexed DataFrame would return the same DataFrame without seeming to sort.
This would happen with a lexsorted, but non-monotonic levels. (GH 15622, GH 15687, GH 14015, GH 13431, GH 15797)
This is unchanged from prior versions, but shown for illustration purposes:
In[81]:df=pd
GroupBy describe formatting
The output formatting of groupby.describe() now labels the describe() metrics in the columns instead of the index.
This format is consistent with groupby.agg() when applying multiple functions at once. (GH 4792)
Previous behavior:
In [1]: df=pd.DataFrame({'A':[1,1,2,
Window binary corr/cov operations return a MultiIndex DataFrame
A binary window operation, like .corr() or .cov(), when operating on a .rolling(..), .expanding(..), or .ewm(..) object,
will now return a 2-level MultiIndexedDataFrame rather than a Panel, as Panel is now deprecated,
see here. These are equivalent in function,
but a MultiIndexed DataFrame enjoys more support in pandas.
See the section on for more information. ()
HDFStore where string comparison
In previous versions most types could be compared to string column in a HDFStore
usually resulting in an invalid comparison, returning an empty result frame. These comparisons will now raise a
TypeError (GH 15492)
In [88]: df=pd.DataFrame({'unparsed_date':['2014-01-01','2014-01-01']})In [89]: df.to_hdf(
Index.intersection and inner join now preserve the order of the left Index
The documentation for pivot_table() states that a DataFrame is always returned. Here a bug
is fixed that allowed this to return a Series under certain circumstance. (GH 4386)
In [101]: df=pd.DataFrame({'col1':[3,4,
Other API changes
numexpr version is now required to be >= 2.4.6 and it will not be used at all if this requisite is not fulfilled (GH 15213).
CParserError has been renamed to ParserError in pd.read_csv() and will be removed in the future (GH 12665)
SparseArray.cumsum() and SparseSeries.cumsum() will now always return SparseArray and respectively ()
Reorganization of the library: privacy changes
Modules privacy has changed
Some formerly public python/c/c++/cython extension modules have been moved and/or renamed. These are all removed from the public API.
Furthermore, the pandas.core, pandas.compat, and pandas.util top-level modules are now considered to be PRIVATE.
If indicated, a deprecation warning will be issued if you reference these modules. (GH 12588)
Previous Location
New Location
Deprecated
pandas.lib
pandas._libs.lib
X
pandas.tslib
pandas._libs.tslib
X
pandas.computation
pandas.core.computation
X
pandas.msgpack
pandas.io.msgpack
Some new subpackages are created with public functionality that is not directly
exposed in the top-level namespace: pandas.errors, pandas.plotting and
pandas.testing (more details below). Together with pandas.api.types and
certain functions in the pandas.io and pandas.tseries submodules,
these are now the public subpackages.
Further changes:
The function union_categoricals() is now importable from pandas.api.types, formerly from pandas.types.concat (GH 15998)
The type import pandas.tslib.NaTType is deprecated and can be replaced by using type(pandas.NaT) (GH 16146)
The public functions in pandas.tools.hashing deprecated from that locations, but are now importable from pandas.util (GH 16223)
pandas.errors
We are adding a standard public module for all pandas exceptions & warnings pandas.errors. (GH 14800). Previously
these exceptions & warnings could be imported from pandas.core.common or pandas.io.common. These exceptions and warnings
will be removed from the *.common locations in a future release. (GH 15541)
We are adding a standard module that exposes the public testing functions in pandas.testing (GH 9895). Those functions can be used when writing tests for functionality using pandas objects.
The following testing functions are now part of this API:
A new public pandas.plotting module has been added that holds plotting functionality that was previously in either pandas.tools.plotting or in the top-level namespace. See the deprecations sections for more details.
Other development changes
Building pandas for development now requires cython>=0.23 (GH 14831)
Require at least 0.23 version of cython to avoid problems with character encodings (GH 14699)
The .ix indexer is deprecated, in favor of the more strict .iloc and .loc indexers. .ix offers a lot of magic on the inference of what the user wants to do. More specifically, .ix can decide to index positionally OR via labels, depending on the data type of the index. This has caused quite a bit of user confusion over the years. The full indexing documentation is here. (GH 14218)
The recommended methods of indexing are:
.loc if you want to label index
.iloc if you want to positionally index.
Using .ix will now show a DeprecationWarning with a link to some examples of how to convert code here.
In [104]: df=pd.DataFrame({'A':[1,2,3], .....: 'B':[4,5,6]}, .....: index=list('abc')) .....: In [105]:
Previous behavior, where you wish to get the 0th and the 2nd elements from the index in the ‘A’ column.
In [3]: df.ix[[0,2],'A']Out[3]:a 1c 3Name: A, dtype: int64
Using .loc. Here we will select the appropriate indexes from the index, then use label indexing.
In [106]: df.loc[df.index[[0,2]],'A']Out[106]: a 1c 3Name: A, Length: 2, dtype: int64
Using .iloc. Here we will get the location of the ‘A’ column, then use positional indexing to select things.
In [107]: df.iloc[[0,2],df.columns.get_loc('A')]Out[107]: a 1c 3Name: A, Length: 2, dtype: int64
Deprecate Panel
Panel is deprecated and will be removed in a future version. 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).
In [133]: importpandas._testingastmIn [134]:
Deprecate groupby.agg() with a dictionary when renaming
The .groupby(..).agg(..), .rolling(..).agg(..), and .resample(..).agg(..) syntax can accept a variable of inputs, including scalars,
list, and a dict of column names to scalars or lists. This provides a useful syntax for constructing multiple
(potentially different) aggregations.
However, .agg(..) can also accept a dict that allows ‘renaming’ of the result columns. This is a complicated and confusing syntax, as well as not consistent
between Series and DataFrame. We are deprecating this ‘renaming’ functionality.
We are deprecating passing a dict to a grouped/rolled/resampled Series. This allowed
one to rename the resulting aggregation, but this had a completely different
meaning than passing a dictionary to a grouped , which accepts column-to-aggregations.
Deprecate .plotting
The pandas.tools.plotting module has been deprecated, in favor of the top level pandas.plotting module. All the public plotting functions are now available
from pandas.plotting (GH 12548).
Furthermore, the top-level pandas.scatter_matrix and pandas.plot_params are deprecated.
Users can import these from pandas.plotting as well.
Previous script:
pd.tools.plotting
Other deprecations
SparseArray.to_dense() has deprecated the fill parameter, as that parameter was not being respected (GH 14647)
SparseSeries.to_dense() has deprecated the sparse_only parameter (GH 14647)
Series.repeat() has deprecated the reps parameter in favor of repeats (GH 12662)
Removal of prior version deprecations/changes
The pandas.rpy module is removed. Similar functionality can be accessed
through the rpy2 project.
See the R interfacing docs for more details.
The pandas.io.ga module with a google-analytics interface is removed (GH 11308).
Similar functionality can be found in the Google2Pandas package.
pd.to_datetime and pd.to_timedelta have dropped the coerce parameter in favor of errors (GH 13602)
pandas.stats.fama_macbeth, pandas.stats.ols, pandas.stats.plm and pandas.stats.var, as well as the top-level pandas.fama_macbeth and pandas.ols routines are removed. Similar functionality can be found in the statsmodels package. (GH 11898)
The TimeSeries and SparseTimeSeries classes, aliases of Series
and SparseSeries, are removed (GH 10890, GH 15098).
Series.is_time_series is dropped in favor of Series.index.is_all_dates (GH 15098)
The deprecated irow, icol, iget and iget_value methods are removed
in favor of iloc and iat as explained here (GH 10711).
The deprecated DataFrame.iterkv() has been removed in favor of DataFrame.iteritems() (GH 10711)
The Categorical constructor has dropped the name parameter (GH 10632)
Categorical has dropped support for NaN categories (GH 10748)
The take_last parameter has been dropped from duplicated(), drop_duplicates(), nlargest(), and nsmallest() methods (GH 10236, GH 10792, GH 10920)
Series, Index, and DataFrame have dropped the sort and order methods (GH 10726)
Where clauses in pytables are only accepted as strings and expressions types and not other data-types (GH 12027)
DataFrame has dropped the combineAdd and combineMult methods in favor of add and mul respectively (GH 10735)
Performance improvements
Improved performance of pd.wide_to_long() (GH 14779)
Improved performance of pd.factorize() by releasing the GIL with object dtype when inferred as strings (GH 14859, GH 16057)
Improved performance of timeseries plotting with an irregular DatetimeIndex
(or with compat_x=True) (GH 15073).
The default is set at origin='unix', which defaults to 1970-01-0100:00:00, which is
commonly called ‘unix epoch’ or POSIX time. This was the previous default, so this is a backward compatible change.
In [14]: pd.to_datetime([1,2,3],unit='D')Out[14]: DatetimeIndex(['1970-01-02', '1970-01-03', '1970-01-04'], dtype='datetime64[ns]', freq=None)
Bug in converting object elements of array-like objects to unsigned 64-bit integers (GH 4471, GH 14982)
Bug in Series.unique() in which unsigned 64-bit integers were causing overflow (GH 14721)
Bug in DataFrame construction in which unsigned 64-bit integer elements were being converted to objects (GH 14881)
Bug in pd.read_csv() in which unsigned 64-bit integer elements were being improperly converted to the wrong data types (GH 14983)
Bug in pd.unique() in which unsigned 64-bit integers were causing overflow (GH 14915)
Bug in pd.value_counts() in which unsigned 64-bit integers were being erroneously truncated in the output (GH 14934)
[
'X'
,
'Y'
]]
In [35]:
df
=
pd
.
DataFrame
({
....:
'A'
:
np
.
random
.
randint
(
100
),
....:
'B'
:
np
.
random
.
randint
(
100
),
....:
'C'
:
np
.
random
.
randint
(
100
),
....:
'chromosomes'
:
pd
.
Categorical
(
np
.
random
.
choice
(
chromosomes
,
100
),
....:
categories
=
chromosomes
,
....:
ordered
=
True
)})
....:
In [36]:
df
Out[36]:
A B C chromosomes
0 87 22 81 4
1 87 22 81 13
2 87 22 81 22
3 87 22 81 2
4 87 22 81 6
.. .. .. .. ...
95 87 22 81 8
96 87 22 81 11
97 87 22 81 X
98 87 22 81 1
99 87 22 81 19
[100 rows x 4 columns]
Previous behavior:
In [3]: df[df.chromosomes!='1'].groupby('chromosomes',observed=False,sort=False).sum()---------------------------------------------------------------------------ValueError: items in new_categories are not the same as in old categories
Additionally, the repr for DataFrame and Series can now publish
this JSON Table schema representation of the Series or DataFrame if you are
using IPython (or another frontend like nteract using the Jupyter messaging
protocol).
This gives frontends like the Jupyter notebook and nteract
more flexibility in how they display pandas objects, since they have
more information about the data.
You must enable this by setting the display.html.table_schema option to True.
(
size
=
(
1000
,
5
))
arr
[
arr
<
.9
]
=
0
sp_arr
=
csr_matrix
(
arr
)
sp_arr
sdf
=
pd
.
SparseDataFrame
(
sp_arr
)
sdf
To convert a SparseDataFrame back to sparse SciPy matrix in COO format, you can use:
Series.str.replace() now accepts a compiled regular expression as a pattern (GH 15446)
Series.sort_index accepts parameters kind and na_position (GH 13589, GH 14444)
DataFrame and DataFrame.groupby() have gained a nunique() method to count the distinct values over an axis (GH 14336, GH 15197).
DataFrame has gained a melt() method, equivalent to pd.melt(), for unpivoting from a wide to long format (GH 12640).
pd.read_excel() now preserves sheet order when using sheetname=None (GH 9930)
Multiple offset aliases with decimal points are now supported (e.g. 0.5min is parsed as 30s) (GH 8419)
.isnull() and .notnull() have been added to Index object to make them more consistent with the Series API (GH 15300)
New UnsortedIndexError (subclass of KeyError) raised when indexing/slicing into an
unsorted MultiIndex (GH 11897). This allows differentiation between errors due to lack
of sorting or an incorrect key. See here
MultiIndex has gained a .to_frame() method to convert to a DataFrame (GH 12397)
pd.cut and pd.qcut now support datetime64 and timedelta64 dtypes (GH 14714, GH 14798)
pd.qcut has gained the duplicates='raise'|'drop' option to control whether to raise on duplicated edges (GH 7751)
Series provides a to_excel method to output Excel files (GH 8825)
The usecols argument in pd.read_csv() now accepts a callable function as a value (GH 14154)
The skiprows argument in pd.read_csv() now accepts a callable function as a value (GH 10882)
The nrows and chunksize arguments in pd.read_csv() are supported if both are passed (GH 6774, GH 15755)
DataFrame.plot now prints a title above each subplot if suplots=True and title is a list of strings (GH 14753)
DataFrame.plot can pass the matplotlib 2.0 default color cycle as a single string as color parameter, see here. (GH 15516)
Series.interpolate() now supports timedelta as an index type with method='time' (GH 6424)
Addition of a level keyword to DataFrame/Series.rename to rename
labels in the specified level of a MultiIndex (GH 4160).
DataFrame.reset_index() will now interpret a tuple index.name as a key spanning across levels of columns, if this is a MultiIndex (GH 16164)
Styler.render() now accepts **kwargs to allow user-defined variables in the template (GH 15649)
Compatibility with Jupyter notebook 5.0; MultiIndex column labels are left-aligned and MultiIndex row-labels are top-aligned (GH 15379)
TimedeltaIndex now has a custom date-tick formatter specifically designed for nanosecond level precision (GH 8711)
pd.api.types.union_categoricals gained the ignore_ordered argument to allow ignoring the ordered attribute of unioned categoricals (GH 13410). See the categorical union docs for more information.
DataFrame.to_latex() and DataFrame.to_string() now allow optional header aliases. (GH 15536)
Re-enable the parse_dates keyword of pd.read_excel() to parse string columns as dates (GH 14326)
Added .empty property to subclasses of Index. (GH 15270)
Enabled floor division for Timedelta and TimedeltaIndex (GH 15828)
pandas.io.json.json_normalize() gained the option errors='ignore'|'raise'; the default is errors='raise' which is backward compatible. (GH 14583)
pandas.io.json.json_normalize() with an empty list will return an empty DataFrame (GH 15534)
pandas.io.json.json_normalize() has gained a sep option that accepts str to separate joined fields; the default is “.”, which is backward compatible. (GH 14883)
pd.read_csv() will now raise a ParserError error whenever any parsing error occurs (GH 15913, GH 15925)
pd.read_csv() now supports the error_bad_lines and warn_bad_lines arguments for the Python parser (GH 15925)
The display.show_dimensions option can now also be used to specify
whether the length of a Series should be shown in its repr (GH 7117).
parallel_coordinates() has gained a sort_labels keyword argument that sorts class labels and the colors assigned to them (GH 15908)
Options added to allow one to turn on/off using bottleneck and numexpr, see here (GH 16157)
DataFrame.style.bar() now accepts two more options to further customize the bar chart. Bar alignment is set with align='left'|'mid'|'zero', the default is “left”, which is backward compatible; You can now pass a list of color=[color_negative,color_positive]. (GH 14757)
This has the advantage that specific Index methods are still available on the
result. On the other hand, this might have backward incompatibilities: e.g.
compared to numpy arrays, Index objects are not mutable. To get the original
ndarray, you can always convert explicitly using np.asarray(idx.hour).
However, this example, which has a non-monotonic 2nd level,
doesn’t behave as desired.
In [77]: df=pd.DataFrame({'value':[1,2,3,4]}, ....: index=pd.MultiIndex([['a','b'],['bb','aa']], ....: [[0,0,1,1],[0,1,0,1]])) ....: In [78]: dfOut[78]: valuea bb 1 aa 2b bb 3 aa 4[4 rows x 1 columns]
In [82]: np.random.seed(1234)In [83]: df=pd.DataFrame(np.random.rand(100,2), ....: columns=pd.Index(['A','B'],name='bar'), ....: index=pd.date_range('20160101', ....: periods=100,freq='D',name='foo')) ....: In [84]: df.tail()Out[84]: bar A Bfoo 2016-04-05 0.640880 0.1262052016-04-06 0.171465 0.7370862016-04-07 0.127029 0.3696502016-04-08 0.604334 0.1031042016-04-09 0.802374 0.945553[5 rows x 2 columns]
Previous behavior:
In [2]: df.rolling(12).corr()Out[2]:<class 'pandas.core.panel.Panel'>Dimensions: 100 (items) x 2 (major_axis) x 2 (minor_axis)Items axis: 2016-01-01 00:00:00 to 2016-04-09 00:00:00Major_axis axis: A to BMinor_axis axis: A to B
New behavior:
In [85]: res=df.rolling(12).corr()In [86]: res.tail()Out[86]: bar A Bfoo bar 2016-04-07 B -0.132090 1.0000002016-04-08 A 1.000000 -0.145775 B -0.145775 1.0000002016-04-09 A 1.000000 0.119645 B 0.119645 1.000000[5 rows x 2 columns]
Retrieving a correlation matrix for a cross-section
In [87]: df.rolling(12).corr().loc['2016-04-07']Out[87]: bar A Bbar A 1.00000 -0.13209B -0.13209 1.00000[2 rows x 2 columns]
'store.h5'
,
key
=
'key'
,
format
=
'table'
,
data_columns
=
True
)
In [90]:
df
.
dtypes
Out[90]:
unparsed_date object
Length: 1, dtype: object
Previous behavior:
In [4]: pd.read_hdf('store.h5','key',where='unparsed_date > ts')File "<string>", line 1 (unparsed_date > 1970-01-01 00:00:01.388552400) ^SyntaxError: invalid token
New behavior:
In [18]: ts=pd.Timestamp('2014-01-01')In [19]: pd.read_hdf('store.h5','key',where='unparsed_date > ts')TypeError: Cannot compare 2014-01-01 00:00:00 oftype <class 'pandas.tslib.Timestamp'> to string column
DataFrame.applymap() with an empty DataFrame will return a copy of the empty DataFrame instead of a Series (GH 8222)
Series.map() now respects default values of dictionary subclasses with a __missing__ method, such as collections.Counter (GH 15999)
.loc has compat with .ix for accepting iterators, and NamedTuples (GH 15120)
interpolate() and fillna() will raise a ValueError if the limit keyword argument is not greater than 0. (GH 9217)
pd.read_csv() will now issue a ParserWarning whenever there are conflicting values provided by the dialect parameter and the user (GH 14898)
pd.read_csv() will now raise a ValueError for the C engine if the quote character is larger than one byte (GH 11592)
inplace arguments now require a boolean value, else a ValueError is thrown (GH 14189)
pandas.api.types.is_datetime64_ns_dtype will now report True on a tz-aware dtype, similar to pandas.api.types.is_datetime64_any_dtype
DataFrame.asof() will return a null filled Series instead the scalar NaN if a match is not found (GH 15118)
Specific support for copy.copy() and copy.deepcopy() functions on NDFrame objects (GH 15444)
Series.sort_values() accepts a one element list of bool for consistency with the behavior of DataFrame.sort_values() (GH 15604)
.merge() and .join() on category dtype columns will now preserve the category dtype when possible (GH 10409)
SparseDataFrame.default_fill_value will be 0, previously was nan in the return from pd.get_dummies(...,sparse=True) (GH 15594)
The default behaviour of Series.str.match has changed from extracting
groups to matching the pattern. The extracting behaviour was deprecated
since pandas version 0.13.0 and can be done with the Series.str.extract
method (GH 5224). As a consequence, the as_indexer keyword is
ignored (no longer needed to specify the new behaviour) and is deprecated.
NaT will now correctly report False for datetimelike boolean operations such as is_month_start (GH 15781)
NaT will now correctly return np.nan for Timedelta and Period accessors such as days and quarter (GH 15782)
NaT will now returns NaT for tz_localize and tz_convert
methods (GH 15830)
DataFrame and Panel constructors with invalid input will now raise ValueError rather than PandasError, if called with scalar inputs and not axes (GH 15541)
DataFrame and Panel constructors with invalid input will now raise ValueError rather than pandas.core.common.PandasError, if called with scalar inputs and not axes; The exception PandasError is removed as well. (GH 15541)
The exception pandas.core.common.AmbiguousIndexError is removed as it is not referenced (GH 15541)
pandas.index
pandas._libs.index
pandas.algos
pandas._libs.algos
pandas.hashtable
pandas._libs.hashtable
pandas.indexes
pandas.core.indexes
pandas.json
pandas._libs.json / pandas.io.json
X
pandas.parser
pandas._libs.parsers
X
pandas.formats
pandas.io.formats
pandas.sparse
pandas.core.sparse
pandas.tools
pandas.core.reshape
X
pandas.types
pandas.core.dtypes
X
pandas.io.sas.saslib
pandas.io.sas._sas
pandas._join
pandas._libs.join
pandas._hash
pandas._libs.hashing
pandas._period
pandas._libs.period
pandas._sparse
pandas._libs.sparse
pandas._testing
pandas._libs.testing
pandas._window
pandas._libs.window
The modules in pandas.util: decorators, print_versions, doctools, validators, depr_module are now private. Only the functions exposed in pandas.util itself are public (GH 16223)
'ParserError'
,
'ParserWarning'
,
'PerformanceWarning'
,
'UnsortedIndexError'
,
'UnsupportedFunctionCall'
]
testing.assert_index_equal()
df
Out[105]:
A B
a 1 4
b 2 5
c 3 6
[3 rows x 2 columns]
p
=
tm
.
makePanel
()
In [135]:
p
Out[135]:
<class 'pandas.core.panel.Panel'>
Dimensions: 3 (items) x 3 (major_axis) x 4 (minor_axis)
Items axis: ItemA to ItemC
Major_axis axis: 2000-01-03 00:00:00 to 2000-01-05 00:00:00
Minor_axis axis: A to D
Convert to a MultiIndex DataFrame
In [136]: p.to_frame()Out[136]: ItemA ItemB ItemCmajor minor2000-01-03 A 0.628776 -1.409432 0.209395 B 0.988138 -1.347533 -0.896581 C -0.938153 1.272395 -0.161137 D -0.223019 -0.591863 -1.0515392000-01-04 A 0.186494 1.422986 -0.592886 B -0.072608 0.363565 1.104352 C -1.239072 -1.449567 0.889157 D 2.123692 -0.414505 -0.3195612000-01-05 A 0.952478 -2.147855 -1.473116 B -0.550603 -0.014752 -0.431550 C 0.139683 -1.195524 0.288377 D 0.122273 -1.425795 -0.619993[12 rows x 3 columns]
We are deprecating passing a dict-of-dicts to a grouped/rolled/resampled DataFrame in a similar manner.
This is an illustrative example:
In [108]: df=pd.DataFrame({'A':[1,1,1,2,2], .....: 'B':range(5), .....: 'C':range(5)}) .....: In [109]: dfOut[109]: A B C0 1 0 01 1 1 12 1 2 23 2 3 34 2 4 4[5 rows x 3 columns]
Here is a typical useful syntax for computing different aggregations for different columns. This
is a natural, and useful syntax. We aggregate from the dict-to-list by taking the specified
columns and applying the list of functions. This returns a MultiIndex for the columns (this is not deprecated).
In [110]: df.groupby('A').agg({'B':'sum','C':'min'})Out[110]: B CA 1 3 02 7 3[2 rows x 2 columns]
Here’s an example of the first deprecation, passing a dict to a grouped Series. This
is a combination aggregation & renaming:
In [6]: df.groupby('A').B.agg({'foo':'count'})FutureWarning: using a dict on a Series for aggregationis deprecated and will be removed in a future versionOut[6]: fooA1 32 2
You can accomplish the same operation, more idiomatically by:
In [111]: df.groupby('A').B.agg(['count']).rename(columns={'count':'foo'})Out[111]: fooA 1 32 2[2 rows x 1 columns]
Here’s an example of the second deprecation, passing a dict-of-dict to a grouped DataFrame:
In [112]: (df.groupby('A') .....: .agg({'B':'sum','C':'min'}) .....: .rename(columns={'B':'foo','C':'bar'}) .....: ) .....: Out[112]: foo barA 1 3 02 7 3[2 rows x 2 columns]
.
scatter_matrix
(
df
)
pd
.
scatter_matrix
(
df
)
Should be changed to:
pd.plotting.scatter_matrix(df)
The Series constructor and .astype method have deprecated accepting timestamp dtypes without a frequency (e.g. np.datetime64) for the dtype parameter (GH 15524)
Index.repeat() and MultiIndex.repeat() have deprecated the n parameter in favor of repeats (GH 12662)
Categorical.searchsorted() and Series.searchsorted() have deprecated the v parameter in favor of value (GH 12662)
TimedeltaIndex.searchsorted(), DatetimeIndex.searchsorted(), and PeriodIndex.searchsorted() have deprecated the key parameter in favor of value (GH 12662)
DataFrame.astype() has deprecated the raise_on_error parameter in favor of errors (GH 14878)
Series.sortlevel and DataFrame.sortlevel have been deprecated in favor of Series.sort_index and DataFrame.sort_index (GH 15099)
importing concat from pandas.tools.merge has been deprecated in favor of imports from the pandas namespace. This should only affect explicit imports (GH 15358)
Series/DataFrame/Panel.consolidate() been deprecated as a public method. (GH 15483)
The as_indexer keyword of Series.str.match() has been deprecated (ignored keyword) (GH 15257).
The following top-level pandas functions have been deprecated and will be removed in a future version (GH 13790, GH 15940)
pd.pnow(), replaced by Period.now()
pd.Term, is removed, as it is not applicable to user code. Instead use in-line string expressions in the where clause when searching in HDFStore
pd.Expr, is removed, as it is not applicable to user code.
pd.match(), is removed.
pd.groupby(), replaced by using the .groupby() method directly on a Series/DataFrame
pd.get_store(), replaced by a direct call to pd.HDFStore(...)
is_any_int_dtype, is_floating_dtype, and is_sequence are deprecated from pandas.api.types (GH 16042)
Bug in DataFrame.loc with indexing a MultiIndex with a numpy array (GH 15434)
Bug in Series.asof which raised if the series contained all np.nan (GH 15713)
Bug in .at when selecting from a tz-aware column (GH 15822)
Bug in Series.where() and DataFrame.where() where array-like conditionals were being rejected (GH 15414)
Bug in Series.where() where TZ-aware data was converted to float representation (GH 15701)
Bug in .loc that would not return the correct dtype for scalar access for a DataFrame (GH 11617)
Bug in output formatting of a MultiIndex when names are integers (GH 12223, GH 15262)
Bug in Categorical.searchsorted() where alphabetical instead of the provided categorical order was used (GH 14522)
Bug in Series.iloc where a Categorical object for list-like indexes input was returned, where a Series was expected. (GH 14580)
Bug in DataFrame.isin comparing datetimelike to empty frame (GH 15473)
Bug in .reset_index() when an all NaN level of a MultiIndex would fail (GH 6322)
Bug in .reset_index() when raising error for index name already present in MultiIndex columns (GH 16120)
Bug in creating a MultiIndex with tuples and not passing a list of names; this will now raise ValueError (GH 15110)
Bug in the HTML display with a MultiIndex and truncation (GH 14882)
Bug in the display of .info() where a qualifier (+) would always be displayed with a MultiIndex that contains only non-strings (GH 15245)
Bug in pd.concat() where the names of MultiIndex of resulting DataFrame are not handled correctly when None is presented in the names of MultiIndex of input DataFrame (GH 15787)
Bug in DataFrame.sort_index() and Series.sort_index() where na_position doesn’t work with a MultiIndex (GH 14784, GH 16604)
Bug in pd.concat() when combining objects with a CategoricalIndex (GH 16111)
Bug in indexing with a scalar and a CategoricalIndex (GH 16123)
Bug in pd.read_csv() in which a file containing a row with many columns followed by rows with fewer columns would cause a crash (GH 14125)
Bug in pd.read_csv() for the C engine where usecols were being indexed incorrectly with parse_dates (GH 14792)
Bug in pd.read_csv() with parse_dates when multi-line headers are specified (GH 15376)
Bug in pd.read_csv() with float_precision='round_trip' which caused a segfault when a text entry is parsed (GH 15140)
Bug in pd.read_csv() when an index was specified and no values were specified as null values (GH 15835)
Bug in pd.read_csv() in which certain invalid file objects caused the Python interpreter to crash (GH 15337)
Bug in pd.read_csv() in which invalid values for nrows and chunksize were allowed (GH 15767)
Bug in pd.read_csv() for the Python engine in which unhelpful error messages were being raised when parsing errors occurred (GH 15910)
Bug in pd.read_csv() in which the skipfooter parameter was not being properly validated (GH 15925)
Bug in pd.to_csv() in which there was numeric overflow when a timestamp index was being written (GH 15982)
Bug in pd.util.hashing.hash_pandas_object() in which hashing of categoricals depended on the ordering of categories, instead of just their values. (GH 15143)
Bug in .to_json() where lines=True and contents (keys or values) contain escaped characters (GH 15096)
Bug in .to_json() causing single byte ascii characters to be expanded to four byte unicode (GH 15344)
Bug in .to_json() for the C engine where rollover was not correctly handled for case where frac is odd and diff is exactly 0.5 (GH 15716, GH 15864)
Bug in pd.read_json() for Python 2 where lines=True and contents contain non-ascii unicode characters (GH 15132)
Bug in pd.read_msgpack() in which Series categoricals were being improperly processed (GH 14901)
Bug in pd.read_msgpack() which did not allow loading of a dataframe with an index of type CategoricalIndex (GH 15487)
Bug in pd.read_msgpack() when deserializing a CategoricalIndex (GH 15487)
Bug in DataFrame.to_records() with converting a DatetimeIndex with a timezone (GH 13937)
Bug in DataFrame.to_records() which failed with unicode characters in column names (GH 11879)
Bug in .to_sql() when writing a DataFrame with numeric index names (GH 15404).
Bug in DataFrame.to_html() with index=False and max_rows raising in IndexError (GH 14998)
Bug in pd.read_hdf() passing a Timestamp to the where parameter with a non date column (GH 15492)
Bug in DataFrame.to_stata() and StataWriter which produces incorrectly formatted files to be produced for some locales (GH 13856)
Bug in StataReader and StataWriter which allows invalid encodings (GH 15723)
Bug in the Series repr not showing the length when the output was truncated (GH 15962).