Table Of Contents

Search

Enter search terms or a module, class or function name.

What’s New

These are new features and improvements of note in each release.

v0.22.0 (December 29, 2017)

This is a major release from 0.21.1 and includes a single, API-breaking change. We recommend that all users upgrade to this version after carefully reading the release note (singular!).

Backwards incompatible API changes

Pandas 0.22.0 changes the handling of empty and all-NA sums and products. The summary is that

  • The sum of an empty or all-NA Series is now 0
  • The product of an empty or all-NA Series is now 1
  • We’ve added a min_count parameter to .sum() and .prod() controlling the minimum number of valid values for the result to be valid. If fewer than min_count non-NA values are present, the result is NA. The default is 0. To return NaN, the 0.21 behavior, use min_count=1.

Some background: In pandas 0.21, we fixed a long-standing inconsistency in the return value of all-NA series depending on whether or not bottleneck was installed. See Sum/Prod of all-NaN or empty Series/DataFrames is now consistently NaN. At the same time, we changed the sum and prod of an empty Series to also be NaN.

Based on feedback, we’ve partially reverted those changes.

Arithmetic Operations

The default sum for empty or all-NA Series is now 0.

pandas 0.21.x

In [1]: pd.Series([]).sum()
Out[1]: nan

In [2]: pd.Series([np.nan]).sum()
Out[2]: nan

pandas 0.22.0

In [1]: pd.Series([]).sum()
Out[1]: 0.0

In [2]: pd.Series([np.nan]).sum()
Out[2]: 0.0

The default behavior is the same as pandas 0.20.3 with bottleneck installed. It also matches the behavior of NumPy’s np.nansum on empty and all-NA arrays.

To have the sum of an empty series return NaN (the default behavior of pandas 0.20.3 without bottleneck, or pandas 0.21.x), use the min_count keyword.

In [3]: pd.Series([]).sum(min_count=1)
Out[3]: nan

Thanks to the skipna parameter, the .sum on an all-NA series is conceptually the same as the .sum of an empty one with skipna=True (the default).

In [4]: pd.Series([np.nan]).sum(min_count=1)  # skipna=True by default
Out[4]: nan

The min_count parameter refers to the minimum number of non-null values required for a non-NA sum or product.

Series.prod() has been updated to behave the same as Series.sum(), returning 1 instead.

In [5]: pd.Series([]).prod()
Out[5]: 1.0

In [6]: pd.Series([np.nan]).prod()
Out[6]: 1.0

In [7]: pd.Series([]).prod(min_count=1)
Out[7]: nan

These changes affect DataFrame.sum() and DataFrame.prod() as well. Finally, a few less obvious places in pandas are affected by this change.

Grouping by a Categorical

Grouping by a Categorical and summing now returns 0 instead of NaN for categories with no observations. The product now returns 1 instead of NaN.

pandas 0.21.x

In [8]: grouper = pd.Categorical(['a', 'a'], categories=['a', 'b'])

In [9]: pd.Series([1, 2]).groupby(grouper).sum()
Out[9]:
a    3.0
b    NaN
dtype: float64

pandas 0.22

In [8]: grouper = pd.Categorical(['a', 'a'], categories=['a', 'b'])

In [9]: pd.Series([1, 2]).groupby(grouper).sum()
Out[9]: 
a    3
b    0
dtype: int64

To restore the 0.21 behavior of returning NaN for unobserved groups, use min_count>=1.

In [10]: pd.Series([1, 2]).groupby(grouper).sum(min_count=1)
Out[10]: 
a    3.0
b    NaN
dtype: float64

Resample

The sum and product of all-NA bins has changed from NaN to 0 for sum and 1 for product.

pandas 0.21.x

In [11]: s = pd.Series([1, 1, np.nan, np.nan],
   ...:                index=pd.date_range('2017', periods=4))
   ...:  s
Out[11]:
2017-01-01    1.0
2017-01-02    1.0
2017-01-03    NaN
2017-01-04    NaN
Freq: D, dtype: float64

In [12]: s.resample('2d').sum()
Out[12]:
2017-01-01    2.0
2017-01-03    NaN
Freq: 2D, dtype: float64

pandas 0.22.0

In [11]: s = pd.Series([1, 1, np.nan, np.nan],
   ....:               index=pd.date_range('2017', periods=4))
   ....: 

In [12]: s.resample('2d').sum()
Out[12]: 
2017-01-01    2.0
2017-01-03    0.0
dtype: float64

To restore the 0.21 behavior of returning NaN, use min_count>=1.

In [13]: s.resample('2d').sum(min_count=1)
Out[13]: 
2017-01-01    2.0
2017-01-03    NaN
dtype: float64

In particular, upsampling and taking the sum or product is affected, as upsampling introduces missing values even if the original series was entirely valid.

pandas 0.21.x

In [14]: idx = pd.DatetimeIndex(['2017-01-01', '2017-01-02'])

In [15]: pd.Series([1, 2], index=idx).resample('12H').sum()
Out[15]:
2017-01-01 00:00:00    1.0
2017-01-01 12:00:00    NaN
2017-01-02 00:00:00    2.0
Freq: 12H, dtype: float64

pandas 0.22.0

In [14]: idx = pd.DatetimeIndex(['2017-01-01', '2017-01-02'])

In [15]: pd.Series([1, 2], index=idx).resample("12H").sum()
Out[15]: 
2017-01-01 00:00:00    1
2017-01-01 12:00:00    0
2017-01-02 00:00:00    2
Freq: 12H, dtype: int64

Once again, the min_count keyword is available to restore the 0.21 behavior.

In [16]: pd.Series([1, 2], index=idx).resample("12H").sum(min_count=1)
Out[16]: 
2017-01-01 00:00:00    1.0
2017-01-01 12:00:00    NaN
2017-01-02 00:00:00    2.0
Freq: 12H, dtype: float64

Rolling and Expanding

Rolling and expanding already have a min_periods keyword that behaves similar to min_count. The only case that changes is when doing a rolling or expanding sum with min_periods=0. Previously this returned NaN, when fewer than min_periods non-NA values were in the window. Now it returns 0.

pandas 0.21.1

In [17]: s = pd.Series([np.nan, np.nan])

In [18]: s.rolling(2, min_periods=0).sum()
Out[18]:
0   NaN
1   NaN
dtype: float64

pandas 0.22.0

In [17]: s = pd.Series([np.nan, np.nan])

In [18]: s.rolling(2, min_periods=0).sum()
Out[18]: 
0    0.0
1    0.0
dtype: float64

The default behavior of min_periods=None, implying that min_periods equals the window size, is unchanged.

Compatibility

If you maintain a library that should work across pandas versions, it may be easiest to exclude pandas 0.21 from your requirements. Otherwise, all your sum() calls would need to check if the Series is empty before summing.

With setuptools, in your setup.py use:

install_requires=['pandas!=0.21.*', ...]

With conda, use

requirements:
  run:
    - pandas !=0.21.0,!=0.21.1

Note that the inconsistency in the return value for all-NA series is still there for pandas 0.20.3 and earlier. Avoiding pandas 0.21 will only help with the empty case.

v0.21.1 (December 12, 2017)

This is a minor bug-fix release in the 0.21.x series and includes some small regression fixes, bug fixes and performance improvements. We recommend that all users upgrade to this version.

Highlights include:

  • Temporarily restore matplotlib datetime plotting functionality. This should resolve issues for users who implicitly relied on pandas to plot datetimes with matplotlib. See here.
  • Improvements to the Parquet IO functions introduced in 0.21.0. See here.

Restore Matplotlib datetime Converter Registration

Pandas implements some matplotlib converters for nicely formatting the axis labels on plots with datetime or Period values. Prior to pandas 0.21.0, these were implicitly registered with matplotlib, as a side effect of import pandas.

In pandas 0.21.0, we required users to explicitly register the converter. This caused problems for some users who relied on those converters being present for regular matplotlib.pyplot plotting methods, so we’re temporarily reverting that change; pandas 0.21.1 again registers the converters on import, just like before 0.21.0.

We’ve added a new option to control the converters: pd.options.plotting.matplotlib.register_converters. By default, they are registered. Toggling this to False removes pandas’ formatters and restore any converters we overwrote when registering them (GH18301).

We’re working with the matplotlib developers to make this easier. We’re trying to balance user convenience (automatically registering the converters) with import performance and best practices (importing pandas shouldn’t have the side effect of overwriting any custom converters you’ve already set). In the future we hope to have most of the datetime formatting functionality in matplotlib, with just the pandas-specific converters in pandas. We’ll then gracefully deprecate the automatic registration of converters in favor of users explicitly registering them when they want them.

New features

Improvements to the Parquet IO functionality

Other Enhancements

Deprecations

  • pandas.tseries.register has been renamed to pandas.plotting.register_matplotlib_converters`() (GH18301)

Performance Improvements

  • Improved performance of plotting large series/dataframes (GH18236).

Bug Fixes

Conversion

  • Bug in TimedeltaIndex subtraction could incorrectly overflow when NaT is present (GH17791)
  • Bug in DatetimeIndex subtracting datetimelike from DatetimeIndex could fail to overflow (GH18020)
  • Bug in IntervalIndex.copy() when copying and IntervalIndex with non-default closed (GH18339)
  • Bug in DataFrame.to_dict() where columns of datetime that are tz-aware were not converted to required arrays when used with orient='records', raising``TypeError` (GH18372)
  • Bug in DateTimeIndex and date_range() where mismatching tz-aware start and end timezones would not raise an err if end.tzinfo is None (GH18431)
  • Bug in Series.fillna() which raised when passed a long integer on Python 2 (GH18159).

Indexing

  • Bug in a boolean comparison of a datetime.datetime and a datetime64[ns] dtype Series (GH17965)
  • Bug where a MultiIndex with more than a million records was not raising AttributeError when trying to access a missing attribute (GH18165)
  • Bug in IntervalIndex constructor when a list of intervals is passed with non-default closed (GH18334)
  • Bug in Index.putmask when an invalid mask passed (GH18368)
  • Bug in masked assignment of a timedelta64[ns] dtype Series, incorrectly coerced to float (GH18493)

I/O

  • Bug in class:~pandas.io.stata.StataReader not converting date/time columns with display formatting addressed (GH17990). Previously columns with display formatting were normally left as ordinal numbers and not converted to datetime objects.
  • Bug in read_csv() when reading a compressed UTF-16 encoded file (GH18071)
  • Bug in read_csv() for handling null values in index columns when specifying na_filter=False (GH5239)
  • Bug in read_csv() when reading numeric category fields with high cardinality (GH18186)
  • Bug in DataFrame.to_csv() when the table had MultiIndex columns, and a list of strings was passed in for header (GH5539)
  • Bug in parsing integer datetime-like columns with specified format in read_sql (GH17855).
  • Bug in DataFrame.to_msgpack() when serializing data of the numpy.bool_ datatype (GH18390)
  • Bug in read_json() not decoding when reading line deliminted JSON from S3 (GH17200)
  • Bug in pandas.io.json.json_normalize() to avoid modification of meta (GH18610)
  • Bug in to_latex() where repeated multi-index values were not printed even though a higher level index differed from the previous row (GH14484)
  • Bug when reading NaN-only categorical columns in HDFStore (GH18413)
  • Bug in DataFrame.to_latex() with longtable=True where a latex multicolumn always spanned over three columns (GH17959)

Plotting

  • Bug in DataFrame.plot() and Series.plot() with DatetimeIndex where a figure generated by them is not pickleable in Python 3 (GH18439)

Groupby/Resample/Rolling

  • Bug in DataFrame.resample(...).apply(...) when there is a callable that returns different columns (GH15169)
  • Bug in DataFrame.resample(...) when there is a time change (DST) and resampling frequecy is 12h or higher (GH15549)
  • Bug in pd.DataFrameGroupBy.count() when counting over a datetimelike column (GH13393)
  • Bug in rolling.var where calculation is inaccurate with a zero-valued array (GH18430)

Reshaping

  • Error message in pd.merge_asof() for key datatype mismatch now includes datatype of left and right key (GH18068)
  • Bug in pd.concat when empty and non-empty DataFrames or Series are concatenated (GH18178 GH18187)
  • Bug in DataFrame.filter(...) when unicode is passed as a condition in Python 2 (GH13101)
  • Bug when merging empty DataFrames when np.seterr(divide='raise') is set (GH17776)

Numeric

  • Bug in pd.Series.rolling.skew() and rolling.kurt() with all equal values has floating issue (GH18044)
  • Bug in TimedeltaIndex subtraction could incorrectly overflow when NaT is present (GH17791)
  • Bug in DatetimeIndex subtracting datetimelike from DatetimeIndex could fail to overflow (GH18020)

Categorical

  • Bug in DataFrame.astype() where casting to ‘category’ on an empty DataFrame causes a segmentation fault (GH18004)
  • Error messages in the testing module have been improved when items have different CategoricalDtype (GH18069)
  • CategoricalIndex can now correctly take a pd.api.types.CategoricalDtype as its dtype (GH18116)
  • Bug in Categorical.unique() returning read-only codes array when all categories were NaN (GH18051)
  • Bug in DataFrame.groupby(axis=1) with a CategoricalIndex (GH18432)

String

v0.21.0 (October 27, 2017)

This is a major release from 0.20.3 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:

  • Integration with Apache Parquet, including a new top-level read_parquet() function and DataFrame.to_parquet() method, see here.
  • New user-facing pandas.api.types.CategoricalDtype for specifying categoricals independent of the data, see here.
  • The behavior of sum and prod on all-NaN Series/DataFrames is now consistent and no longer depends on whether bottleneck is installed, and sum and prod on empty Series now return NaN instead of 0, see here.
  • Compatibility fixes for pypy, see here.
  • Additions to the drop, reindex and rename API to make them more consistent, see here.
  • Addition of the new methods DataFrame.infer_objects (see here) and GroupBy.pipe (see here).
  • Indexing with a list of labels, where one or more of the labels is missing, is deprecated and will raise a KeyError in a future version, see here.

Check the API Changes and deprecations before updating.

New features

Integration with Apache Parquet file format

Integration with Apache Parquet, including a new top-level read_parquet() and DataFrame.to_parquet() method, see here (GH15838, GH17438).

Apache Parquet provides a cross-language, binary file format for reading and writing data frames efficiently. Parquet is designed to faithfully serialize and de-serialize DataFrame s, supporting all of the pandas dtypes, including extension dtypes such as datetime with timezones.

This functionality depends on either the pyarrow or fastparquet library. For more details, see see the IO docs on Parquet.

infer_objects type conversion

The DataFrame.infer_objects() and Series.infer_objects() methods have been added to perform dtype inference on object columns, replacing some of the functionality of the deprecated convert_objects method. See the documentation here for more details. (GH11221)

This method only performs soft conversions on object columns, converting Python objects to native types, but not any coercive conversions. For example:

In [1]: df = pd.DataFrame({'A': [1, 2, 3],
   ...:                    'B': np.array([1, 2, 3], dtype='object'),
   ...:                    'C': ['1', '2', '3']})
   ...: 

In [2]: df.dtypes
Out[2]: 
A     int64
B    object
C    object
dtype: object

In [3]: df.infer_objects().dtypes
Out[3]: 
A     int64
B     int64
C    object
dtype: object

Note that column 'C' was not converted - only scalar numeric types will be converted to a new type. Other types of conversion should be accomplished using the to_numeric() function (or to_datetime(), to_timedelta()).

In [4]: df = df.infer_objects()

In [5]: df['C'] = pd.to_numeric(df['C'], errors='coerce')

In [6]: df.dtypes
Out[6]: 
A    int64
B    int64
C    int64
dtype: object

Improved warnings when attempting to create columns

New users are often puzzled by the relationship between column operations and attribute access on DataFrame instances (GH7175). One specific instance of this confusion is attempting to create a new column by setting an attribute on the DataFrame:

In[1]: df = pd.DataFrame({'one': [1., 2., 3.]})
In[2]: df.two = [4, 5, 6]

This does not raise any obvious exceptions, but also does not create a new column:

In[3]: df
Out[3]:
    one
0  1.0
1  2.0
2  3.0

Setting a list-like data structure into a new attribute now raises a UserWarning about the potential for unexpected behavior. See Attribute Access.

drop now also accepts index/columns keywords

The drop() method has gained index/columns keywords as an alternative to specifying the axis. This is similar to the behavior of reindex (GH12392).

For example:

In [7]: df = pd.DataFrame(np.arange(8).reshape(2,4),
   ...:                   columns=['A', 'B', 'C', 'D'])
   ...: 

In [8]: df
Out[8]: 
   A  B  C  D
0  0  1  2  3
1  4  5  6  7

In [9]: df.drop(['B', 'C'], axis=1)
Out[9]: 
   A  D
0  0  3
1  4  7

# the following is now equivalent
In [10]: df.drop(columns=['B', 'C'])
Out[10]: 
   A  D
0  0  3
1  4  7

rename, reindex now also accept axis keyword

The DataFrame.rename() and DataFrame.reindex() methods have gained the axis keyword to specify the axis to target with the operation (GH12392).

Here’s rename:

In [11]: df = pd.DataFrame({"A": [1, 2, 3], "B": [4, 5, 6]})

In [12]: df.rename(str.lower, axis='columns')
Out[12]: 
   a  b
0  1  4
1  2  5
2  3  6

In [13]: df.rename(id, axis='index')
Out[13]: 
            A  B
4305697456  1  4
4305697488  2  5
4305697520  3  6

And reindex:

In [14]: df.reindex(['A', 'B', 'C'], axis='columns')
Out[14]: 
   A  B   C
0  1  4 NaN
1  2  5 NaN
2  3  6 NaN

In [15]: df.reindex([0, 1, 3], axis='index')
Out[15]: 
     A    B
0  1.0  4.0
1  2.0  5.0
3  NaN  NaN

The “index, columns” style continues to work as before.

In [16]: df.rename(index=id, columns=str.lower)
Out[16]: 
            a  b
4305697456  1  4
4305697488  2  5
4305697520  3  6

In [17]: df.reindex(index=[0, 1, 3], columns=['A', 'B', 'C'])
Out[17]: 
     A    B   C
0  1.0  4.0 NaN
1  2.0  5.0 NaN
3  NaN  NaN NaN

We highly encourage using named arguments to avoid confusion when using either style.

CategoricalDtype for specifying categoricals

pandas.api.types.CategoricalDtype has been added to the public API and expanded to include the categories and ordered attributes. A CategoricalDtype can be used to specify the set of categories and orderedness of an array, independent of the data. This can be useful for example, when converting string data to a Categorical (GH14711, GH15078, GH16015, GH17643):

In [18]: from pandas.api.types import CategoricalDtype

In [19]: s = pd.Series(['a', 'b', 'c', 'a'])  # strings

In [20]: dtype = CategoricalDtype(categories=['a', 'b', 'c', 'd'], ordered=True)

In [21]: s.astype(dtype)
Out[21]: 
0    a
1    b
2    c
3    a
dtype: category
Categories (4, object): [a < b < c < d]

One place that deserves special mention is in read_csv(). Previously, with dtype={'col': 'category'}, the returned values and categories would always be strings.

In [22]: data = 'A,B\na,1\nb,2\nc,3'

In [23]: pd.read_csv(StringIO(data), dtype={'B': 'category'}).B.cat.categories
Out[23]: Index(['1', '2', '3'], dtype='object')

Notice the “object” dtype.

With a CategoricalDtype of all numerics, datetimes, or timedeltas, we can automatically convert to the correct type

In [24]: dtype = {'B': CategoricalDtype([1, 2, 3])}

In [25]: pd.read_csv(StringIO(data), dtype=dtype).B.cat.categories
Out[25]: Int64Index([1, 2, 3], dtype='int64')

The values have been correctly interpreted as integers.

The .dtype property of a Categorical, CategoricalIndex or a Series with categorical type will now return an instance of CategoricalDtype. While the repr has changed, str(CategoricalDtype()) is still the string 'category'. We’ll take this moment to remind users that the preferred way to detect categorical data is to use pandas.api.types.is_categorical_dtype(), and not str(dtype) == 'category'.

See the CategoricalDtype docs for more.

GroupBy objects now have a pipe method

GroupBy objects now have a pipe method, similar to the one on DataFrame and Series, that allow for functions that take a GroupBy to be composed in a clean, readable syntax. (GH17871)

For a concrete example on combining .groupby and .pipe , imagine having a DataFrame with columns for stores, products, revenue and sold quantity. We’d like to do a groupwise calculation of prices (i.e. revenue/quantity) per store and per product. We could do this in a multi-step operation, but expressing it in terms of piping can make the code more readable.

First we set the data:

In [26]: import numpy as np

In [27]: n = 1000

In [28]: df = pd.DataFrame({'Store': np.random.choice(['Store_1', 'Store_2'], n),
   ....:                    'Product': np.random.choice(['Product_1', 'Product_2', 'Product_3'], n),
   ....:                    'Revenue': (np.random.random(n)*50+10).round(2),
   ....:                    'Quantity': np.random.randint(1, 10, size=n)})
   ....: 

In [29]: df.head(2)
Out[29]: 
     Product  Quantity  Revenue    Store
0  Product_3         1    14.23  Store_2
1  Product_2         8    46.07  Store_1

Now, to find prices per store/product, we can simply do:

In [30]: (df.groupby(['Store', 'Product'])
   ....:    .pipe(lambda grp: grp.Revenue.sum()/grp.Quantity.sum())
   ....:    .unstack().round(2))
   ....: 
Out[30]: 
Product  Product_1  Product_2  Product_3
Store                                   
Store_1       7.26       7.00       7.22
Store_2       7.10       6.35       7.45

See the documentation for more.

Categorical.rename_categories accepts a dict-like

rename_categories() now accepts a dict-like argument for new_categories. The previous categories are looked up in the dictionary’s keys and replaced if found. The behavior of missing and extra keys is the same as in DataFrame.rename().

In [31]: c = pd.Categorical(['a', 'a', 'b'])

In [32]: c.rename_categories({"a": "eh", "b": "bee"})
Out[32]: 
[eh, eh, bee]
Categories (2, object): [eh, bee]

Warning

To assist with upgrading pandas, rename_categories treats Series as list-like. Typically, Series are considered to be dict-like (e.g. in .rename, .map). In a future version of pandas rename_categories will change to treat them as dict-like. Follow the warning message’s recommendations for writing future-proof code.

In [33]: c.rename_categories(pd.Series([0, 1], index=['a', 'c']))
FutureWarning: Treating Series 'new_categories' as a list-like and using the values.
In a future version, 'rename_categories' will treat Series like a dictionary.
For dict-like, use 'new_categories.to_dict()'
For list-like, use 'new_categories.values'.
Out[33]:
[0, 0, 1]
Categories (2, int64): [0, 1]

Other Enhancements

New functions or methods
New keywords
Various enhancements

Backwards incompatible API changes

Dependencies have increased minimum versions

We have updated our minimum supported versions of dependencies (GH15206, GH15543, GH15214). If installed, we now require:

Package Minimum Version Required
Numpy 1.9.0 X
Matplotlib 1.4.3  
Scipy 0.14.0  
Bottleneck 1.0.0  

Additionally, support has been dropped for Python 3.4 (GH15251).

Sum/Prod of all-NaN or empty Series/DataFrames is now consistently NaN

Note

The changes described here have been partially reverted. See the v0.22.0 Whatsnew for more.

The behavior of sum and prod on all-NaN Series/DataFrames no longer depends on whether bottleneck is installed, and return value of sum and prod on an empty Series has changed (GH9422, GH15507).

Calling sum or prod on an empty or all-NaN Series, or columns of a DataFrame, will result in NaN. See the docs.

In [33]: s = Series([np.nan])

Previously WITHOUT bottleneck installed:

In [2]: s.sum()
Out[2]: np.nan

Previously WITH bottleneck:

In [2]: s.sum()
Out[2]: 0.0

New Behavior, without regard to the bottleneck installation:

In [34]: s.sum()
Out[34]: 0.0

Note that this also changes the sum of an empty Series. Previously this always returned 0 regardless of a bottlenck installation:

In [1]: pd.Series([]).sum()
Out[1]: 0

but for consistency with the all-NaN case, this was changed to return NaN as well:

In [35]: pd.Series([]).sum()
Out[35]: 0.0

Indexing with a list with missing labels is Deprecated

Previously, selecting with a list of labels, where one or more labels were missing would always succeed, returning NaN for missing labels. This will now show a FutureWarning. In the future this will raise a KeyError (GH15747). This warning will trigger on a DataFrame or a Series for using .loc[] or [[]] when passing a list-of-labels with at least 1 missing label. See the deprecation docs.

In [36]: s = pd.Series([1, 2, 3])

In [37]: s
Out[37]: 
0    1
1    2
2    3
dtype: int64

Previous Behavior

In [4]: s.loc[[1, 2, 3]]
Out[4]:
1    2.0
2    3.0
3    NaN
dtype: float64

Current Behavior

In [4]: s.loc[[1, 2, 3]]
Passing list-likes to .loc or [] with any missing label will raise
KeyError in the future, you can use .reindex() as an alternative.

See the documentation here:
http://pandas.pydata.org/pandas-docs/stable/indexing.html#deprecate-loc-reindex-listlike

Out[4]:
1    2.0
2    3.0
3    NaN
dtype: float64

The idiomatic way to achieve selecting potentially not-found elements is via .reindex()

In [38]: s.reindex([1, 2, 3])
Out[38]: 
1    2.0
2    3.0
3    NaN
dtype: float64

Selection with all keys found is unchanged.

In [39]: s.loc[[1, 2]]
Out[39]: 
1    2
2    3
dtype: int64

NA naming Changes

In order to promote more consistency among the pandas API, we have added additional top-level functions isna() and notna() that are aliases for isnull() and notnull(). The naming scheme is now more consistent with methods like .dropna() and .fillna(). Furthermore in all cases where .isnull() and .notnull() methods are defined, these have additional methods named .isna() and .notna(), these are included for classes Categorical, Index, Series, and DataFrame. (GH15001).

The configuration option pd.options.mode.use_inf_as_null is deprecated, and pd.options.mode.use_inf_as_na is added as a replacement.

Iteration of Series/Index will now return Python scalars

Previously, when using certain iteration methods for a Series with dtype int or float, you would receive a numpy scalar, e.g. a np.int64, rather than a Python int. Issue (GH10904) corrected this for Series.tolist() and list(Series). This change makes all iteration methods consistent, in particular, for __iter__() and .map(); note that this only affects int/float dtypes. (GH13236, GH13258, GH14216).

In [40]: s = pd.Series([1, 2, 3])

In [41]: s
Out[41]: 
0    1
1    2
2    3
dtype: int64

Previously:

In [2]: type(list(s)[0])
Out[2]: numpy.int64

New Behaviour:

In [42]: type(list(s)[0])
Out[42]: int

Furthermore this will now correctly box the results of iteration for DataFrame.to_dict() as well.

In [43]: d = {'a':[1], 'b':['b']}

In [44]: df = pd.DataFrame(d)

Previously:

In [8]: type(df.to_dict()['a'][0])
Out[8]: numpy.int64

New Behaviour:

In [45]: type(df.to_dict()['a'][0])
Out[45]: int

Indexing with a Boolean Index

Previously when passing a boolean Index to .loc, if the index of the Series/DataFrame had boolean labels, you would get a label based selection, potentially duplicating result labels, rather than a boolean indexing selection (where True selects elements), this was inconsistent how a boolean numpy array indexed. The new behavior is to act like a boolean numpy array indexer. (GH17738)

Previous Behavior:

In [46]: s = pd.Series([1, 2, 3], index=[False, True, False])

In [47]: s
Out[47]: 
False    1
True     2
False    3
dtype: int64
In [59]: s.loc[pd.Index([True, False, True])]
Out[59]:
True     2
False    1
False    3
True     2
dtype: int64

Current Behavior

In [48]: s.loc[pd.Index([True, False, True])]
Out[48]: 
False    1
False    3
dtype: int64

Furthermore, previously if you had an index that was non-numeric (e.g. strings), then a boolean Index would raise a KeyError. This will now be treated as a boolean indexer.

Previously Behavior:

In [49]: s = pd.Series([1,2,3], index=['a', 'b', 'c'])

In [50]: s
Out[50]: 
a    1
b    2
c    3
dtype: int64
In [39]: s.loc[pd.Index([True, False, True])]
KeyError: "None of [Index([True, False, True], dtype='object')] are in the [index]"

Current Behavior

In [51]: s.loc[pd.Index([True, False, True])]
Out[51]: 
a    1
c    3
dtype: int64

PeriodIndex resampling

In previous versions of pandas, resampling a Series/DataFrame indexed by a PeriodIndex returned a DatetimeIndex in some cases (GH12884). Resampling to a multiplied frequency now returns a PeriodIndex (GH15944). As a minor enhancement, resampling a PeriodIndex can now handle NaT values (GH13224)

Previous Behavior:

In [1]: pi = pd.period_range('2017-01', periods=12, freq='M')

In [2]: s = pd.Series(np.arange(12), index=pi)

In [3]: resampled = s.resample('2Q').mean()

In [4]: resampled
Out[4]:
2017-03-31     1.0
2017-09-30     5.5
2018-03-31    10.0
Freq: 2Q-DEC, dtype: float64

In [5]: resampled.index
Out[5]: DatetimeIndex(['2017-03-31', '2017-09-30', '2018-03-31'], dtype='datetime64[ns]', freq='2Q-DEC')

New Behavior:

In [52]: pi = pd.period_range('2017-01', periods=12, freq='M')

In [53]: s = pd.Series(np.arange(12), index=pi)

In [54]: resampled = s.resample('2Q').mean()

In [55]: resampled
Out[55]: 
2017Q1    2.5
2017Q3    8.5
Freq: 2Q-DEC, dtype: float64

In [56]: resampled.index
Out[56]: PeriodIndex(['2017Q1', '2017Q3'], dtype='period[2Q-DEC]', freq='2Q-DEC')

Upsampling and calling .ohlc() previously returned a Series, basically identical to calling .asfreq(). OHLC upsampling now returns a DataFrame with columns open, high, low and close (GH13083). This is consistent with downsampling and DatetimeIndex behavior.

Previous Behavior:

In [1]: pi = pd.PeriodIndex(start='2000-01-01', freq='D', periods=10)

In [2]: s = pd.Series(np.arange(10), index=pi)

In [3]: s.resample('H').ohlc()
Out[3]:
2000-01-01 00:00    0.0
                ...
2000-01-10 23:00    NaN
Freq: H, Length: 240, dtype: float64

In [4]: s.resample('M').ohlc()
Out[4]:
         open  high  low  close
2000-01     0     9    0      9

New Behavior:

In [57]: pi = pd.PeriodIndex(start='2000-01-01', freq='D', periods=10)

In [58]: s = pd.Series(np.arange(10), index=pi)

In [59]: s.resample('H').ohlc()
Out[59]: 
                  open  high  low  close
2000-01-01 00:00   0.0   0.0  0.0    0.0
2000-01-01 01:00   NaN   NaN  NaN    NaN
2000-01-01 02:00   NaN   NaN  NaN    NaN
2000-01-01 03:00   NaN   NaN  NaN    NaN
2000-01-01 04:00   NaN   NaN  NaN    NaN
2000-01-01 05:00   NaN   NaN  NaN    NaN
2000-01-01 06:00   NaN   NaN  NaN    NaN
...                ...   ...  ...    ...
2000-01-10 17:00   NaN   NaN  NaN    NaN
2000-01-10 18:00   NaN   NaN  NaN    NaN
2000-01-10 19:00   NaN   NaN  NaN    NaN
2000-01-10 20:00   NaN   NaN  NaN    NaN
2000-01-10 21:00   NaN   NaN  NaN    NaN
2000-01-10 22:00   NaN   NaN  NaN    NaN
2000-01-10 23:00   NaN   NaN  NaN    NaN

[240 rows x 4 columns]

In [60]: s.resample('M').ohlc()
Out[60]: 
         open  high  low  close
2000-01     0     9    0      9

Improved error handling during item assignment in pd.eval

eval() will now raise a ValueError when item assignment malfunctions, or inplace operations are specified, but there is no item assignment in the expression (GH16732)

In [61]: arr = np.array([1, 2, 3])

Previously, if you attempted the following expression, you would get a not very helpful error message:

In [3]: pd.eval("a = 1 + 2", target=arr, inplace=True)
...
IndexError: only integers, slices (`:`), ellipsis (`...`), numpy.newaxis (`None`)
and integer or boolean arrays are valid indices

This is a very long way of saying numpy arrays don’t support string-item indexing. With this change, the error message is now this:

In [3]: pd.eval("a = 1 + 2", target=arr, inplace=True)
...
ValueError: Cannot assign expression output to target

It also used to be possible to evaluate expressions inplace, even if there was no item assignment:

In [4]: pd.eval("1 + 2", target=arr, inplace=True)
Out[4]: 3

However, this input does not make much sense because the output is not being assigned to the target. Now, a ValueError will be raised when such an input is passed in:

In [4]: pd.eval("1 + 2", target=arr, inplace=True)
...
ValueError: Cannot operate inplace if there is no assignment

Dtype Conversions

Previously assignments, .where() and .fillna() with a bool assignment, would coerce to same the type (e.g. int / float), or raise for datetimelikes. These will now preserve the bools with object dtypes. (GH16821).

In [62]: s = Series([1, 2, 3])
In [5]: s[1] = True

In [6]: s
Out[6]:
0    1
1    1
2    3
dtype: int64

New Behavior

In [63]: s[1] = True

In [64]: s
Out[64]: 
0       1
1    True
2       3
dtype: object

Previously, as assignment to a datetimelike with a non-datetimelike would coerce the non-datetime-like item being assigned (GH14145).

In [65]: s = pd.Series([pd.Timestamp('2011-01-01'), pd.Timestamp('2012-01-01')])
In [1]: s[1] = 1

In [2]: s
Out[2]:
0   2011-01-01 00:00:00.000000000
1   1970-01-01 00:00:00.000000001
dtype: datetime64[ns]

These now coerce to object dtype.

In [66]: s[1] = 1

In [67]: s
Out[67]: 
0    2011-01-01 00:00:00
1                      1
dtype: object
  • Inconsistent behavior in .where() with datetimelikes which would raise rather than coerce to object (GH16402)
  • Bug in assignment against int64 data with np.ndarray with float64 dtype may keep int64 dtype (GH14001)

MultiIndex Constructor with a Single Level

The MultiIndex constructors no longer squeezes a MultiIndex with all length-one levels down to a regular Index. This affects all the MultiIndex constructors. (GH17178)

Previous behavior:

In [2]: pd.MultiIndex.from_tuples([('a',), ('b',)])
Out[2]: Index(['a', 'b'], dtype='object')

Length 1 levels are no longer special-cased. They behave exactly as if you had length 2+ levels, so a MultiIndex is always returned from all of the MultiIndex constructors:

In [68]: pd.MultiIndex.from_tuples([('a',), ('b',)])
Out[68]: 
MultiIndex(levels=[['a', 'b']],
           labels=[[0, 1]])

UTC Localization with Series

Previously, to_datetime() did not localize datetime Series data when utc=True was passed. Now, to_datetime() will correctly localize Series with a datetime64[ns, UTC] dtype to be consistent with how list-like and Index data are handled. (GH6415).

Previous Behavior

In [69]: s = Series(['20130101 00:00:00'] * 3)
In [12]: pd.to_datetime(s, utc=True)
Out[12]:
0   2013-01-01
1   2013-01-01
2   2013-01-01
dtype: datetime64[ns]

New Behavior

In [70]: pd.to_datetime(s, utc=True)
Out[70]: 
0   2013-01-01 00:00:00+00:00
1   2013-01-01 00:00:00+00:00
2   2013-01-01 00:00:00+00:00
dtype: datetime64[ns, UTC]

Additionally, DataFrames with datetime columns that were parsed by read_sql_table() and read_sql_query() will also be localized to UTC only if the original SQL columns were timezone aware datetime columns.

Consistency of Range Functions

In previous versions, there were some inconsistencies between the various range functions: date_range(), bdate_range(), period_range(), timedelta_range(), and interval_range(). (GH17471).

One of the inconsistent behaviors occurred when the start, end and period parameters were all specified, potentially leading to ambiguous ranges. When all three parameters were passed, interval_range ignored the period parameter, period_range ignored the end parameter, and the other range functions raised. To promote consistency among the range functions, and avoid potentially ambiguous ranges, interval_range and period_range will now raise when all three parameters are passed.

Previous Behavior:

In [2]: pd.interval_range(start=0, end=4, periods=6)
Out[2]:
IntervalIndex([(0, 1], (1, 2], (2, 3]]
              closed='right',
              dtype='interval[int64]')

In [3]: pd.period_range(start='2017Q1', end='2017Q4', periods=6, freq='Q')
Out[3]: PeriodIndex(['2017Q1', '2017Q2', '2017Q3', '2017Q4', '2018Q1', '2018Q2'], dtype='period[Q-DEC]', freq='Q-DEC')

New Behavior:

In [2]: pd.interval_range(start=0, end=4, periods=6)
---------------------------------------------------------------------------
ValueError: Of the three parameters: start, end, and periods, exactly two must be specified

In [3]: pd.period_range(start='2017Q1', end='2017Q4', periods=6, freq='Q')
---------------------------------------------------------------------------
ValueError: Of the three parameters: start, end, and periods, exactly two must be specified

Additionally, the endpoint parameter end was not included in the intervals produced by interval_range. However, all other range functions include end in their output. To promote consistency among the range functions, interval_range will now include end as the right endpoint of the final interval, except if freq is specified in a way which skips end.

Previous Behavior:

In [4]: pd.interval_range(start=0, end=4)
Out[4]:
IntervalIndex([(0, 1], (1, 2], (2, 3]]
              closed='right',
              dtype='interval[int64]')

New Behavior:

In [71]: pd.interval_range(start=0, end=4)
Out[71]: 
IntervalIndex([(0, 1], (1, 2], (2, 3], (3, 4]]
              closed='right',
              dtype='interval[int64]')

No Automatic Matplotlib Converters

Pandas no longer registers our date, time, datetime, datetime64, and Period converters with matplotlib when pandas is imported. Matplotlib plot methods (plt.plot, ax.plot, ...), will not nicely format the x-axis for DatetimeIndex or PeriodIndex values. You must explicitly register these methods:

In [72]: from pandas.tseries import converter

In [73]: converter.register()

In [74]: fig, ax = plt.subplots()

In [75]: plt.plot(pd.date_range('2017', periods=6), range(6))
Out[75]: [<matplotlib.lines.Line2D at 0x12e329a58>]

Pandas built-in Series.plot and DataFrame.plot will register these converters on first-use (:issue:17710).

Other API Changes

  • The Categorical constructor no longer accepts a scalar for the categories keyword. (GH16022)
  • Accessing a non-existent attribute on a closed HDFStore will now raise an AttributeError rather than a ClosedFileError (GH16301)
  • read_csv() now issues a UserWarning if the names parameter contains duplicates (GH17095)
  • read_csv() now treats 'null' and 'n/a' strings as missing values by default (GH16471, GH16078)
  • pandas.HDFStore‘s string representation is now faster and less detailed. For the previous behavior, use pandas.HDFStore.info(). (GH16503).
  • Compression defaults in HDF stores now follow pytables standards. Default is no compression and if complib is missing and complevel > 0 zlib is used (GH15943)
  • Index.get_indexer_non_unique() now returns a ndarray indexer rather than an Index; this is consistent with Index.get_indexer() (GH16819)
  • Removed the @slow decorator from pandas.util.testing, which caused issues for some downstream packages’ test suites. Use @pytest.mark.slow instead, which achieves the same thing (GH16850)
  • Moved definition of MergeError to the pandas.errors module.
  • The signature of Series.set_axis() and DataFrame.set_axis() has been changed from set_axis(axis, labels) to set_axis(labels, axis=0), for consistency with the rest of the API. The old signature is deprecated and will show a FutureWarning (GH14636)
  • Series.argmin() and Series.argmax() will now raise a TypeError when used with object dtypes, instead of a ValueError (GH13595)
  • Period is now immutable, and will now raise an AttributeError when a user tries to assign a new value to the ordinal or freq attributes (GH17116).
  • to_datetime() when passed a tz-aware origin= kwarg will now raise a more informative ValueError rather than a TypeError (GH16842)
  • to_datetime() now raises a ValueError when format includes %W or %U without also including day of the week and calendar year (GH16774)
  • Renamed non-functional index to index_col in read_stata() to improve API consistency (GH16342)
  • Bug in DataFrame.drop() caused boolean labels False and True to be treated as labels 0 and 1 respectively when dropping indices from a numeric index. This will now raise a ValueError (GH16877)
  • Restricted DateOffset keyword arguments. Previously, DateOffset subclasses allowed arbitrary keyword arguments which could lead to unexpected behavior. Now, only valid arguments will be accepted. (GH17176).

Deprecations

Series.select and DataFrame.select

The Series.select() and DataFrame.select() methods are deprecated in favor of using df.loc[labels.map(crit)] (GH12401)

In [76]: df = DataFrame({'A': [1, 2, 3]}, index=['foo', 'bar', 'baz'])
In [3]: df.select(lambda x: x in ['bar', 'baz'])
FutureWarning: select is deprecated and will be removed in a future release. You can use .loc[crit] as a replacement
Out[3]:
     A
bar  2
baz  3
In [77]: df.loc[df.index.map(lambda x: x in ['bar', 'baz'])]
Out[77]: 
     A
bar  2
baz  3

Series.argmax and Series.argmin

The behavior of Series.argmax() and Series.argmin() have been deprecated in favor of Series.idxmax() and Series.idxmin(), respectively (GH16830).

For compatibility with NumPy arrays, pd.Series implements argmax and argmin. Since pandas 0.13.0, argmax has been an alias for pandas.Series.idxmax(), and argmin has been an alias for pandas.Series.idxmin(). They return the label of the maximum or minimum, rather than the position.

We’ve deprecated the current behavior of Series.argmax and Series.argmin. Using either of these will emit a FutureWarning. Use Series.idxmax() if you want the label of the maximum. Use Series.values.argmax() if you want the position of the maximum. Likewise for the minimum. In a future release Series.argmax and Series.argmin will return the position of the maximum or minimum.

Removal of prior version deprecations/changes

  • read_excel() has dropped the has_index_names parameter (GH10967)
  • The pd.options.display.height configuration has been dropped (GH3663)
  • The pd.options.display.line_width configuration has been dropped (GH2881)
  • The pd.options.display.mpl_style configuration has been dropped (GH12190)
  • Index has dropped the .sym_diff() method in favor of .symmetric_difference() (GH12591)
  • Categorical has dropped the .order() and .sort() methods in favor of .sort_values() (GH12882)
  • eval() and DataFrame.eval() have changed the default of inplace from None to False (GH11149)
  • The function get_offset_name has been dropped in favor of the .freqstr attribute for an offset (GH11834)
  • pandas no longer tests for compatibility with hdf5-files created with pandas < 0.11 (GH17404).

Performance Improvements

  • Improved performance of instantiating SparseDataFrame (GH16773)
  • Series.dt no longer performs frequency inference, yielding a large speedup when accessing the attribute (GH17210)
  • Improved performance of set_categories() by not materializing the values (GH17508)
  • Timestamp.microsecond no longer re-computes on attribute access (GH17331)
  • Improved performance of the CategoricalIndex for data that is already categorical dtype (GH17513)
  • Improved performance of RangeIndex.min() and RangeIndex.max() by using RangeIndex properties to perform the computations (GH17607)

Documentation Changes

  • Several NaT method docstrings (e.g. NaT.ctime()) were incorrect (GH17327)
  • The documentation has had references to versions < v0.17 removed and cleaned up (GH17442, GH17442, GH17404 & GH17504)

Bug Fixes

Conversion

  • Bug in assignment against datetime-like data with int may incorrectly convert to datetime-like (GH14145)
  • Bug in assignment against int64 data with np.ndarray with float64 dtype may keep int64 dtype (GH14001)
  • Fixed the return type of IntervalIndex.is_non_overlapping_monotonic to be a Python bool for consistency with similar attributes/methods. Previously returned a numpy.bool_. (GH17237)
  • Bug in IntervalIndex.is_non_overlapping_monotonic when intervals are closed on both sides and overlap at a point (GH16560)
  • Bug in Series.fillna() returns frame when inplace=True and value is dict (GH16156)
  • Bug in Timestamp.weekday_name returning a UTC-based weekday name when localized to a timezone (GH17354)
  • Bug in Timestamp.replace when replacing tzinfo around DST changes (GH15683)
  • Bug in Timedelta construction and arithmetic that would not propagate the Overflow exception (GH17367)
  • Bug in astype() converting to object dtype when passed extension type classes (DatetimeTZDtype`, CategoricalDtype) rather than instances. Now a TypeError is raised when a class is passed (GH17780).
  • Bug in to_numeric() in which elements were not always being coerced to numeric when errors='coerce' (GH17007, GH17125)
  • Bug in DataFrame and Series constructors where range objects are converted to int32 dtype on Windows instead of int64 (GH16804)

Indexing

  • When called with a null slice (e.g. df.iloc[:]), the .iloc and .loc indexers return a shallow copy of the original object. Previously they returned the original object. (GH13873).
  • When called on an unsorted MultiIndex, the loc indexer now will raise UnsortedIndexError only if proper slicing is used on non-sorted levels (GH16734).
  • Fixes regression in 0.20.3 when indexing with a string on a TimedeltaIndex (GH16896).
  • Fixed TimedeltaIndex.get_loc() handling of np.timedelta64 inputs (GH16909).
  • Fix MultiIndex.sort_index() ordering when ascending argument is a list, but not all levels are specified, or are in a different order (GH16934).
  • Fixes bug where indexing with np.inf caused an OverflowError to be raised (GH16957)
  • Bug in reindexing on an empty CategoricalIndex (GH16770)
  • Fixes DataFrame.loc for setting with alignment and tz-aware DatetimeIndex (GH16889)
  • Avoids IndexError when passing an Index or Series to .iloc with older numpy (GH17193)
  • Allow unicode empty strings as placeholders in multilevel columns in Python 2 (GH17099)
  • Bug in .iloc when used with inplace addition or assignment and an int indexer on a MultiIndex causing the wrong indexes to be read from and written to (GH17148)
  • Bug in .isin() in which checking membership in empty Series objects raised an error (GH16991)
  • Bug in CategoricalIndex reindexing in which specified indices containing duplicates were not being respected (GH17323)
  • Bug in intersection of RangeIndex with negative step (GH17296)
  • Bug in IntervalIndex where performing a scalar lookup fails for included right endpoints of non-overlapping monotonic decreasing indexes (GH16417, GH17271)
  • Bug in DataFrame.first_valid_index() and DataFrame.last_valid_index() when no valid entry (GH17400)
  • Bug in Series.rename() when called with a callable, incorrectly alters the name of the Series, rather than the name of the Index. (GH17407)
  • Bug in String.str_get() raises IndexError instead of inserting NaNs when using a negative index. (GH17704)

I/O

  • Bug in read_hdf() when reading a timezone aware index from fixed format HDFStore (GH17618)
  • Bug in read_csv() in which columns were not being thoroughly de-duplicated (GH17060)
  • Bug in read_csv() in which specified column names were not being thoroughly de-duplicated (GH17095)
  • Bug in read_csv() in which non integer values for the header argument generated an unhelpful / unrelated error message (GH16338)
  • Bug in read_csv() in which memory management issues in exception handling, under certain conditions, would cause the interpreter to segfault (GH14696, GH16798).
  • Bug in read_csv() when called with low_memory=False in which a CSV with at least one column > 2GB in size would incorrectly raise a MemoryError (GH16798).
  • Bug in read_csv() when called with a single-element list header would return a DataFrame of all NaN values (GH7757)
  • Bug in DataFrame.to_csv() defaulting to ‘ascii’ encoding in Python 3, instead of ‘utf-8’ (GH17097)
  • Bug in read_stata() where value labels could not be read when using an iterator (GH16923)
  • Bug in read_stata() where the index was not set (GH16342)
  • Bug in read_html() where import check fails when run in multiple threads (GH16928)
  • Bug in read_csv() where automatic delimiter detection caused a TypeError to be thrown when a bad line was encountered rather than the correct error message (GH13374)
  • Bug in DataFrame.to_html() with notebook=True where DataFrames with named indices or non-MultiIndex indices had undesired horizontal or vertical alignment for column or row labels, respectively (GH16792)
  • Bug in DataFrame.to_html() in which there was no validation of the justify parameter (GH17527)
  • Bug in HDFStore.select() when reading a contiguous mixed-data table featuring VLArray (GH17021)
  • Bug in to_json() where several conditions (including objects with unprintable symbols, objects with deep recursion, overlong labels) caused segfaults instead of raising the appropriate exception (GH14256)

Plotting

  • Bug in plotting methods using secondary_y and fontsize not setting secondary axis font size (GH12565)
  • Bug when plotting timedelta and datetime dtypes on y-axis (GH16953)
  • Line plots no longer assume monotonic x data when calculating xlims, they show the entire lines now even for unsorted x data. (GH11310, GH11471)
  • With matplotlib 2.0.0 and above, calculation of x limits for line plots is left to matplotlib, so that its new default settings are applied. (GH15495)
  • Bug in Series.plot.bar or DataFrame.plot.bar with y not respecting user-passed color (GH16822)
  • Bug causing plotting.parallel_coordinates to reset the random seed when using random colors (GH17525)

Groupby/Resample/Rolling

  • Bug in DataFrame.resample(...).size() where an empty DataFrame did not return a Series (GH14962)
  • Bug in infer_freq() causing indices with 2-day gaps during the working week to be wrongly inferred as business daily (GH16624)
  • Bug in .rolling(...).quantile() which incorrectly used different defaults than Series.quantile() and DataFrame.quantile() (GH9413, GH16211)
  • Bug in groupby.transform() that would coerce boolean dtypes back to float (GH16875)
  • Bug in Series.resample(...).apply() where an empty Series modified the source index and did not return the name of a Series (GH14313)
  • Bug in .rolling(...).apply(...) with a DataFrame with a DatetimeIndex, a window of a timedelta-convertible and min_periods >= 1 (GH15305)
  • Bug in DataFrame.groupby where index and column keys were not recognized correctly when the number of keys equaled the number of elements on the groupby axis (GH16859)
  • Bug in groupby.nunique() with TimeGrouper which cannot handle NaT correctly (GH17575)
  • Bug in DataFrame.groupby where a single level selection from a MultiIndex unexpectedly sorts (GH17537)
  • Bug in DataFrame.groupby where spurious warning is raised when Grouper object is used to override ambiguous column name (GH17383)
  • Bug in TimeGrouper differs when passes as a list and as a scalar (GH17530)

Sparse

  • Bug in SparseSeries raises AttributeError when a dictionary is passed in as data (GH16905)
  • Bug in SparseDataFrame.fillna() not filling all NaNs when frame was instantiated from SciPy sparse matrix (GH16112)
  • Bug in SparseSeries.unstack() and SparseDataFrame.stack() (GH16614, GH15045)
  • Bug in make_sparse() treating two numeric/boolean data, which have same bits, as same when array dtype is object (GH17574)
  • SparseArray.all() and SparseArray.any() are now implemented to handle SparseArray, these were used but not implemented (GH17570)

Reshaping

  • Joining/Merging with a non unique PeriodIndex raised a TypeError (GH16871)
  • Bug in crosstab() where non-aligned series of integers were casted to float (GH17005)
  • Bug in merging with categorical dtypes with datetimelikes incorrectly raised a TypeError (GH16900)
  • Bug when using isin() on a large object series and large comparison array (GH16012)
  • Fixes regression from 0.20, Series.aggregate() and DataFrame.aggregate() allow dictionaries as return values again (GH16741)
  • Fixes dtype of result with integer dtype input, from pivot_table() when called with margins=True (GH17013)
  • Bug in crosstab() where passing two Series with the same name raised a KeyError (GH13279)
  • Series.argmin(), Series.argmax(), and their counterparts on DataFrame and groupby objects work correctly with floating point data that contains infinite values (GH13595).
  • Bug in unique() where checking a tuple of strings raised a TypeError (GH17108)
  • Bug in concat() where order of result index was unpredictable if it contained non-comparable elements (GH17344)
  • Fixes regression when sorting by multiple columns on a datetime64 dtype Series with NaT values (GH16836)
  • Bug in pivot_table() where the result’s columns did not preserve the categorical dtype of columns when dropna was False (GH17842)
  • Bug in DataFrame.drop_duplicates where dropping with non-unique column names raised a ValueError (GH17836)
  • Bug in unstack() which, when called on a list of levels, would discard the fillna argument (GH13971)
  • Bug in the alignment of range objects and other list-likes with DataFrame leading to operations being performed row-wise instead of column-wise (GH17901)

Numeric

  • Bug in .clip() with axis=1 and a list-like for threshold is passed; previously this raised ValueError (GH15390)
  • Series.clip() and DataFrame.clip() now treat NA values for upper and lower arguments as None instead of raising ValueError (GH17276).

Categorical

  • Bug in Series.isin() when called with a categorical (GH16639)
  • Bug in the categorical constructor with empty values and categories causing the .categories to be an empty Float64Index rather than an empty Index with object dtype (GH17248)
  • Bug in categorical operations with Series.cat not preserving the original Series’ name (GH17509)
  • Bug in DataFrame.merge() failing for categorical columns with boolean/int data types (GH17187)
  • Bug in constructing a Categorical/CategoricalDtype when the specified categories are of categorical type (GH17884).

PyPy

  • Compatibility with PyPy in read_csv() with usecols=[<unsorted ints>] and read_json() (GH17351)
  • Split tests into cases for CPython and PyPy where needed, which highlights the fragility of index matching with float('nan'), np.nan and NAT (GH17351)
  • Fix DataFrame.memory_usage() to support PyPy. Objects on PyPy do not have a fixed size, so an approximation is used instead (GH17228)

Other

  • Bug where some inplace operators were not being wrapped and produced a copy when invoked (GH12962)
  • Bug in eval() where the inplace parameter was being incorrectly handled (GH16732)

v0.20.3 (July 7, 2017)

This is a minor bug-fix release in the 0.20.x series and includes some small regression fixes and bug fixes. We recommend that all users upgrade to this version.

Bug Fixes

  • Fixed a bug in failing to compute rolling computations of a column-MultiIndexed DataFrame (GH16789, GH16825)
  • Fixed a pytest marker failing downstream packages’ tests suites (GH16680)

Conversion

  • Bug in pickle compat prior to the v0.20.x series, when UTC is a timezone in a Series/DataFrame/Index (GH16608)
  • Bug in Series construction when passing a Series with dtype='category' (GH16524).
  • Bug in DataFrame.astype() when passing a Series as the dtype kwarg. (GH16717).

Indexing

  • Bug in Float64Index causing an empty array instead of None to be returned from .get(np.nan) on a Series whose index did not contain any NaN s (GH8569)
  • Bug in MultiIndex.isin causing an error when passing an empty iterable (GH16777)
  • Fixed a bug in a slicing DataFrame/Series that have a TimedeltaIndex (GH16637)

I/O

  • Bug in read_csv() in which files weren’t opened as binary files by the C engine on Windows, causing EOF characters mid-field, which would fail (GH16039, GH16559, GH16675)
  • Bug in read_hdf() in which reading a Series saved to an HDF file in ‘fixed’ format fails when an explicit mode='r' argument is supplied (GH16583)
  • Bug in DataFrame.to_latex() where bold_rows was wrongly specified to be True by default, whereas in reality row labels remained non-bold whatever parameter provided. (GH16707)
  • Fixed an issue with DataFrame.style() where generated element ids were not unique (GH16780)
  • Fixed loading a DataFrame with a PeriodIndex, from a format='fixed' HDFStore, in Python 3, that was written in Python 2 (GH16781)

Plotting

  • Fixed regression that prevented RGB and RGBA tuples from being used as color arguments (GH16233)
  • Fixed an issue with DataFrame.plot.scatter() that incorrectly raised a KeyError when categorical data is used for plotting (GH16199)

Reshaping

  • PeriodIndex / TimedeltaIndex.join was missing the sort= kwarg (GH16541)
  • Bug in joining on a MultiIndex with a category dtype for a level (GH16627).
  • Bug in merge() when merging/joining with multiple categorical columns (GH16767)

Categorical

  • Bug in DataFrame.sort_values not respecting the kind parameter with categorical data (GH16793)

v0.20.2 (June 4, 2017)

This is a minor bug-fix release in the 0.20.x series and includes some small regression fixes, bug fixes and performance improvements. We recommend that all users upgrade to this version.

Enhancements

  • Unblocked access to additional compression types supported in pytables: ‘blosc:blosclz, ‘blosc:lz4’, ‘blosc:lz4hc’, ‘blosc:snappy’, ‘blosc:zlib’, ‘blosc:zstd’ (GH14478)
  • Series provides a to_latex method (GH16180)
  • A new groupby method ngroup(), parallel to the existing cumcount(), has been added to return the group order (GH11642); see here.

Performance Improvements

  • Performance regression fix when indexing with a list-like (GH16285)
  • Performance regression fix for MultiIndexes (GH16319, GH16346)
  • Improved performance of .clip() with scalar arguments (GH15400)
  • Improved performance of groupby with categorical groupers (GH16413)
  • Improved performance of MultiIndex.remove_unused_levels() (GH16556)

Bug Fixes

  • Silenced a warning on some Windows environments about “tput: terminal attributes: No such device or address” when detecting the terminal size. This fix only applies to python 3 (GH16496)
  • Bug in using pathlib.Path or py.path.local objects with io functions (GH16291)
  • Bug in Index.symmetric_difference() on two equal MultiIndex’s, results in a TypeError (:issue 13490)
  • Bug in DataFrame.update() with overwrite=False and NaN values (GH15593)
  • Passing an invalid engine to read_csv() now raises an informative ValueError rather than UnboundLocalError. (GH16511)
  • Bug in unique() on an array of tuples (GH16519)
  • Bug in cut() when labels are set, resulting in incorrect label ordering (GH16459)
  • Fixed a compatibility issue with IPython 6.0’s tab completion showing deprecation warnings on Categoricals (GH16409)

Conversion

  • Bug in to_numeric() in which empty data inputs were causing a segfault of the interpreter (GH16302)
  • Silence numpy warnings when broadcasting DataFrame to Series with comparison ops (GH16378, GH16306)

Indexing

  • Bug in DataFrame.reset_index(level=) with single level index (GH16263)
  • Bug in partial string indexing with a monotonic, but not strictly-monotonic, index incorrectly reversing the slice bounds (GH16515)
  • Bug in MultiIndex.remove_unused_levels() that would not return a MultiIndex equal to the original. (GH16556)

I/O

  • Bug in read_csv() when comment is passed in a space delimited text file (GH16472)
  • Bug in read_csv() not raising an exception with nonexistent columns in usecols when it had the correct length (GH14671)
  • Bug that would force importing of the clipboard routines unnecessarily, potentially causing an import error on startup (GH16288)
  • Bug that raised IndexError when HTML-rendering an empty DataFrame (GH15953)
  • Bug in read_csv() in which tarfile object inputs were raising an error in Python 2.x for the C engine (GH16530)
  • Bug where DataFrame.to_html() ignored the index_names parameter (GH16493)
  • Bug where pd.read_hdf() returns numpy strings for index names (GH13492)
  • Bug in HDFStore.select_as_multiple() where start/stop arguments were not respected (GH16209)

Plotting

  • Bug in DataFrame.plot with a single column and a list-like color (GH3486)
  • Bug in plot where NaT in DatetimeIndex results in Timestamp.min (:issue: 12405)
  • Bug in DataFrame.boxplot where figsize keyword was not respected for non-grouped boxplots (GH11959)

Groupby/Resample/Rolling

  • Bug in creating a time-based rolling window on an empty DataFrame (GH15819)
  • Bug in rolling.cov() with offset window (GH16058)
  • Bug in .resample() and .groupby() when aggregating on integers (GH16361)

Sparse

  • Bug in construction of SparseDataFrame from scipy.sparse.dok_matrix (GH16179)

Reshaping

  • Bug in DataFrame.stack with unsorted levels in MultiIndex columns (GH16323)
  • Bug in pd.wide_to_long() where no error was raised when i was not a unique identifier (GH16382)
  • Bug in Series.isin(..) with a list of tuples (GH16394)
  • Bug in construction of a DataFrame with mixed dtypes including an all-NaT column. (GH16395)
  • Bug in DataFrame.agg() and Series.agg() with aggregating on non-callable attributes (GH16405)

Numeric

  • Bug in .interpolate(), where limit_direction was not respected when limit=None (default) was passed (GH16282)

Categorical

  • Fixed comparison operations considering the order of the categories when both categoricals are unordered (GH16014)

Other

  • Bug in DataFrame.drop() with an empty-list with non-unique indices (GH16270)

v0.20.1 (May 5, 2017)

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.
  • The .ix indexer has been deprecated, see here
  • Panel has been deprecated, see here
  • Addition of an IntervalIndex and Interval scalar type, see here
  • Improved user API when grouping by index levels in .groupby(), see here
  • Improved support for UInt64 dtypes, 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
  • Support for S3 handling now uses s3fs, see here
  • Google BigQuery support now uses the pandas-gbq library, see here

Warning

Pandas has changed the internal structure and layout of the codebase. This can affect imports that are not from the top-level pandas.* namespace, please see the changes here.

Check the API Changes and deprecations before updating.

Note

This is a combined release for 0.20.0 and and 0.20.1. Version 0.20.1 contains one additional change for backwards-compatibility with downstream projects using pandas’ utils routines. (GH16250)

What’s new in v0.20.0

New features

agg API for DataFrame/Series

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 (GH1623).

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.nan

In [3]: df
Out[3]: 
                   A         B         C
2000-01-01  0.665719  0.234544 -0.497107
2000-01-02  0.603650  0.567011 -0.994009
2000-01-03 -2.230893 -1.635263  0.357573
2000-01-04       NaN       NaN       NaN
2000-01-05       NaN       NaN       NaN
2000-01-06       NaN       NaN       NaN
2000-01-07       NaN       NaN       NaN
2000-01-08  1.667624  1.619575 -0.948507
2000-01-09 -0.360596  1.412609 -0.398833
2000-01-10 -2.429301 -0.645124 -0.102111

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   -2.083797
B    1.553352
C   -2.582995
dtype: float64

Multiple aggregations with a list of functions.

In [5]: df.agg(['sum', 'min'])
Out[5]: 
            A         B         C
sum -2.083797  1.553352 -2.582995
min -2.429301 -1.635263 -0.994009

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         B
max       NaN  1.619575
min -2.429301 -1.635263
sum -2.083797       NaN

The API also supports a .transform() function for broadcasting results.

In [7]: df.transform(['abs', lambda x: x - x.min()])
Out[7]: 
                   A                   B                   C          
                 abs  <lambda>       abs  <lambda>       abs  <lambda>
2000-01-01  0.665719  3.095020  0.234544  1.869807  0.497107  0.496902
2000-01-02  0.603650  3.032952  0.567011  2.202274  0.994009  0.000000
2000-01-03  2.230893  0.198409  1.635263  0.000000  0.357573  1.351583
2000-01-04       NaN       NaN       NaN       NaN       NaN       NaN
2000-01-05       NaN       NaN       NaN       NaN       NaN       NaN
2000-01-06       NaN       NaN       NaN       NaN       NaN       NaN
2000-01-07       NaN       NaN       NaN       NaN       NaN       NaN
2000-01-08  1.667624  4.096925  1.619575  3.254838  0.948507  0.045502
2000-01-09  0.360596  2.068705  1.412609  3.047871  0.398833  0.595176
2000-01-10  2.429301  0.000000  0.645124  0.990138  0.102111  0.891898

When presented with mixed dtypes that cannot be aggregated, .agg() will only take the valid aggregations. This is similiar to how groupby .agg() works. (GH15015)

In [8]: df = pd.DataFrame({'A': [1, 2, 3],
   ...:                    'B': [1., 2., 3.],
   ...:                    'C': ['foo', 'bar', 'baz'],
   ...:                    'D': pd.date_range('20130101', periods=3)})
   ...: 

In [9]: df.dtypes
Out[9]: 
A             int64
B           float64
C            object
D    datetime64[ns]
dtype: object
In [10]: df.agg(['min', 'sum'])
Out[10]: 
     A    B          C          D
min  1  1.0        bar 2013-01-01
sum  6  6.0  foobarbaz        NaT

dtype keyword for data IO

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 (GH14295). See the io docs for more information.

In [11]: data = "a  b\n1  2\n3  4"

In [12]: pd.read_fwf(StringIO(data)).dtypes
Out[12]: 
a    int64
b    int64
dtype: object

In [13]: pd.read_fwf(StringIO(data), dtype={'a':'float64', 'b':'object'}).dtypes
Out[13]: 
a    float64
b     object
dtype: object

.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. (GH11276, GH11745)

For example, with 1960-01-01 as the starting date:

In [14]: pd.to_datetime([1, 2, 3], unit='D', origin=pd.Timestamp('1960-01-01'))
Out[14]: DatetimeIndex(['1960-01-02', '1960-01-03', '1960-01-04'], dtype='datetime64[ns]', freq=None)

The default is set at origin='unix', which defaults to 1970-01-01 00:00:00, which is commonly called ‘unix epoch’ or POSIX time. This was the previous default, so this is a backward compatible change.

In [15]: pd.to_datetime([1, 2, 3], unit='D')
Out[15]: DatetimeIndex(['1970-01-02', '1970-01-03', '1970-01-04'], dtype='datetime64[ns]', freq=None)

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. (GH5677)

In [16]: arrays = [['bar', 'bar', 'baz', 'baz', 'foo', 'foo', 'qux', 'qux'],
   ....:           ['one', 'two', 'one', 'two', 'one', 'two', 'one', 'two']]
   ....: 

In [17]: index = pd.MultiIndex.from_arrays(arrays, names=['first', 'second'])

In [18]: df = pd.DataFrame({'A': [1, 1, 1, 1, 2, 2, 3, 3],
   ....:                    'B': np.arange(8)},
   ....:                   index=index)
   ....: 

In [19]: df
Out[19]: 
              A  B
first second      
bar   one     1  0
      two     1  1
baz   one     1  2
      two     1  3
foo   one     2  4
      two     2  5
qux   one     3  6
      two     3  7

In [20]: df.groupby(['second', 'A']).sum()
Out[20]: 
          B
second A   
one    1  2
       2  4
       3  6
two    1  4
       2  5
       3  7

Better support for compressed URLs in read_csv

The compression code was refactored (GH12688). As a result, reading dataframes from URLs in read_csv() or read_table() now supports additional compression methods: xz, bz2, and zip (GH14570). 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 (GH14874).

In [21]: url = 'https://github.com/{repo}/raw/{branch}/{path}'.format(
   ....:     repo = 'pandas-dev/pandas',
   ....:     branch = 'master',
   ....:     path = 'pandas/tests/io/parser/data/salaries.csv.bz2',
   ....: )
   ....: 

In [22]: df = pd.read_table(url, compression='infer')  # default, infer compression

In [23]: df = pd.read_table(url, compression='bz2')  # explicitly specify compression

In [24]: df.head(2)
Out[24]: 
       S  X  E  M
0  13876  1  1  1
1  11608  1  3  0

Pickle file I/O now supports compression

read_pickle(), DataFrame.to_pickle() and Series.to_pickle() can now read from and write to compressed pickle files. Compression methods can be an explicit parameter or be inferred from the file extension. See the docs here.

In [25]: df = pd.DataFrame({
   ....:     'A': np.random.randn(1000),
   ....:     'B': 'foo',
   ....:     'C': pd.date_range('20130101', periods=1000, freq='s')})
   ....: 

Using an explicit compression type

In [26]: df.to_pickle("data.pkl.compress", compression="gzip")

In [27]: rt = pd.read_pickle("data.pkl.compress", compression="gzip")

In [28]: rt.head()
Out[28]: 
          A    B                   C
0  0.804438  foo 2013-01-01 00:00:00
1 -0.000818  foo 2013-01-01 00:00:01
2 -1.084383  foo 2013-01-01 00:00:02
3  1.776343  foo 2013-01-01 00:00:03
4  0.884521  foo 2013-01-01 00:00:04

The default is to infer the compression type from the extension (compression='infer'):

In [29]: df.to_pickle("data.pkl.gz")

In [30]: rt = pd.read_pickle("data.pkl.gz")

In [31]: rt.head()
Out[31]: 
          A    B                   C
0  0.804438  foo 2013-01-01 00:00:00
1 -0.000818  foo 2013-01-01 00:00:01
2 -1.084383  foo 2013-01-01 00:00:02
3  1.776343  foo 2013-01-01 00:00:03
4  0.884521  foo 2013-01-01 00:00:04

In [32]: df["A"].to_pickle("s1.pkl.bz2")

In [33]: rt = pd.read_pickle("s1.pkl.bz2")

In [34]: rt.head()
Out[34]: 
0    0.804438
1   -0.000818
2   -1.084383
3    1.776343
4    0.884521
Name: A, dtype: float64

UInt64 Support 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 (GH14937)

In [35]: idx = pd.UInt64Index([1, 2, 3])

In [36]: df = pd.DataFrame({'A': ['a', 'b', 'c']}, index=idx)

In [37]: df.index
Out[37]: UInt64Index([1, 2, 3], dtype='uint64')
  • Bug in converting object elements of array-like objects to unsigned 64-bit integers (GH4471, GH14982)
  • Bug in Series.unique() in which unsigned 64-bit integers were causing overflow (GH14721)
  • Bug in DataFrame construction in which unsigned 64-bit integer elements were being converted to objects (GH14881)
  • Bug in pd.read_csv() in which unsigned 64-bit integer elements were being improperly converted to the wrong data types (GH14983)
  • Bug in pd.unique() in which unsigned 64-bit integers were causing overflow (GH14915)
  • Bug in pd.value_counts() in which unsigned 64-bit integers were being erroneously truncated in the output (GH14934)

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. (GH13179)

In [38]: chromosomes = np.r_[np.arange(1, 23).astype(str), ['X', 'Y']]

In [39]: 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 [40]: df
Out[40]: 
     A   B   C chromosomes
0   61  79  43          17
1   61  79  43          11
2   61  79  43           8
3   61  79  43          17
4   61  79  43          14
5   61  79  43          14
6   61  79  43           X
..  ..  ..  ..         ...
93  61  79  43           1
94  61  79  43           1
95  61  79  43           6
96  61  79  43          11
97  61  79  43          13
98  61  79  43           3
99  61  79  43           8

[100 rows x 4 columns]

Previous Behavior:

In [3]: df[df.chromosomes != '1'].groupby('chromosomes', sort=False).sum()
---------------------------------------------------------------------------
ValueError: items in new_categories are not the same as in old categories

New Behavior:

In [41]: df[df.chromosomes != '1'].groupby('chromosomes', sort=False).sum()
Out[41]: 
               A    B    C
chromosomes               
2            305  395  215
3             61   79   43
4            244  316  172
5            366  474  258
6            305  395  215
7            244  316  172
8            305  395  215
...          ...  ...  ...
19           305  395  215
20           122  158   86
22           366  474  258
X            244  316  172
Y            183  237  129
1              0    0    0
21             0    0    0

[24 rows x 3 columns]

Table Schema Output

The new orient 'table' for DataFrame.to_json() will generate a Table Schema compatible string representation of the data.

In [42]: df = pd.DataFrame(
   ....:     {'A': [1, 2, 3],
   ....:      'B': ['a', 'b', 'c'],
   ....:      'C': pd.date_range('2016-01-01', freq='d', periods=3),
   ....:     }, index=pd.Index(range(3), name='idx'))
   ....: 

In [43]: df
Out[43]: 
     A  B          C
idx                 
0    1  a 2016-01-01
1    2  b 2016-01-02
2    3  c 2016-01-03

In [44]: df.to_json(orient='table')
Out[44]: '{"schema": {"fields":[{"name":"idx","type":"integer"},{"name":"A","type":"integer"},{"name":"B","type":"string"},{"name":"C","type":"datetime"}],"primaryKey":["idx"],"pandas_version":"0.20.0"}, "data": [{"idx":0,"A":1,"B":"a","C":"2016-01-01T00:00:00.000Z"},{"idx":1,"A":2,"B":"b","C":"2016-01-02T00:00:00.000Z"},{"idx":2,"A":3,"B":"c","C":"2016-01-03T00:00:00.000Z"}]}'

See IO: Table Schema for more information.

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 flexiblity 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.

SciPy sparse matrix from/to SparseDataFrame

Pandas now supports creating sparse dataframes directly from scipy.sparse.spmatrix instances. See the documentation for more information. (GH4343)

All sparse formats are supported, but matrices that are not in COOrdinate format will be converted, copying data as needed.

In [45]: from scipy.sparse import csr_matrix

In [46]: arr = np.random.random(size=(1000, 5))

In [47]: arr[arr < .9] = 0

In [48]: sp_arr = csr_matrix(arr)

In [49]: sp_arr
Out[49]: 
<1000x5 sparse matrix of type '<class 'numpy.float64'>'
	with 521 stored elements in Compressed Sparse Row format>

In [50]: sdf = pd.SparseDataFrame(sp_arr)

In [51]: sdf
Out[51]: 
            0         1         2         3         4
0         NaN       NaN       NaN       NaN       NaN
1         NaN       NaN       NaN  0.999681       NaN
2    0.989621       NaN       NaN       NaN       NaN
3         NaN  0.986495       NaN       NaN       NaN
4         NaN       NaN       NaN       NaN  0.990083
5         NaN       NaN  0.987794       NaN       NaN
6         NaN       NaN       NaN       NaN       NaN
..        ...       ...       ...       ...       ...
993  0.936109       NaN       NaN       NaN       NaN
994       NaN       NaN       NaN       NaN       NaN
995       NaN       NaN       NaN       NaN  0.981932
996       NaN  0.985932       NaN  0.967058       NaN
997       NaN       NaN       NaN       NaN       NaN
998       NaN       NaN       NaN       NaN       NaN
999       NaN       NaN       NaN       NaN       NaN

[1000 rows x 5 columns]

To convert a SparseDataFrame back to sparse SciPy matrix in COO format, you can use:

In [52]: sdf.to_coo()
Out[52]: 
<1000x5 sparse matrix of type '<class 'numpy.float64'>'
	with 521 stored elements in COOrdinate format>

Excel output for styled DataFrames

Experimental support has been added to export DataFrame.style formats to Excel using the openpyxl engine. (GH15530)

For example, after running the following, styled.xlsx renders as below:

In [53]: np.random.seed(24)

In [54]: df = pd.DataFrame({'A': np.linspace(1, 10, 10)})

In [55]: df = pd.concat([df, pd.DataFrame(np.random.RandomState(24).randn(10, 4),
   ....:                                  columns=list('BCDE'))],
   ....:                axis=1)
   ....: 

In [56]: df.iloc[0, 2] = np.nan

In [57]: df
Out[57]: 
      A         B         C         D         E
0   1.0  1.329212       NaN -0.316280 -0.990810
1   2.0 -1.070816 -1.438713  0.564417  0.295722
2   3.0 -1.626404  0.219565  0.678805  1.889273
3   4.0  0.961538  0.104011 -0.481165  0.850229
4   5.0  1.453425  1.057737  0.165562  0.515018
5   6.0 -1.336936  0.562861  1.392855 -0.063328
6   7.0  0.121668  1.207603 -0.002040  1.627796
7   8.0  0.354493  1.037528 -0.385684  0.519818
8   9.0  1.686583 -1.325963  1.428984 -2.089354
9  10.0 -0.129820  0.631523 -0.586538  0.290720

In [58]: styled = df.style.\
   ....:     applymap(lambda val: 'color: %s' % 'red' if val < 0 else 'black').\
   ....:     highlight_max()
   ....: 

In [59]: styled.to_excel('styled.xlsx', engine='openpyxl')
_images/style-excel.png

See the Style documentation for more detail.

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. (GH7640, GH8625)

Warning

These indexing behaviors of the IntervalIndex are provisional and may change in a future version of pandas. Feedback on usage is welcome.

Previous behavior:

The returned categories were strings, representing Intervals

In [1]: c = pd.cut(range(4), bins=2)

In [2]: c
Out[2]:
[(-0.003, 1.5], (-0.003, 1.5], (1.5, 3], (1.5, 3]]
Categories (2, object): [(-0.003, 1.5] < (1.5, 3]]

In [3]: c.categories
Out[3]: Index(['(-0.003, 1.5]', '(1.5, 3]'], dtype='object')

New behavior:

In [60]: c = pd.cut(range(4), bins=2)

In [61]: c
Out[61]: 
[(-0.003, 1.5], (-0.003, 1.5], (1.5, 3.0], (1.5, 3.0]]
Categories (2, interval[float64]): [(-0.003, 1.5] < (1.5, 3.0]]

In [62]: c.categories
Out[62]: 
IntervalIndex([(-0.003, 1.5], (1.5, 3.0]]
              closed='right',
              dtype='interval[float64]')

Furthermore, this allows one to bin other data with these same bins, with NaN representing a missing value similar to other dtypes.

In [63]: pd.cut([0, 3, 5, 1], bins=c.categories)
Out[63]: 
[(-0.003, 1.5], (1.5, 3.0], NaN, (-0.003, 1.5]]
Categories (2, interval[float64]): [(-0.003, 1.5] < (1.5, 3.0]]

An IntervalIndex can also be used in Series and DataFrame as the index.

In [64]: df = pd.DataFrame({'A': range(4),
   ....:                    'B': pd.cut([0, 3, 1, 1], bins=c.categories)}
   ....:                  ).set_index('B')
   ....: 

In [65]: df
Out[65]: 
               A
B               
(-0.003, 1.5]  0
(1.5, 3.0]     1
(-0.003, 1.5]  2
(-0.003, 1.5]  3

Selecting via a specific interval:

In [66]: df.loc[pd.Interval(1.5, 3.0)]
Out[66]: 
A    1
Name: (1.5, 3.0], dtype: int64

Selecting via a scalar value that is contained in the intervals.

In [67]: df.loc[0]
Out[67]: 
               A
B               
(-0.003, 1.5]  0
(-0.003, 1.5]  2
(-0.003, 1.5]  3

Other Enhancements

  • DataFrame.rolling() now accepts the parameter closed='right'|'left'|'both'|'neither' to choose the rolling window-endpoint closedness. See the documentation (GH13965)
  • 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 re.sub (GH15055)
  • Series.str.replace() now accepts a compiled regular expression as a pattern (GH15446)
  • Series.sort_index accepts parameters kind and na_position (GH13589, GH14444)
  • DataFrame and DataFrame.groupby() have gained a nunique() method to count the distinct values over an axis (GH14336, GH15197).
  • DataFrame has gained a melt() method, equivalent to pd.melt(), for unpivoting from a wide to long format (GH12640).
  • pd.read_excel() now preserves sheet order when using sheetname=None (GH9930)
  • Multiple offset aliases with decimal points are now supported (e.g. 0.5min is parsed as 30s) (GH8419)
  • .isnull() and .notnull() have been added to Index object to make them more consistent with the Series API (GH15300)
  • New UnsortedIndexError (subclass of KeyError) raised when indexing/slicing into an unsorted MultiIndex (GH11897). 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 (GH12397)
  • pd.cut and pd.qcut now support datetime64 and timedelta64 dtypes (GH14714, GH14798)
  • pd.qcut has gained the duplicates='raise'|'drop' option to control whether to raise on duplicated edges (GH7751)
  • Series provides a to_excel method to output Excel files (GH8825)
  • The usecols argument in pd.read_csv() now accepts a callable function as a value (GH14154)
  • The skiprows argument in pd.read_csv() now accepts a callable function as a value (GH10882)
  • The nrows and chunksize arguments in pd.read_csv() are supported if both are passed (GH6774, GH15755)
  • DataFrame.plot now prints a title above each subplot if suplots=True and title is a list of strings (GH14753)
  • DataFrame.plot can pass the matplotlib 2.0 default color cycle as a single string as color parameter, see here. (GH15516)
  • Series.interpolate() now supports timedelta as an index type with method='time' (GH6424)
  • Addition of a level keyword to DataFrame/Series.rename to rename labels in the specified level of a MultiIndex (GH4160).
  • DataFrame.reset_index() will now interpret a tuple index.name as a key spanning across levels of columns, if this is a MultiIndex (GH16164)
  • Timedelta.isoformat method added for formatting Timedeltas as an ISO 8601 duration. See the Timedelta docs (GH15136)
  • .select_dtypes() now allows the string datetimetz to generically select datetimes with tz (GH14910)
  • The .to_latex() method will now accept multicolumn and multirow arguments to use the accompanying LaTeX enhancements
  • pd.merge_asof() gained the option direction='backward'|'forward'|'nearest' (GH14887)
  • Series/DataFrame.asfreq() have gained a fill_value parameter, to fill missing values (GH3715).
  • Series/DataFrame.resample.asfreq have gained a fill_value parameter, to fill missing values during resampling (GH3715).
  • pandas.util.hash_pandas_object() has gained the ability to hash a MultiIndex (GH15224)
  • Series/DataFrame.squeeze() have gained the axis parameter. (GH15339)
  • DataFrame.to_excel() has a new freeze_panes parameter to turn on Freeze Panes when exporting to Excel (GH15160)
  • pd.read_html() will parse multiple header rows, creating a MutliIndex header. (GH13434).
  • HTML table output skips colspan or rowspan attribute if equal to 1. (GH15403)
  • pandas.io.formats.style.Styler template now has blocks for easier extension, see the example notebook (GH15649)
  • Styler.render() now accepts **kwargs to allow user-defined variables in the template (GH15649)
  • Compatibility with Jupyter notebook 5.0; MultiIndex column labels are left-aligned and MultiIndex row-labels are top-aligned (GH15379)
  • TimedeltaIndex now has a custom date-tick formatter specifically designed for nanosecond level precision (GH8711)
  • pd.api.types.union_categoricals gained the ignore_ordered argument to allow ignoring the ordered attribute of unioned categoricals (GH13410). See the categorical union docs for more information.
  • DataFrame.to_latex() and DataFrame.to_string() now allow optional header aliases. (GH15536)
  • Re-enable the parse_dates keyword of pd.read_excel() to parse string columns as dates (GH14326)
  • Added .empty property to subclasses of Index. (GH15270)
  • Enabled floor division for Timedelta and TimedeltaIndex (GH15828)
  • pandas.io.json.json_normalize() gained the option errors='ignore'|'raise'; the default is errors='raise' which is backward compatible. (GH14583)
  • pandas.io.json.json_normalize() with an empty list will return an empty DataFrame (GH15534)
  • pandas.io.json.json_normalize() has gained a sep option that accepts str to separate joined fields; the default is ”.”, which is backward compatible. (GH14883)
  • MultiIndex.remove_unused_levels() has been added to facilitate removing unused levels. (GH15694)
  • pd.read_csv() will now raise a ParserError error whenever any parsing error occurs (GH15913, GH15925)
  • pd.read_csv() now supports the error_bad_lines and warn_bad_lines arguments for the Python parser (GH15925)
  • The display.show_dimensions option can now also be used to specify whether the length of a Series should be shown in its repr (GH7117).
  • parallel_coordinates() has gained a sort_labels keyword argument that sorts class labels and the colors assigned to them (GH15908)
  • Options added to allow one to turn on/off using bottleneck and numexpr, see here (GH16157)
  • 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]. (GH14757)

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. (GH15098).

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.

In [2]: s = pd.TimeSeries([1,2,3], index=pd.date_range('20130101', periods=3))

In [3]: s
Out[3]:
2013-01-01    1
2013-01-02    2
2013-01-03    3
Freq: D, dtype: int64

In [4]: type(s)
Out[4]: pandas.core.series.TimeSeries

In [5]: s = pd.Series(s)

In [6]: s
Out[6]:
2013-01-01    1
2013-01-02    2
2013-01-03    3
Freq: D, dtype: int64

In [7]: type(s)
Out[7]: pandas.core.series.Series

Map on Index types now return other Index types

map on an Index now returns an Index, not a numpy array (GH12766)

In [68]: idx = Index([1, 2])

In [69]: idx
Out[69]: Int64Index([1, 2], dtype='int64')

In [70]: mi = MultiIndex.from_tuples([(1, 2), (2, 4)])

In [71]: mi
Out[71]: 
MultiIndex(levels=[[1, 2], [2, 4]],
           labels=[[0, 1], [0, 1]])

Previous Behavior:

In [5]: idx.map(lambda x: x * 2)
Out[5]: array([2, 4])

In [6]: idx.map(lambda x: (x, x * 2))
Out[6]: array([(1, 2), (2, 4)], dtype=object)

In [7]: mi.map(lambda x: x)
Out[7]: array([(1, 2), (2, 4)], dtype=object)

In [8]: mi.map(lambda x: x[0])
Out[8]: array([1, 2])

New Behavior:

In [72]: idx.map(lambda x: x * 2)
Out[72]: Int64Index([2, 4], dtype='int64')

In [73]: idx.map(lambda x: (x, x * 2))
Out[73]: 
MultiIndex(levels=[[1, 2], [2, 4]],
           labels=[[0, 1], [0, 1]])

In [74]: mi.map(lambda x: x)
Out[74]: 
MultiIndex(levels=[[1, 2], [2, 4]],
           labels=[[0, 1], [0, 1]])

In [75]: mi.map(lambda x: x[0])
Out[75]: Int64Index([1, 2], dtype='int64')

map on a Series with datetime64 values may return int64 dtypes rather than int32

In [76]: s = Series(date_range('2011-01-02T00:00', '2011-01-02T02:00', freq='H').tz_localize('Asia/Tokyo'))

In [77]: s
Out[77]: 
0   2011-01-02 00:00:00+09:00
1   2011-01-02 01:00:00+09:00
2   2011-01-02 02:00:00+09:00
dtype: datetime64[ns, Asia/Tokyo]

Previous Behavior:

In [9]: s.map(lambda x: x.hour)
Out[9]:
0    0
1    1
2    2
dtype: int32

New Behavior:

In [78]: s.map(lambda x: x.hour)
Out[78]: 
0    0
1    1
2    2
dtype: int64

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. (GH15022)

Previous behaviour:

In [1]: idx = pd.date_range("2015-01-01", periods=5, freq='10H')

In [2]: idx.hour
Out[2]: array([ 0, 10, 20,  6, 16], dtype=int32)

New Behavior:

In [79]: idx = pd.date_range("2015-01-01", periods=5, freq='10H')

In [80]: idx.hour
Out[80]: Int64Index([0, 10, 20, 6, 16], dtype='int64')

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).

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. (GH15903)

  • Datetime tz-aware

    Previous behaviour:

    # Series
    In [5]: pd.Series([pd.Timestamp('20160101', tz='US/Eastern'),
                       pd.Timestamp('20160101', tz='US/Eastern')]).unique()
    Out[5]: array([Timestamp('2016-01-01 00:00:00-0500', tz='US/Eastern')], dtype=object)
    
    In [6]: pd.unique(pd.Series([pd.Timestamp('20160101', tz='US/Eastern'),
                                 pd.Timestamp('20160101', tz='US/Eastern')]))
    Out[6]: array(['2016-01-01T05:00:00.000000000'], dtype='datetime64[ns]')
    
    # Index
    In [7]: pd.Index([pd.Timestamp('20160101', tz='US/Eastern'),
                      pd.Timestamp('20160101', tz='US/Eastern')]).unique()
    Out[7]: DatetimeIndex(['2016-01-01 00:00:00-05:00'], dtype='datetime64[ns, US/Eastern]', freq=None)
    
    In [8]: pd.unique([pd.Timestamp('20160101', tz='US/Eastern'),
                       pd.Timestamp('20160101', tz='US/Eastern')])
    Out[8]: array(['2016-01-01T05:00:00.000000000'], dtype='datetime64[ns]')
    

    New Behavior:

    # Series, returns an array of Timestamp tz-aware
    In [81]: pd.Series([pd.Timestamp('20160101', tz='US/Eastern'),
       ....:           pd.Timestamp('20160101', tz='US/Eastern')]).unique()
       ....: 
    Out[81]: array([Timestamp('2016-01-01 00:00:00-0500', tz='US/Eastern')], dtype=object)
    
    In [82]: pd.unique(pd.Series([pd.Timestamp('20160101', tz='US/Eastern'),
       ....:                      pd.Timestamp('20160101', tz='US/Eastern')]))
       ....: 
    Out[82]: array([Timestamp('2016-01-01 00:00:00-0500', tz='US/Eastern')], dtype=object)
    
    # Index, returns a DatetimeIndex
    In [83]: pd.Index([pd.Timestamp('20160101', tz='US/Eastern'),
       ....:           pd.Timestamp('20160101', tz='US/Eastern')]).unique()
       ....: 
    Out[83]: DatetimeIndex(['2016-01-01 00:00:00-05:00'], dtype='datetime64[ns, US/Eastern]', freq=None)
    
    In [84]: pd.unique(pd.Index([pd.Timestamp('20160101', tz='US/Eastern'),
       ....:                     pd.Timestamp('20160101', tz='US/Eastern')]))
       ....: 
    Out[84]: DatetimeIndex(['2016-01-01 00:00:00-05:00'], dtype='datetime64[ns, US/Eastern]', freq=None)
    
  • Categoricals

    Previous behaviour:

    In [1]: pd.Series(list('baabc'), dtype='category').unique()
    Out[1]:
    [b, a, c]
    Categories (3, object): [b, a, c]
    
    In [2]: pd.unique(pd.Series(list('baabc'), dtype='category'))
    Out[2]: array(['b', 'a', 'c'], dtype=object)
    

    New Behavior:

    # returns a Categorical
    In [85]: pd.Series(list('baabc'), dtype='category').unique()
    Out[85]: 
    [b, a, c]
    Categories (3, object): [b, a, c]
    
    In [86]: pd.unique(pd.Series(list('baabc'), dtype='category'))
    Out[86]: 
    [b, a, c]
    Categories (3, object): [b, a, c]
    

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. (GH11915).

Partial String Indexing Changes

DatetimeIndex Partial String Indexing now works as an exact match, provided that string resolution coincides with index resolution, including a case when both are seconds (GH14826). See Slice vs. Exact Match for details.

In [87]: df = DataFrame({'a': [1, 2, 3]}, DatetimeIndex(['2011-12-31 23:59:59',
   ....:                                                 '2012-01-01 00:00:00',
   ....:                                                 '2012-01-01 00:00:01']))
   ....: 

Previous Behavior:

In [4]: df['2011-12-31 23:59:59']
Out[4]:
                       a
2011-12-31 23:59:59  1

In [5]: df['a']['2011-12-31 23:59:59']
Out[5]:
2011-12-31 23:59:59    1
Name: a, dtype: int64

New Behavior:

In [4]: df['2011-12-31 23:59:59']
KeyError: '2011-12-31 23:59:59'

In [5]: df['a']['2011-12-31 23:59:59']
Out[5]: 1

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 (GH13247)

In [88]: df1 = pd.DataFrame(np.array([1.0], dtype=np.float32, ndmin=2))

In [89]: df1.dtypes
Out[89]: 
0    float32
dtype: object

In [90]: df2 = pd.DataFrame(np.array([np.nan], dtype=np.float32, ndmin=2))

In [91]: df2.dtypes
Out[91]: 
0    float32
dtype: object

Previous Behavior:

In [7]: pd.concat([df1, df2]).dtypes
Out[7]:
0    float64
dtype: object

New Behavior:

In [92]: pd.concat([df1, df2]).dtypes
Out[92]: 
0    float32
dtype: object

Pandas Google BigQuery support has moved

pandas has split off Google BigQuery support into a separate package pandas-gbq. You can conda install pandas-gbq -c conda-forge or pip install pandas-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 (GH15347)

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. (GH15237)

Previous Behavior:

In [8]: index = Index(['foo', 'bar', 'baz'])

In [9]: index.memory_usage(deep=True)
Out[9]: 180

In [10]: index.get_loc('foo')
Out[10]: 0

In [11]: index.memory_usage(deep=True)
Out[11]: 180

New Behavior:

In [8]: index = Index(['foo', 'bar', 'baz'])

In [9]: index.memory_usage(deep=True)
Out[9]: 180

In [10]: index.get_loc('foo')
Out[10]: 0

In [11]: index.memory_usage(deep=True)
Out[11]: 260

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. (GH15622, GH15687, GH14015, GH13431, GH15797)

This is unchanged from prior versions, but shown for illustration purposes:

In [93]: df = DataFrame(np.arange(6), columns=['value'], index=MultiIndex.from_product([list('BA'), range(3)]))

In [94]: df
Out[94]: 
     value
B 0      0
  1      1
  2      2
A 0      3
  1      4
  2      5
In [95]: df.index.is_lexsorted()
Out[95]: False

In [96]: df.index.is_monotonic
Out[96]: False

Sorting works as expected

In [97]: df.sort_index()
Out[97]: 
     value
A 0      3
  1      4
  2      5
B 0      0
  1      1
  2      2
In [98]: df.sort_index().index.is_lexsorted()
Out[98]: True

In [99]: df.sort_index().index.is_monotonic
Out[99]: True

However, this example, which has a non-monotonic 2nd level, doesn’t behave as desired.

In [100]: df = pd.DataFrame(
   .....:         {'value': [1, 2, 3, 4]},
   .....:          index=pd.MultiIndex(levels=[['a', 'b'], ['bb', 'aa']],
   .....:                              labels=[[0, 0, 1, 1], [0, 1, 0, 1]]))
   .....: 

In [101]: df
Out[101]: 
      value
a bb      1
  aa      2
b bb      3
  aa      4

Previous Behavior:

In [11]: df.sort_index()
Out[11]:
      value
a bb      1
  aa      2
b bb      3
  aa      4

In [14]: df.sort_index().index.is_lexsorted()
Out[14]: True

In [15]: df.sort_index().index.is_monotonic
Out[15]: False

New Behavior:

In [102]: df.sort_index()
Out[102]: 
      value
a aa      2
  bb      1
b aa      4
  bb      3

In [103]: df.sort_index().index.is_lexsorted()
Out[103]: True

In [104]: df.sort_index().index.is_monotonic
Out[104]: True

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. (GH4792)

Previous Behavior:

In [1]: df = pd.DataFrame({'A': [1, 1, 2, 2], 'B': [1, 2, 3, 4]})

In [2]: df.groupby('A').describe()
Out[2]:
                B
A
1 count  2.000000
  mean   1.500000
  std    0.707107
  min    1.000000
  25%    1.250000
  50%    1.500000
  75%    1.750000
  max    2.000000
2 count  2.000000
  mean   3.500000
  std    0.707107
  min    3.000000
  25%    3.250000
  50%    3.500000
  75%    3.750000
  max    4.000000

In [3]: df.groupby('A').agg([np.mean, np.std, np.min, np.max])
Out[3]:
     B
  mean       std amin amax
A
1  1.5  0.707107    1    2
2  3.5  0.707107    3    4

New Behavior:

In [105]: df = pd.DataFrame({'A': [1, 1, 2, 2], 'B': [1, 2, 3, 4]})

In [106]: df.groupby('A').describe()
Out[106]: 
      B                                          
  count mean       std  min   25%  50%   75%  max
A                                                
1   2.0  1.5  0.707107  1.0  1.25  1.5  1.75  2.0
2   2.0  3.5  0.707107  3.0  3.25  3.5  3.75  4.0

In [107]: df.groupby('A').agg([np.mean, np.std, np.min, np.max])
Out[107]: 
     B                    
  mean       std amin amax
A                         
1  1.5  0.707107    1    2
2  3.5  0.707107    3    4

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 MultiIndexed DataFrame 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 Windowed Binary Operations for more information. (GH15677)

In [108]: np.random.seed(1234)

In [109]: 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 [110]: df.tail()
Out[110]: 
bar                A         B
foo                           
2016-04-05  0.640880  0.126205
2016-04-06  0.171465  0.737086
2016-04-07  0.127029  0.369650
2016-04-08  0.604334  0.103104
2016-04-09  0.802374  0.945553

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:00
Major_axis axis: A to B
Minor_axis axis: A to B

New Behavior:

In [111]: res = df.rolling(12).corr()

In [112]: res.tail()
Out[112]: 
bar                    A         B
foo        bar                    
2016-04-07 B   -0.132090  1.000000
2016-04-08 A    1.000000 -0.145775
           B   -0.145775  1.000000
2016-04-09 A    1.000000  0.119645
           B    0.119645  1.000000

Retrieving a correlation matrix for a cross-section

In [113]: df.rolling(12).corr().loc['2016-04-07']
Out[113]: 
bar                   A        B
foo        bar                  
2016-04-07 A    1.00000 -0.13209
           B   -0.13209  1.00000

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 (GH15492)

In [114]: df = pd.DataFrame({'unparsed_date': ['2014-01-01', '2014-01-01']})

In [115]: df.to_hdf('store.h5', 'key', format='table', data_columns=True)

In [116]: df.dtypes
Out[116]: 
unparsed_date    object
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 of
type <class 'pandas.tslib.Timestamp'> to string column

Index.intersection and inner join now preserve the order of the left Index

Index.intersection() now preserves the order of the calling Index (left) instead of the other Index (right) (GH15582). This affects inner joins, DataFrame.join() and merge(), and the .align method.

  • Index.intersection

    In [117]: left = pd.Index([2, 1, 0])
    
    In [118]: left
    Out[118]: Int64Index([2, 1, 0], dtype='int64')
    
    In [119]: right = pd.Index([1, 2, 3])
    
    In [120]: right
    Out[120]: Int64Index([1, 2, 3], dtype='int64')
    

    Previous Behavior:

    In [4]: left.intersection(right)
    Out[4]: Int64Index([1, 2], dtype='int64')
    

    New Behavior:

    In [121]: left.intersection(right)
    Out[121]: Int64Index([2, 1], dtype='int64')
    
  • DataFrame.join and pd.merge

    In [122]: left = pd.DataFrame({'a': [20, 10, 0]}, index=[2, 1, 0])
    
    In [123]: left
    Out[123]: 
        a
    2  20
    1  10
    0   0
    
    In [124]: right = pd.DataFrame({'b': [100, 200, 300]}, index=[1, 2, 3])
    
    In [125]: right
    Out[125]: 
         b
    1  100
    2  200
    3  300
    

    Previous Behavior:

    In [4]: left.join(right, how='inner')
    Out[4]:
        a    b
    1  10  100
    2  20  200
    

    New Behavior:

    In [126]: left.join(right, how='inner')
    Out[126]: 
        a    b
    2  20  200
    1  10  100
    

Pivot Table always returns a DataFrame

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. (GH4386)

In [127]: df = DataFrame({'col1': [3, 4, 5],
   .....:                 'col2': ['C', 'D', 'E'],
   .....:                 'col3': [1, 3, 9]})
   .....: 

In [128]: df
Out[128]: 
   col1 col2  col3
0     3    C     1
1     4    D     3
2     5    E     9

Previous Behavior:

In [2]: df.pivot_table('col1', index=['col3', 'col2'], aggfunc=np.sum)
Out[2]:
col3  col2
1     C       3
3     D       4
9     E       5
Name: col1, dtype: int64

New Behavior:

In [129]: df.pivot_table('col1', index=['col3', 'col2'], aggfunc=np.sum)
Out[129]: 
           col1
col3 col2      
1    C        3
3    D        4
9    E        5

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 (GH15213).
  • CParserError has been renamed to ParserError in pd.read_csv() and will be removed in the future (GH12665)
  • SparseArray.cumsum() and SparseSeries.cumsum() will now always return SparseArray and SparseSeries respectively (GH12855)
  • DataFrame.applymap() with an empty DataFrame will return a copy of the empty DataFrame instead of a Series (GH8222)
  • Series.map() now respects default values of dictionary subclasses with a __missing__ method, such as collections.Counter (GH15999)
  • .loc has compat with .ix for accepting iterators, and NamedTuples (GH15120)
  • interpolate() and fillna() will raise a ValueError if the limit keyword argument is not greater than 0. (GH9217)
  • pd.read_csv() will now issue a ParserWarning whenever there are conflicting values provided by the dialect parameter and the user (GH14898)
  • pd.read_csv() will now raise a ValueError for the C engine if the quote character is larger than than one byte (GH11592)
  • inplace arguments now require a boolean value, else a ValueError is thrown (GH14189)
  • 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 (GH15118)
  • Specific support for copy.copy() and copy.deepcopy() functions on NDFrame objects (GH15444)
  • Series.sort_values() accepts a one element list of bool for consistency with the behavior of DataFrame.sort_values() (GH15604)
  • .merge() and .join() on category dtype columns will now preserve the category dtype when possible (GH10409)
  • SparseDataFrame.default_fill_value will be 0, previously was nan in the return from pd.get_dummies(..., sparse=True) (GH15594)
  • 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 (GH5224). 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 (GH15781)
  • NaT will now correctly return np.nan for Timedelta and Period accessors such as days and quarter (GH15782)
  • NaT will now returns NaT for tz_localize and tz_convert methods (GH15830)
  • DataFrame and Panel constructors with invalid input will now raise ValueError rather than PandasError, if called with scalar inputs and not axes (GH15541)
  • 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. (GH15541)
  • The exception pandas.core.common.AmbiguousIndexError is removed as it is not referenced (GH15541)

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 theses modules. (GH12588)

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  
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  

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 (GH15998)
  • The type import pandas.tslib.NaTType is deprecated and can be replaced by using type(pandas.NaT) (GH16146)
  • The public functions in pandas.tools.hashing deprecated from that locations, but are now importable from pandas.util (GH16223)
  • 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 (GH16223)

pandas.errors

We are adding a standard public module for all pandas exceptions & warnings pandas.errors. (GH14800). 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. (GH15541)

The following are now part of this API:

['DtypeWarning',
 'EmptyDataError',
 'OutOfBoundsDatetime',
 'ParserError',
 'ParserWarning',
 'PerformanceWarning',
 'UnsortedIndexError',
 'UnsupportedFunctionCall']

pandas.testing

We are adding a standard module that exposes the public testing functions in pandas.testing (GH9895). Those functions can be used when writing tests for functionality using pandas objects.

The following testing functions are now part of this API:

pandas.plotting

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 (GH14831)
  • Require at least 0.23 version of cython to avoid problems with character encodings (GH14699)
  • Switched the test framework to use pytest (GH13097)
  • Reorganization of tests directory layout (GH14854, GH15707).

Deprecations

Deprecate .ix

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. To wit, .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. (GH14218)

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 [130]: df = pd.DataFrame({'A': [1, 2, 3],
   .....:                    'B': [4, 5, 6]},
   .....:                   index=list('abc'))
   .....: 

In [131]: df
Out[131]: 
   A  B
a  1  4
b  2  5
c  3  6

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    1
c    3
Name: A, dtype: int64

Using .loc. Here we will select the appropriate indexes from the index, then use label indexing.

In [132]: df.loc[df.index[[0, 2]], 'A']
Out[132]: 
a    1
c    3
Name: A, dtype: int64

Using .iloc. Here we will get the location of the ‘A’ column, then use positional indexing to select things.

In [133]: df.iloc[[0, 2], df.columns.get_loc('A')]
Out[133]: 
a    1
c    3
Name: A, 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. For more details see Deprecate Panel documentation. (GH13563).

In [134]: 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     ItemC
major      minor                              
2000-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.051539
2000-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.319561
2000-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

Convert to an xarray DataArray

In [137]: p.to_xarray()
Out[137]: 
<xarray.DataArray (items: 3, major_axis: 3, minor_axis: 4)>
array([[[ 0.628776,  0.988138, -0.938153, -0.223019],
        [ 0.186494, -0.072608, -1.239072,  2.123692],
        [ 0.952478, -0.550603,  0.139683,  0.122273]],

       [[-1.409432, -1.347533,  1.272395, -0.591863],
        [ 1.422986,  0.363565, -1.449567, -0.414505],
        [-2.147855, -0.014752, -1.195524, -1.425795]],

       [[ 0.209395, -0.896581, -0.161137, -1.051539],
        [-0.592886,  1.104352,  0.889157, -0.319561],
        [-1.473116, -0.43155 ,  0.288377, -0.619993]]])
Coordinates:
  * items       (items) object 'ItemA' 'ItemB' 'ItemC'
  * major_axis  (major_axis) datetime64[ns] 2000-01-03 2000-01-04 2000-01-05
  * minor_axis  (minor_axis) object 'A' 'B' 'C' 'D'

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’ functionaility.

  • 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 DataFrame, which accepts column-to-aggregations.
  • We are deprecating passing a dict-of-dicts to a grouped/rolled/resampled DataFrame in a similar manner.

This is an illustrative example:

In [138]: df = pd.DataFrame({'A': [1, 1, 1, 2, 2],
   .....:                    'B': range(5),
   .....:                    'C': range(5)})
   .....: 

In [139]: df
Out[139]: 
   A  B  C
0  1  0  0
1  1  1  1
2  1  2  2
3  2  3  3
4  2  4  4

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 [140]: df.groupby('A').agg({'B': 'sum', 'C': 'min'})
Out[140]: 
   B  C
A      
1  3  0
2  7  3

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 aggregation
is deprecated and will be removed in a future version

Out[6]:
   foo
A
1    3
2    2

You can accomplish the same operation, more idiomatically by:

In [141]: df.groupby('A').B.agg(['count']).rename(columns={'count': 'foo'})
Out[141]: 
   foo
A     
1    3
2    2

Here’s an example of the second deprecation, passing a dict-of-dict to a grouped DataFrame:

In [23]: (df.groupby('A')
            .agg({'B': {'foo': 'sum'}, 'C': {'bar': 'min'}})
         )
FutureWarning: using a dict with renaming is deprecated and
will be removed in a future version

Out[23]:
     B   C
   foo bar
A
1   3   0
2   7   3

You can accomplish nearly the same by:

In [142]: (df.groupby('A')
   .....:    .agg({'B': 'sum', 'C': 'min'})
   .....:    .rename(columns={'B': 'foo', 'C': 'bar'})
   .....: )
   .....: 
Out[142]: 
   foo  bar
A          
1    3    0
2    7    3

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 (GH12548).

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.scatter_matrix(df)
pd.scatter_matrix(df)

Should be changed to:

pd.plotting.scatter_matrix(df)

Other Deprecations

  • SparseArray.to_dense() has deprecated the fill parameter, as that parameter was not being respected (GH14647)
  • SparseSeries.to_dense() has deprecated the sparse_only parameter (GH14647)
  • Series.repeat() has deprecated the reps parameter in favor of repeats (GH12662)
  • The Series constructor and .astype method have deprecated accepting timestamp dtypes without a frequency (e.g. np.datetime64) for the dtype parameter (GH15524)
  • Index.repeat() and MultiIndex.repeat() have deprecated the n parameter in favor of repeats (GH12662)
  • Categorical.searchsorted() and Series.searchsorted() have deprecated the v parameter in favor of value (GH12662)
  • TimedeltaIndex.searchsorted(), DatetimeIndex.searchsorted(), and PeriodIndex.searchsorted() have deprecated the key parameter in favor of value (GH12662)
  • DataFrame.astype() has deprecated the raise_on_error parameter in favor of errors (GH14878)
  • Series.sortlevel and DataFrame.sortlevel have been deprecated in favor of Series.sort_index and DataFrame.sort_index (GH15099)
  • importing concat from pandas.tools.merge has been deprecated in favor of imports from the pandas namespace. This should only affect explict imports (GH15358)
  • Series/DataFrame/Panel.consolidate() been deprecated as a public method. (GH15483)
  • The as_indexer keyword of Series.str.match() has been deprecated (ignored keyword) (GH15257).
  • The following top-level pandas functions have been deprecated and will be removed in a future version (GH13790, GH15940)
    • 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 (GH16042)

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 (GH11308). 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 (GH13602)
  • 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 functionaility can be found in the statsmodels package. (GH11898)
  • The TimeSeries and SparseTimeSeries classes, aliases of Series and SparseSeries, are removed (GH10890, GH15098).
  • Series.is_time_series is dropped in favor of Series.index.is_all_dates (GH15098)
  • The deprecated irow, icol, iget and iget_value methods are removed in favor of iloc and iat as explained here (GH10711).
  • The deprecated DataFrame.iterkv() has been removed in favor of DataFrame.iteritems() (GH10711)
  • The Categorical constructor has dropped the name parameter (GH10632)
  • Categorical has dropped support for NaN categories (GH10748)
  • The take_last parameter has been dropped from duplicated(), drop_duplicates(), nlargest(), and nsmallest() methods (GH10236, GH10792, GH10920)
  • Series, Index, and DataFrame have dropped the sort and order methods (GH10726)
  • Where clauses in pytables are only accepted as strings and expressions types and not other data-types (GH12027)
  • DataFrame has dropped the combineAdd and combineMult methods in favor of add and mul respectively (GH10735)

Performance Improvements

  • Improved performance of pd.wide_to_long() (GH14779)
  • Improved performance of pd.factorize() by releasing the GIL with object dtype when inferred as strings (GH14859, GH16057)
  • Improved performance of timeseries plotting with an irregular DatetimeIndex (or with compat_x=True) (GH15073).
  • Improved performance of groupby().cummin() and groupby().cummax() (GH15048, GH15109, GH15561, GH15635)
  • Improved performance and reduced memory when indexing with a MultiIndex (GH15245)
  • When reading buffer object in read_sas() method without specified format, filepath string is inferred rather than buffer object. (GH14947)
  • Improved performance of .rank() for categorical data (GH15498)
  • Improved performance when using .unstack() (GH15503)
  • Improved performance of merge/join on category columns (GH10409)
  • Improved performance of drop_duplicates() on bool columns (GH12963)
  • Improve performance of pd.core.groupby.GroupBy.apply when the applied function used the .name attribute of the group DataFrame (GH15062).
  • Improved performance of iloc indexing with a list or array (GH15504).
  • Improved performance of Series.sort_index() with a monotonic index (GH15694)
  • Improved performance in pd.read_csv() on some platforms with buffered reads (GH16039)

Bug Fixes

Conversion

  • Bug in Timestamp.replace now raises TypeError when incorrect argument names are given; previously this raised ValueError (GH15240)
  • Bug in Timestamp.replace with compat for passing long integers (GH15030)
  • Bug in Timestamp returning UTC based time/date attributes when a timezone was provided (GH13303, GH6538)
  • Bug in Timestamp incorrectly localizing timezones during construction (GH11481, GH15777)
  • Bug in TimedeltaIndex addition where overflow was being allowed without error (GH14816)
  • Bug in TimedeltaIndex raising a ValueError when boolean indexing with loc (GH14946)
  • Bug in catching an overflow in Timestamp + Timedelta/Offset operations (GH15126)
  • Bug in DatetimeIndex.round() and Timestamp.round() floating point accuracy when rounding by milliseconds or less (GH14440, GH15578)
  • Bug in astype() where inf values were incorrectly converted to integers. Now raises error now with astype() for Series and DataFrames (GH14265)
  • Bug in DataFrame(..).apply(to_numeric) when values are of type decimal.Decimal. (GH14827)
  • Bug in describe() when passing a numpy array which does not contain the median to the percentiles keyword argument (GH14908)
  • Cleaned up PeriodIndex constructor, including raising on floats more consistently (GH13277)
  • Bug in using __deepcopy__ on empty NDFrame objects (GH15370)
  • Bug in .replace() may result in incorrect dtypes. (GH12747, GH15765)
  • Bug in Series.replace and DataFrame.replace which failed on empty replacement dicts (GH15289)
  • Bug in Series.replace which replaced a numeric by string (GH15743)
  • Bug in Index construction with NaN elements and integer dtype specified (GH15187)
  • Bug in Series construction with a datetimetz (GH14928)
  • Bug in Series.dt.round() inconsistent behaviour on NaT ‘s with different arguments (GH14940)
  • Bug in Series constructor when both copy=True and dtype arguments are provided (GH15125)
  • Incorrect dtyped Series was returned by comparison methods (e.g., lt, gt, ...) against a constant for an empty DataFrame (GH15077)
  • Bug in Series.ffill() with mixed dtypes containing tz-aware datetimes. (GH14956)
  • Bug in DataFrame.fillna() where the argument downcast was ignored when fillna value was of type dict (GH15277)
  • Bug in .asfreq(), where frequency was not set for empty Series (GH14320)
  • Bug in DataFrame construction with nulls and datetimes in a list-like (GH15869)
  • Bug in DataFrame.fillna() with tz-aware datetimes (GH15855)
  • Bug in is_string_dtype, is_timedelta64_ns_dtype, and is_string_like_dtype in which an error was raised when None was passed in (GH15941)
  • Bug in the return type of pd.unique on a Categorical, which was returning an ndarray and not a Categorical (GH15903)
  • Bug in Index.to_series() where the index was not copied (and so mutating later would change the original), (GH15949)
  • Bug in indexing with partial string indexing with a len-1 DataFrame (GH16071)
  • Bug in Series construction where passing invalid dtype didn’t raise an error. (GH15520)

Indexing

  • Bug in Index power operations with reversed operands (GH14973)
  • Bug in DataFrame.sort_values() when sorting by multiple columns where one column is of type int64 and contains NaT (GH14922)
  • Bug in DataFrame.reindex() in which method was ignored when passing columns (GH14992)
  • Bug in DataFrame.loc with indexing a MultiIndex with a Series indexer (GH14730, GH15424)
  • Bug in DataFrame.loc with indexing a MultiIndex with a numpy array (GH15434)
  • Bug in Series.asof which raised if the series contained all np.nan (GH15713)
  • Bug in .at when selecting from a tz-aware column (GH15822)
  • Bug in Series.where() and DataFrame.where() where array-like conditionals were being rejected (GH15414)
  • Bug in Series.where() where TZ-aware data was converted to float representation (GH15701)
  • Bug in .loc that would not return the correct dtype for scalar access for a DataFrame (GH11617)
  • Bug in output formatting of a MultiIndex when names are integers (GH12223, GH15262)
  • Bug in Categorical.searchsorted() where alphabetical instead of the provided categorical order was used (GH14522)
  • Bug in Series.iloc where a Categorical object for list-like indexes input was returned, where a Series was expected. (GH14580)
  • Bug in DataFrame.isin comparing datetimelike to empty frame (GH15473)
  • Bug in .reset_index() when an all NaN level of a MultiIndex would fail (GH6322)
  • Bug in .reset_index() when raising error for index name already present in MultiIndex columns (GH16120)
  • Bug in creating a MultiIndex with tuples and not passing a list of names; this will now raise ValueError (GH15110)
  • Bug in the HTML display with with a MultiIndex and truncation (GH14882)
  • Bug in the display of .info() where a qualifier (+) would always be displayed with a MultiIndex that contains only non-strings (GH15245)
  • 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 (GH15787)
  • Bug in DataFrame.sort_index() and Series.sort_index() where na_position doesn’t work with a MultiIndex (GH14784, GH16604)
  • Bug in in pd.concat() when combining objects with a CategoricalIndex (GH16111)
  • Bug in indexing with a scalar and a CategoricalIndex (GH16123)

I/O

  • Bug in pd.to_numeric() in which float and unsigned integer elements were being improperly casted (GH14941, GH15005)
  • Bug in pd.read_fwf() where the skiprows parameter was not being respected during column width inference (GH11256)
  • Bug in pd.read_csv() in which the dialect parameter was not being verified before processing (GH14898)
  • Bug in pd.read_csv() in which missing data was being improperly handled with usecols (GH6710)
  • 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 (GH14125)
  • Bug in pd.read_csv() for the C engine where usecols were being indexed incorrectly with parse_dates (GH14792)
  • Bug in pd.read_csv() with parse_dates when multiline headers are specified (GH15376)
  • Bug in pd.read_csv() with float_precision='round_trip' which caused a segfault when a text entry is parsed (GH15140)
  • Bug in pd.read_csv() when an index was specified and no values were specified as null values (GH15835)
  • Bug in pd.read_csv() in which certain invalid file objects caused the Python interpreter to crash (GH15337)
  • Bug in pd.read_csv() in which invalid values for nrows and chunksize were allowed (GH15767)
  • Bug in pd.read_csv() for the Python engine in which unhelpful error messages were being raised when parsing errors occurred (GH15910)
  • Bug in pd.read_csv() in which the skipfooter parameter was not being properly validated (GH15925)
  • Bug in pd.to_csv() in which there was numeric overflow when a timestamp index was being written (GH15982)
  • Bug in pd.util.hashing.hash_pandas_object() in which hashing of categoricals depended on the ordering of categories, instead of just their values. (GH15143)
  • Bug in .to_json() where lines=True and contents (keys or values) contain escaped characters (GH15096)
  • Bug in .to_json() causing single byte ascii characters to be expanded to four byte unicode (GH15344)
  • 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 (GH15716, GH15864)
  • Bug in pd.read_json() for Python 2 where lines=True and contents contain non-ascii unicode characters (GH15132)
  • Bug in pd.read_msgpack() in which Series categoricals were being improperly processed (GH14901)
  • Bug in pd.read_msgpack() which did not allow loading of a dataframe with an index of type CategoricalIndex (GH15487)
  • Bug in pd.read_msgpack() when deserializing a CategoricalIndex (GH15487)
  • Bug in DataFrame.to_records() with converting a DatetimeIndex with a timezone (GH13937)
  • Bug in DataFrame.to_records() which failed with unicode characters in column names (GH11879)
  • Bug in .to_sql() when writing a DataFrame with numeric index names (GH15404).
  • Bug in DataFrame.to_html() with index=False and max_rows raising in IndexError (GH14998)
  • Bug in pd.read_hdf() passing a Timestamp to the where parameter with a non date column (GH15492)
  • Bug in DataFrame.to_stata() and StataWriter which produces incorrectly formatted files to be produced for some locales (GH13856)
  • Bug in StataReader and StataWriter which allows invalid encodings (GH15723)
  • Bug in the Series repr not showing the length when the output was truncated (GH15962).

Plotting

  • Bug in DataFrame.hist where plt.tight_layout caused an AttributeError (use matplotlib >= 2.0.1) (GH9351)
  • Bug in DataFrame.boxplot where fontsize was not applied to the tick labels on both axes (GH15108)
  • Bug in the date and time converters pandas registers with matplotlib not handling multiple dimensions (GH16026)
  • Bug in pd.scatter_matrix() could accept either color or c, but not both (GH14855)

Groupby/Resample/Rolling

  • Bug in .groupby(..).resample() when passed the on= kwarg. (GH15021)
  • Properly set __name__ and __qualname__ for Groupby.* functions (GH14620)
  • Bug in GroupBy.get_group() failing with a categorical grouper (GH15155)
  • Bug in .groupby(...).rolling(...) when on is specified and using a DatetimeIndex (GH15130, GH13966)
  • Bug in groupby operations with timedelta64 when passing numeric_only=False (GH5724)
  • Bug in groupby.apply() coercing object dtypes to numeric types, when not all values were numeric (GH14423, GH15421, GH15670)
  • Bug in resample, where a non-string loffset argument would not be applied when resampling a timeseries (GH13218)
  • Bug in DataFrame.groupby().describe() when grouping on Index containing tuples (GH14848)
  • Bug in groupby().nunique() with a datetimelike-grouper where bins counts were incorrect (GH13453)
  • Bug in groupby.transform() that would coerce the resultant dtypes back to the original (GH10972, GH11444)
  • Bug in groupby.agg() incorrectly localizing timezone on datetime (GH15426, GH10668, GH13046)
  • Bug in .rolling/expanding() functions where count() was not counting np.Inf, nor handling object dtypes (GH12541)
  • Bug in .rolling() where pd.Timedelta or datetime.timedelta was not accepted as a window argument (GH15440)
  • Bug in Rolling.quantile function that caused a segmentation fault when called with a quantile value outside of the range [0, 1] (GH15463)
  • Bug in DataFrame.resample().median() if duplicate column names are present (GH14233)

Sparse

  • Bug in SparseSeries.reindex on single level with list of length 1 (GH15447)
  • Bug in repr-formatting a SparseDataFrame after a value was set on (a copy of) one of its series (GH15488)
  • Bug in SparseDataFrame construction with lists not coercing to dtype (GH15682)
  • Bug in sparse array indexing in which indices were not being validated (GH15863)

Reshaping

  • Bug in pd.merge_asof() where left_index or right_index caused a failure when multiple by was specified (GH15676)
  • Bug in pd.merge_asof() where left_index/right_index together caused a failure when tolerance was specified (GH15135)
  • Bug in DataFrame.pivot_table() where dropna=True would not drop all-NaN columns when the columns was a category dtype (GH15193)
  • Bug in pd.melt() where passing a tuple value for value_vars caused a TypeError (GH15348)
  • Bug in pd.pivot_table() where no error was raised when values argument was not in the columns (GH14938)
  • Bug in pd.concat() in which concatenating with an empty dataframe with join='inner' was being improperly handled (GH15328)
  • Bug with sort=True in DataFrame.join and pd.merge when joining on indexes (GH15582)
  • Bug in DataFrame.nsmallest and DataFrame.nlargest where identical values resulted in duplicated rows (GH15297)
  • Bug in pandas.pivot_table() incorrectly raising UnicodeError when passing unicode input for `margins keyword (GH13292)

Numeric

  • Bug in .rank() which incorrectly ranks ordered categories (GH15420)
  • Bug in .corr() and .cov() where the column and index were the same object (GH14617)
  • Bug in .mode() where mode was not returned if was only a single value (GH15714)
  • Bug in pd.cut() with a single bin on an all 0s array (GH15428)
  • Bug in pd.qcut() with a single quantile and an array with identical values (GH15431)
  • Bug in pandas.tools.utils.cartesian_product() with large input can cause overflow on windows (GH15265)
  • Bug in .eval() which caused multiline evals to fail with local variables not on the first line (GH15342)

Other

  • Compat with SciPy 0.19.0 for testing on .interpolate() (GH15662)
  • Compat for 32-bit platforms for .qcut/cut; bins will now be int64 dtype (GH14866)
  • Bug in interactions with Qt when a QtApplication already exists (GH14372)
  • Avoid use of np.finfo() during import pandas removed to mitigate deadlock on Python GIL misuse (GH14641)

v0.19.2 (December 24, 2016)

This is a minor bug-fix release in the 0.19.x series and includes some small regression fixes, bug fixes and performance improvements. We recommend that all users upgrade to this version.

Highlights include:

Enhancements

The pd.merge_asof(), added in 0.19.0, gained some improvements:

  • pd.merge_asof() gained left_index/right_index and left_by/right_by arguments (GH14253)
  • pd.merge_asof() can take multiple columns in by parameter and has specialized dtypes for better performace (GH13936)

Performance Improvements

  • Performance regression with PeriodIndex (GH14822)
  • Performance regression in indexing with getitem (GH14930)
  • Improved performance of .replace() (GH12745)
  • Improved performance Series creation with a datetime index and dictionary data (GH14894)

Bug Fixes

  • Compat with python 3.6 for pickling of some offsets (GH14685)
  • Compat with python 3.6 for some indexing exception types (GH14684, GH14689)
  • Compat with python 3.6 for deprecation warnings in the test suite (GH14681)
  • Compat with python 3.6 for Timestamp pickles (GH14689)
  • Compat with dateutil==2.6.0; segfault reported in the testing suite (GH14621)
  • Allow nanoseconds in Timestamp.replace as a kwarg (GH14621)
  • Bug in pd.read_csv in which aliasing was being done for na_values when passed in as a dictionary (GH14203)
  • Bug in pd.read_csv in which column indices for a dict-like na_values were not being respected (GH14203)
  • Bug in pd.read_csv where reading files fails, if the number of headers is equal to the number of lines in the file (GH14515)
  • Bug in pd.read_csv for the Python engine in which an unhelpful error message was being raised when multi-char delimiters were not being respected with quotes (GH14582)
  • Fix bugs (GH14734, GH13654) in pd.read_sas and pandas.io.sas.sas7bdat.SAS7BDATReader that caused problems when reading a SAS file incrementally.
  • Bug in pd.read_csv for the Python engine in which an unhelpful error message was being raised when skipfooter was not being respected by Python’s CSV library (GH13879)
  • Bug in .fillna() in which timezone aware datetime64 values were incorrectly rounded (GH14872)
  • Bug in .groupby(..., sort=True) of a non-lexsorted MultiIndex when grouping with multiple levels (GH14776)
  • Bug in pd.cut with negative values and a single bin (GH14652)
  • Bug in pd.to_numeric where a 0 was not unsigned on a downcast='unsigned' argument (GH14401)
  • Bug in plotting regular and irregular timeseries using shared axes (sharex=True or ax.twinx()) (GH13341, GH14322).
  • Bug in not propogating exceptions in parsing invalid datetimes, noted in python 3.6 (GH14561)
  • Bug in resampling a DatetimeIndex in local TZ, covering a DST change, which would raise AmbiguousTimeError (GH14682)
  • Bug in indexing that transformed RecursionError into KeyError or IndexingError (GH14554)
  • Bug in HDFStore when writing a MultiIndex when using data_columns=True (GH14435)
  • Bug in HDFStore.append() when writing a Series and passing a min_itemsize argument containing a value for the index (GH11412)
  • Bug when writing to a HDFStore in table format with a min_itemsize value for the index and without asking to append (GH10381)
  • Bug in Series.groupby.nunique() raising an IndexError for an empty Series (GH12553)
  • Bug in DataFrame.nlargest and DataFrame.nsmallest when the index had duplicate values (GH13412)
  • Bug in clipboard functions on linux with python2 with unicode and separators (GH13747)
  • Bug in clipboard functions on Windows 10 and python 3 (GH14362, GH12807)
  • Bug in .to_clipboard() and Excel compat (GH12529)
  • Bug in DataFrame.combine_first() for integer columns (GH14687).
  • Bug in pd.read_csv() in which the dtype parameter was not being respected for empty data (GH14712)
  • Bug in pd.read_csv() in which the nrows parameter was not being respected for large input when using the C engine for parsing (GH7626)
  • Bug in pd.merge_asof() could not handle timezone-aware DatetimeIndex when a tolerance was specified (GH14844)
  • Explicit check in to_stata and StataWriter for out-of-range values when writing doubles (GH14618)
  • Bug in .plot(kind='kde') which did not drop missing values to generate the KDE Plot, instead generating an empty plot. (GH14821)
  • Bug in unstack() if called with a list of column(s) as an argument, regardless of the dtypes of all columns, they get coerced to object (GH11847)

v0.19.1 (November 3, 2016)

This is a minor bug-fix release from 0.19.0 and includes some small regression fixes, bug fixes and performance improvements. We recommend that all users upgrade to this version.

What’s new in v0.19.1

Performance Improvements

  • Fixed performance regression in factorization of Period data (GH14338)
  • Fixed performance regression in Series.asof(where) when where is a scalar (GH14461)
  • Improved performance in DataFrame.asof(where) when where is a scalar (GH14461)
  • Improved performance in .to_json() when lines=True (GH14408)
  • Improved performance in certain types of loc indexing with a MultiIndex (GH14551).

Bug Fixes

  • Source installs from PyPI will now again work without cython installed, as in previous versions (GH14204)
  • Compat with Cython 0.25 for building (GH14496)
  • Fixed regression where user-provided file handles were closed in read_csv (c engine) (GH14418).
  • Fixed regression in DataFrame.quantile when missing values where present in some columns (GH14357).
  • Fixed regression in Index.difference where the freq of a DatetimeIndex was incorrectly set (GH14323)
  • Added back pandas.core.common.array_equivalent with a deprecation warning (GH14555).
  • Bug in pd.read_csv for the C engine in which quotation marks were improperly parsed in skipped rows (GH14459)
  • Bug in pd.read_csv for Python 2.x in which Unicode quote characters were no longer being respected (GH14477)
  • Fixed regression in Index.append when categorical indices were appended (GH14545).
  • Fixed regression in pd.DataFrame where constructor fails when given dict with None value (GH14381)
  • Fixed regression in DatetimeIndex._maybe_cast_slice_bound when index is empty (GH14354).
  • Bug in localizing an ambiguous timezone when a boolean is passed (GH14402)
  • Bug in TimedeltaIndex addition with a Datetime-like object where addition overflow in the negative direction was not being caught (GH14068, GH14453)
  • Bug in string indexing against data with object Index may raise AttributeError (GH14424)
  • Corrrecly raise ValueError on empty input to pd.eval() and df.query() (GH13139)
  • Bug in RangeIndex.intersection when result is a empty set (GH14364).
  • Bug in groupby-transform broadcasting that could cause incorrect dtype coercion (GH14457)
  • Bug in Series.__setitem__ which allowed mutating read-only arrays (GH14359).
  • Bug in DataFrame.insert where multiple calls with duplicate columns can fail (GH14291)
  • pd.merge() will raise ValueError with non-boolean parameters in passed boolean type arguments (GH14434)
  • Bug in Timestamp where dates very near the minimum (1677-09) could underflow on creation (GH14415)
  • Bug in pd.concat where names of the keys were not propagated to the resulting MultiIndex (GH14252)
  • Bug in pd.concat where axis cannot take string parameters 'rows' or 'columns' (GH14369)
  • Bug in pd.concat with dataframes heterogeneous in length and tuple keys (GH14438)
  • Bug in MultiIndex.set_levels where illegal level values were still set after raising an error (GH13754)
  • Bug in DataFrame.to_json where lines=True and a value contained a } character (GH14391)
  • Bug in df.groupby causing an AttributeError when grouping a single index frame by a column and the index level (:issue`14327`)
  • Bug in df.groupby where TypeError raised when pd.Grouper(key=...) is passed in a list (GH14334)
  • Bug in pd.pivot_table may raise TypeError or ValueError when index or columns is not scalar and values is not specified (GH14380)

v0.19.0 (October 2, 2016)

This is a major release from 0.18.1 and includes number of API changes, several 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:

  • merge_asof() for asof-style time-series joining, see here
  • .rolling() is now time-series aware, see here
  • read_csv() now supports parsing Categorical data, see here
  • A function union_categorical() has been added for combining categoricals, see here
  • PeriodIndex now has its own period dtype, and changed to be more consistent with other Index classes. See here
  • Sparse data structures gained enhanced support of int and bool dtypes, see here
  • Comparison operations with Series no longer ignores the index, see here for an overview of the API changes.
  • Introduction of a pandas development API for utility functions, see here.
  • Deprecation of Panel4D and PanelND. We recommend to represent these types of n-dimensional data with the xarray package.
  • Removal of the previously deprecated modules pandas.io.data, pandas.io.wb, pandas.tools.rplot.

Warning

pandas >= 0.19.0 will no longer silence numpy ufunc warnings upon import, see here.

New features

merge_asof for asof-style time-series joining

A long-time requested feature has been added through the merge_asof() function, to support asof style joining of time-series (GH1870, GH13695, GH13709, GH13902). Full documentation is here.

The merge_asof() performs an asof merge, which is similar to a left-join except that we match on nearest key rather than equal keys.

In [1]: left = pd.DataFrame({'a': [1, 5, 10],
   ...:                      'left_val': ['a', 'b', 'c']})
   ...: 

In [2]: right = pd.DataFrame({'a': [1, 2, 3, 6, 7],
   ...:                      'right_val': [1, 2, 3, 6, 7]})
   ...: 

In [3]: left
Out[3]: 
    a left_val
0   1        a
1   5        b
2  10        c

In [4]: right
Out[4]: 
   a  right_val
0  1          1
1  2          2
2  3          3
3  6          6
4  7          7

We typically want to match exactly when possible, and use the most recent value otherwise.

In [5]: pd.merge_asof(left, right, on='a')
Out[5]: 
    a left_val  right_val
0   1        a          1
1   5        b          3
2  10        c          7

We can also match rows ONLY with prior data, and not an exact match.

In [6]: pd.merge_asof(left, right, on='a', allow_exact_matches=False)
Out[6]: 
    a left_val  right_val
0   1        a        NaN
1   5        b        3.0
2  10        c        7.0

In a typical time-series example, we have trades and quotes and we want to asof-join them. This also illustrates using the by parameter to group data before merging.

In [7]: trades = pd.DataFrame({
   ...:     'time': pd.to_datetime(['20160525 13:30:00.023',
   ...:                             '20160525 13:30:00.038',
   ...:                             '20160525 13:30:00.048',
   ...:                             '20160525 13:30:00.048',
   ...:                             '20160525 13:30:00.048']),
   ...:     'ticker': ['MSFT', 'MSFT',
   ...:                'GOOG', 'GOOG', 'AAPL'],
   ...:     'price': [51.95, 51.95,
   ...:               720.77, 720.92, 98.00],
   ...:     'quantity': [75, 155,
   ...:                  100, 100, 100]},
   ...:     columns=['time', 'ticker', 'price', 'quantity'])
   ...: 

In [8]: quotes = pd.DataFrame({
   ...:     'time': pd.to_datetime(['20160525 13:30:00.023',
   ...:                             '20160525 13:30:00.023',
   ...:                             '20160525 13:30:00.030',
   ...:                             '20160525 13:30:00.041',
   ...:                             '20160525 13:30:00.048',
   ...:                             '20160525 13:30:00.049',
   ...:                             '20160525 13:30:00.072',
   ...:                             '20160525 13:30:00.075']),
   ...:     'ticker': ['GOOG', 'MSFT', 'MSFT',
   ...:                'MSFT', 'GOOG', 'AAPL', 'GOOG',
   ...:                'MSFT'],
   ...:     'bid': [720.50, 51.95, 51.97, 51.99,
   ...:             720.50, 97.99, 720.50, 52.01],
   ...:     'ask': [720.93, 51.96, 51.98, 52.00,
   ...:             720.93, 98.01, 720.88, 52.03]},
   ...:     columns=['time', 'ticker', 'bid', 'ask'])
   ...: 
In [9]: trades
Out[9]: 
                     time ticker   price  quantity
0 2016-05-25 13:30:00.023   MSFT   51.95        75
1 2016-05-25 13:30:00.038   MSFT   51.95       155
2 2016-05-25 13:30:00.048   GOOG  720.77       100
3 2016-05-25 13:30:00.048   GOOG  720.92       100
4 2016-05-25 13:30:00.048   AAPL   98.00       100

In [10]: quotes
Out[10]: 
                     time ticker     bid     ask
0 2016-05-25 13:30:00.023   GOOG  720.50  720.93
1 2016-05-25 13:30:00.023   MSFT   51.95   51.96
2 2016-05-25 13:30:00.030   MSFT   51.97   51.98
3 2016-05-25 13:30:00.041   MSFT   51.99   52.00
4 2016-05-25 13:30:00.048   GOOG  720.50  720.93
5 2016-05-25 13:30:00.049   AAPL   97.99   98.01
6 2016-05-25 13:30:00.072   GOOG  720.50  720.88
7 2016-05-25 13:30:00.075   MSFT   52.01   52.03

An asof merge joins on the on, typically a datetimelike field, which is ordered, and in this case we are using a grouper in the by field. This is like a left-outer join, except that forward filling happens automatically taking the most recent non-NaN value.

In [11]: pd.merge_asof(trades, quotes,
   ....:               on='time',
   ....:               by='ticker')
   ....: 
Out[11]: 
                     time ticker   price  quantity     bid     ask
0 2016-05-25 13:30:00.023   MSFT   51.95        75   51.95   51.96
1 2016-05-25 13:30:00.038   MSFT   51.95       155   51.97   51.98
2 2016-05-25 13:30:00.048   GOOG  720.77       100  720.50  720.93
3 2016-05-25 13:30:00.048   GOOG  720.92       100  720.50  720.93
4 2016-05-25 13:30:00.048   AAPL   98.00       100     NaN     NaN

This returns a merged DataFrame with the entries in the same order as the original left passed DataFrame (trades in this case), with the fields of the quotes merged.

.rolling() is now time-series aware

.rolling() objects are now time-series aware and can accept a time-series offset (or convertible) for the window argument (GH13327, GH12995). See the full documentation here.

In [12]: dft = pd.DataFrame({'B': [0, 1, 2, np.nan, 4]},
   ....:                    index=pd.date_range('20130101 09:00:00', periods=5, freq='s'))
   ....: 

In [13]: dft
Out[13]: 
                       B
2013-01-01 09:00:00  0.0
2013-01-01 09:00:01  1.0
2013-01-01 09:00:02  2.0
2013-01-01 09:00:03  NaN
2013-01-01 09:00:04  4.0

This is a regular frequency index. Using an integer window parameter works to roll along the window frequency.

In [14]: dft.rolling(2).sum()
Out[14]: 
                       B
2013-01-01 09:00:00  NaN
2013-01-01 09:00:01  1.0
2013-01-01 09:00:02  3.0
2013-01-01 09:00:03  NaN
2013-01-01 09:00:04  NaN

In [15]: dft.rolling(2, min_periods=1).sum()
Out[15]: 
                       B
2013-01-01 09:00:00  0.0
2013-01-01 09:00:01  1.0
2013-01-01 09:00:02  3.0
2013-01-01 09:00:03  2.0
2013-01-01 09:00:04  4.0

Specifying an offset allows a more intuitive specification of the rolling frequency.

In [16]: dft.rolling('2s').sum()
Out[16]: 
                       B
2013-01-01 09:00:00  0.0
2013-01-01 09:00:01  1.0
2013-01-01 09:00:02  3.0
2013-01-01 09:00:03  2.0
2013-01-01 09:00:04  4.0

Using a non-regular, but still monotonic index, rolling with an integer window does not impart any special calculation.

In [17]: dft = DataFrame({'B': [0, 1, 2, np.nan, 4]},
   ....:                 index = pd.Index([pd.Timestamp('20130101 09:00:00'),
   ....:                                   pd.Timestamp('20130101 09:00:02'),
   ....:                                   pd.Timestamp('20130101 09:00:03'),
   ....:                                   pd.Timestamp('20130101 09:00:05'),
   ....:                                   pd.Timestamp('20130101 09:00:06')],
   ....:                                  name='foo'))
   ....: 

In [18]: dft
Out[18]: 
                       B
foo                     
2013-01-01 09:00:00  0.0
2013-01-01 09:00:02  1.0
2013-01-01 09:00:03  2.0
2013-01-01 09:00:05  NaN
2013-01-01 09:00:06  4.0

In [19]: dft.rolling(2).sum()
Out[19]: 
                       B
foo                     
2013-01-01 09:00:00  NaN
2013-01-01 09:00:02  1.0
2013-01-01 09:00:03  3.0
2013-01-01 09:00:05  NaN
2013-01-01 09:00:06  NaN

Using the time-specification generates variable windows for this sparse data.

In [20]: dft.rolling('2s').sum()
Out[20]: 
                       B
foo                     
2013-01-01 09:00:00  0.0
2013-01-01 09:00:02  1.0
2013-01-01 09:00:03  3.0
2013-01-01 09:00:05  NaN
2013-01-01 09:00:06  4.0

Furthermore, we now allow an optional on parameter to specify a column (rather than the default of the index) in a DataFrame.

In [21]: dft = dft.reset_index()

In [22]: dft
Out[22]: 
                  foo    B
0 2013-01-01 09:00:00  0.0
1 2013-01-01 09:00:02  1.0
2 2013-01-01 09:00:03  2.0
3 2013-01-01 09:00:05  NaN
4 2013-01-01 09:00:06  4.0

In [23]: dft.rolling('2s', on='foo').sum()
Out[23]: 
                  foo    B
0 2013-01-01 09:00:00  0.0
1 2013-01-01 09:00:02  1.0
2 2013-01-01 09:00:03  3.0
3 2013-01-01 09:00:05  NaN
4 2013-01-01 09:00:06  4.0

read_csv has improved support for duplicate column names

Duplicate column names are now supported in read_csv() whether they are in the file or passed in as the names parameter (GH7160, GH9424)

In [24]: data = '0,1,2\n3,4,5'

In [25]: names = ['a', 'b', 'a']

Previous behavior:

In [2]: pd.read_csv(StringIO(data), names=names)
Out[2]:
   a  b  a
0  2  1  2
1  5  4  5

The first a column contained the same data as the second a column, when it should have contained the values [0, 3].

New behavior:

In [26]: pd.read_csv(StringIO(data), names=names)
Out[26]: 
   a  b  a.1
0  0  1    2
1  3  4    5

read_csv supports parsing Categorical directly

The read_csv() function now supports parsing a Categorical column when specified as a dtype (GH10153). Depending on the structure of the data, this can result in a faster parse time and lower memory usage compared to converting to Categorical after parsing. See the io docs here.

In [27]: data = 'col1,col2,col3\na,b,1\na,b,2\nc,d,3'

In [28]: pd.read_csv(StringIO(data))
Out[28]: 
  col1 col2  col3
0    a    b     1
1    a    b     2
2    c    d     3

In [29]: pd.read_csv(StringIO(data)).dtypes
Out[29]: 
col1    object
col2    object
col3     int64
dtype: object

In [30]: pd.read_csv(StringIO(data), dtype='category').dtypes
Out[30]: 
col1    category
col2    category
col3    category
dtype: object

Individual columns can be parsed as a Categorical using a dict specification

In [31]: pd.read_csv(StringIO(data), dtype={'col1': 'category'}).dtypes
Out[31]: 
col1    category
col2      object
col3       int64
dtype: object

Note

The resulting categories will always be parsed as strings (object dtype). If the categories are numeric they can be converted using the to_numeric() function, or as appropriate, another converter such as to_datetime().

In [32]: df = pd.read_csv(StringIO(data), dtype='category')

In [33]: df.dtypes
Out[33]: 
col1    category
col2    category
col3    category
dtype: object

In [34]: df['col3']
Out[34]: 
0    1
1    2
2    3
Name: col3, dtype: category
Categories (3, object): [1, 2, 3]

In [35]: df['col3'].cat.categories = pd.to_numeric(df['col3'].cat.categories)

In [36]: df['col3']
Out[36]: 
0    1
1    2
2    3
Name: col3, dtype: category
Categories (3, int64): [1, 2, 3]

Categorical Concatenation

  • A function union_categoricals() has been added for combining categoricals, see Unioning Categoricals (GH13361, GH:13763, issue:13846, GH14173)

    In [37]: from pandas.api.types import union_categoricals
    
    In [38]: a = pd.Categorical(["b", "c"])
    
    In [39]: b = pd.Categorical(["a", "b"])
    
    In [40]: union_categoricals([a, b])
    Out[40]: 
    [b, c, a, b]
    Categories (3, object): [b, c, a]
    
  • concat and append now can concat category dtypes with different categories as object dtype (GH13524)

    In [41]: s1 = pd.Series(['a', 'b'], dtype='category')
    
    In [42]: s2 = pd.Series(['b', 'c'], dtype='category')
    

    Previous behavior:

    In [1]: pd.concat([s1, s2])
    ValueError: incompatible categories in categorical concat
    

    New behavior:

    In [43]: pd.concat([s1, s2])
    Out[43]: 
    0    a
    1    b
    0    b
    1    c
    dtype: object
    

Semi-Month Offsets

Pandas has gained new frequency offsets, SemiMonthEnd (‘SM’) and SemiMonthBegin (‘SMS’). These provide date offsets anchored (by default) to the 15th and end of month, and 15th and 1st of month respectively. (GH1543)

In [44]: from pandas.tseries.offsets import SemiMonthEnd, SemiMonthBegin

SemiMonthEnd:

In [45]: Timestamp('2016-01-01') + SemiMonthEnd()
Out[45]: Timestamp('2016-01-15 00:00:00')

In [46]: pd.date_range('2015-01-01', freq='SM', periods=4)
Out[46]: DatetimeIndex(['2015-01-15', '2015-01-31', '2015-02-15', '2015-02-28'], dtype='datetime64[ns]', freq='SM-15')

SemiMonthBegin:

In [47]: Timestamp('2016-01-01') + SemiMonthBegin()
Out[47]: Timestamp('2016-01-15 00:00:00')

In [48]: pd.date_range('2015-01-01', freq='SMS', periods=4)
Out[48]: DatetimeIndex(['2015-01-01', '2015-01-15', '2015-02-01', '2015-02-15'], dtype='datetime64[ns]', freq='SMS-15')

Using the anchoring suffix, you can also specify the day of month to use instead of the 15th.

In [49]: pd.date_range('2015-01-01', freq='SMS-16', periods=4)
Out[49]: DatetimeIndex(['2015-01-01', '2015-01-16', '2015-02-01', '2015-02-16'], dtype='datetime64[ns]', freq='SMS-16')

In [50]: pd.date_range('2015-01-01', freq='SM-14', periods=4)
Out[50]: DatetimeIndex(['2015-01-14', '2015-01-31', '2015-02-14', '2015-02-28'], dtype='datetime64[ns]', freq='SM-14')

New Index methods

The following methods and options are added to Index, to be more consistent with the Series and DataFrame API.

Index now supports the .where() function for same shape indexing (GH13170)

In [51]: idx = pd.Index(['a', 'b', 'c'])

In [52]: idx.where([True, False, True])
Out[52]: Index(['a', nan, 'c'], dtype='object')

Index now supports .dropna() to exclude missing values (GH6194)

In [53]: idx = pd.Index([1, 2, np.nan, 4])

In [54]: idx.dropna()
Out[54]: Float64Index([1.0, 2.0, 4.0], dtype='float64')

For MultiIndex, values are dropped if any level is missing by default. Specifying how='all' only drops values where all levels are missing.

In [55]: midx = pd.MultiIndex.from_arrays([[1, 2, np.nan, 4],
   ....:                                     [1, 2, np.nan, np.nan]])
   ....: 

In [56]: midx
Out[56]: 
MultiIndex(levels=[[1, 2, 4], [1, 2]],
           labels=[[0, 1, -1, 2], [0, 1, -1, -1]])

In [57]: midx.dropna()
Out[57]: 
MultiIndex(levels=[[1, 2, 4], [1, 2]],
           labels=[[0, 1], [0, 1]])

In [58]: midx.dropna(how='all')
Out[58]: 
MultiIndex(levels=[[1, 2, 4], [1, 2]],
           labels=[[0, 1, 2], [0, 1, -1]])

Index now supports .str.extractall() which returns a DataFrame, see the docs here (GH10008, GH13156)

In [59]: idx = pd.Index(["a1a2", "b1", "c1"])

In [60]: idx.str.extractall("[ab](?P<digit>\d)")
Out[60]: 
        digit
  match      
0 0         1
  1         2
1 0         1

Index.astype() now accepts an optional boolean argument copy, which allows optional copying if the requirements on dtype are satisfied (GH13209)

Google BigQuery Enhancements

  • The read_gbq() method has gained the dialect argument to allow users to specify whether to use BigQuery’s legacy SQL or BigQuery’s standard SQL. See the docs for more details (GH13615).
  • The to_gbq() method now allows the DataFrame column order to differ from the destination table schema (GH11359).

Fine-grained numpy errstate

Previous versions of pandas would permanently silence numpy’s ufunc error handling when pandas was imported. Pandas did this in order to silence the warnings that would arise from using numpy ufuncs on missing data, which are usually represented as NaN s. Unfortunately, this silenced legitimate warnings arising in non-pandas code in the application. Starting with 0.19.0, pandas will use the numpy.errstate context manager to silence these warnings in a more fine-grained manner, only around where these operations are actually used in the pandas codebase. (GH13109, GH13145)

After upgrading pandas, you may see new RuntimeWarnings being issued from your code. These are likely legitimate, and the underlying cause likely existed in the code when using previous versions of pandas that simply silenced the warning. Use numpy.errstate around the source of the RuntimeWarning to control how these conditions are handled.

get_dummies now returns integer dtypes

The pd.get_dummies function now returns dummy-encoded columns as small integers, rather than floats (GH8725). This should provide an improved memory footprint.

Previous behavior:

In [1]: pd.get_dummies(['a', 'b', 'a', 'c']).dtypes

Out[1]:
a    float64
b    float64
c    float64
dtype: object

New behavior:

In [61]: pd.get_dummies(['a', 'b', 'a', 'c']).dtypes
Out[61]: 
a    uint8
b    uint8
c    uint8
dtype: object

Downcast values to smallest possible dtype in to_numeric

pd.to_numeric() now accepts a downcast parameter, which will downcast the data if possible to smallest specified numerical dtype (GH13352)

In [62]: s = ['1', 2, 3]

In [63]: pd.to_numeric(s, downcast='unsigned')
Out[63]: array([1, 2, 3], dtype=uint8)

In [64]: pd.to_numeric(s, downcast='integer')
Out[64]: array([1, 2, 3], dtype=int8)

pandas development API

As part of making pandas API more uniform and accessible in the future, we have created a standard sub-package of pandas, pandas.api to hold public API’s. We are starting by exposing type introspection functions in pandas.api.types. More sub-packages and officially sanctioned API’s will be published in future versions of pandas (GH13147, GH13634)

The following are now part of this API:

In [65]: import pprint

In [66]: from pandas.api import types

In [67]: funcs = [ f for f in dir(types) if not f.startswith('_') ]

In [68]: pprint.pprint(funcs)
['CategoricalDtype',
 'DatetimeTZDtype',
 'IntervalDtype',
 'PeriodDtype',
 'infer_dtype',
 'is_any_int_dtype',
 'is_bool',
 'is_bool_dtype',
 'is_categorical',
 'is_categorical_dtype',
 'is_complex',
 'is_complex_dtype',
 'is_datetime64_any_dtype',
 'is_datetime64_dtype',
 'is_datetime64_ns_dtype',
 'is_datetime64tz_dtype',
 'is_datetimetz',
 'is_dict_like',
 'is_dtype_equal',
 'is_extension_type',
 'is_file_like',
 'is_float',
 'is_float_dtype',
 'is_floating_dtype',
 'is_hashable',
 'is_int64_dtype',
 'is_integer',
 'is_integer_dtype',
 'is_interval',
 'is_interval_dtype',
 'is_iterator',
 'is_list_like',
 'is_named_tuple',
 'is_number',
 'is_numeric_dtype',
 'is_object_dtype',
 'is_period',
 'is_period_dtype',
 'is_re',
 'is_re_compilable',
 'is_scalar',
 'is_sequence',
 'is_signed_integer_dtype',
 'is_sparse',
 'is_string_dtype',
 'is_timedelta64_dtype',
 'is_timedelta64_ns_dtype',
 'is_unsigned_integer_dtype',
 'pandas_dtype',
 'union_categoricals']

Note

Calling these functions from the internal module pandas.core.common will now show a DeprecationWarning (GH13990)

Other enhancements

  • Timestamp can now accept positional and keyword parameters similar to datetime.datetime() (GH10758, GH11630)

    In [69]: pd.Timestamp(2012, 1, 1)
    Out[69]: Timestamp('2012-01-01 00:00:00')
    
    In [70]: pd.Timestamp(year=2012, month=1, day=1, hour=8, minute=30)
    Out[70]: Timestamp('2012-01-01 08:30:00')
    
  • The .resample() function now accepts a on= or level= parameter for resampling on a datetimelike column or MultiIndex level (GH13500)

    In [71]: df = pd.DataFrame({'date': pd.date_range('2015-01-01', freq='W', periods=5),
       ....:                    'a': np.arange(5)},
       ....:                   index=pd.MultiIndex.from_arrays([
       ....:                            [1,2,3,4,5],
       ....:                            pd.date_range('2015-01-01', freq='W', periods=5)],
       ....:                        names=['v','d']))
       ....: 
    
    In [72]: df
    Out[72]: 
                  a       date
    v d                       
    1 2015-01-04  0 2015-01-04
    2 2015-01-11  1 2015-01-11
    3 2015-01-18  2 2015-01-18
    4 2015-01-25  3 2015-01-25
    5 2015-02-01  4 2015-02-01
    
    In [73]: df.resample('M', on='date').sum()
    Out[73]: 
                a
    date         
    2015-01-31  6
    2015-02-28  4
    
    In [74]: df.resample('M', level='d').sum()
    Out[74]: 
                a
    d            
    2015-01-31  6
    2015-02-28  4
    
  • The .get_credentials() method of GbqConnector can now first try to fetch the application default credentials. See the docs for more details (GH13577).

  • The .tz_localize() method of DatetimeIndex and Timestamp has gained the errors keyword, so you can potentially coerce nonexistent timestamps to NaT. The default behavior remains to raising a NonExistentTimeError (GH13057)

  • .to_hdf/read_hdf() now accept path objects (e.g. pathlib.Path, py.path.local) for the file path (GH11773)

  • The pd.read_csv() with engine='python' has gained support for the decimal (GH12933), na_filter (GH13321) and the memory_map option (GH13381).

  • Consistent with the Python API, pd.read_csv() will now interpret +inf as positive infinity (GH13274)

  • The pd.read_html() has gained support for the na_values, converters, keep_default_na options (GH13461)

  • Categorical.astype() now accepts an optional boolean argument copy, effective when dtype is categorical (GH13209)

  • DataFrame has gained the .asof() method to return the last non-NaN values according to the selected subset (GH13358)

  • The DataFrame constructor will now respect key ordering if a list of OrderedDict objects are passed in (GH13304)

  • pd.read_html() has gained support for the decimal option (GH12907)

  • Series has gained the properties .is_monotonic, .is_monotonic_increasing, .is_monotonic_decreasing, similar to Index (GH13336)

  • DataFrame.to_sql() now allows a single value as the SQL type for all columns (GH11886).

  • Series.append now supports the ignore_index option (GH13677)

  • .to_stata() and StataWriter can now write variable labels to Stata dta files using a dictionary to make column names to labels (GH13535, GH13536)

  • .to_stata() and StataWriter will automatically convert datetime64[ns] columns to Stata format %tc, rather than raising a ValueError (GH12259)

  • read_stata() and StataReader raise with a more explicit error message when reading Stata files with repeated value labels when convert_categoricals=True (GH13923)

  • DataFrame.style will now render sparsified MultiIndexes (GH11655)

  • DataFrame.style will now show column level names (e.g. DataFrame.columns.names) (GH13775)

  • DataFrame has gained support to re-order the columns based on the values in a row using df.sort_values(by='...', axis=1) (GH10806)

    In [75]: df = pd.DataFrame({'A': [2, 7], 'B': [3, 5], 'C': [4, 8]},
       ....:                   index=['row1', 'row2'])
       ....: 
    
    In [76]: df
    Out[76]: 
          A  B  C
    row1  2  3  4
    row2  7  5  8
    
    In [77]: df.sort_values(by='row2', axis=1)
    Out[77]: 
          B  A  C
    row1  3  2  4
    row2  5  7  8
    
  • Added documentation to I/O regarding the perils of reading in columns with mixed dtypes and how to handle it (GH13746)

  • to_html() now has a border argument to control the value in the opening <table> tag. The default is the value of the html.border option, which defaults to 1. This also affects the notebook HTML repr, but since Jupyter’s CSS includes a border-width attribute, the visual effect is the same. (GH11563).

  • Raise ImportError in the sql functions when sqlalchemy is not installed and a connection string is used (GH11920).

  • Compatibility with matplotlib 2.0. Older versions of pandas should also work with matplotlib 2.0 (GH13333)

  • Timestamp, Period, DatetimeIndex, PeriodIndex and .dt accessor have gained a .is_leap_year property to check whether the date belongs to a leap year. (GH13727)

  • astype() will now accept a dict of column name to data types mapping as the dtype argument. (GH12086)

  • The pd.read_json and DataFrame.to_json has gained support for reading and writing json lines with lines option see Line delimited json (GH9180)

  • read_excel() now supports the true_values and false_values keyword arguments (GH13347)

  • groupby() will now accept a scalar and a single-element list for specifying level on a non-MultiIndex grouper. (GH13907)

  • Non-convertible dates in an excel date column will be returned without conversion and the column will be object dtype, rather than raising an exception (GH10001).

  • pd.Timedelta(None) is now accepted and will return NaT, mirroring pd.Timestamp (GH13687)

  • pd.read_stata() can now handle some format 111 files, which are produced by SAS when generating Stata dta files (GH11526)

  • Series and Index now support divmod which will return a tuple of series or indices. This behaves like a standard binary operator with regards to broadcasting rules (GH14208).

API changes

Series.tolist() will now return Python types

Series.tolist() will now return Python types in the output, mimicking NumPy .tolist() behavior (GH10904)

In [78]: s = pd.Series([1,2,3])

Previous behavior:

In [7]: type(s.tolist()[0])
Out[7]:
 <class 'numpy.int64'>

New behavior:

In [79]: type(s.tolist()[0])
Out[79]: int

Series operators for different indexes

Following Series operators have been changed to make all operators consistent, including DataFrame (GH1134, GH4581, GH13538)

  • Series comparison operators now raise ValueError when index are different.
  • Series logical operators align both index of left and right hand side.

Warning

Until 0.18.1, comparing Series with the same length, would succeed even if the .index are different (the result ignores .index). As of 0.19.0, this will raises ValueError to be more strict. This section also describes how to keep previous behavior or align different indexes, using the flexible comparison methods like .eq.

As a result, Series and DataFrame operators behave as below:

Arithmetic operators

Arithmetic operators align both index (no changes).

In [80]: s1 = pd.Series([1, 2, 3], index=list('ABC'))

In [81]: s2 = pd.Series([2, 2, 2], index=list('ABD'))

In [82]: s1 + s2
Out[82]: 
A    3.0
B    4.0
C    NaN
D    NaN
dtype: float64

In [83]: df1 = pd.DataFrame([1, 2, 3], index=list('ABC'))

In [84]: df2 = pd.DataFrame([2, 2, 2], index=list('ABD'))

In [85]: df1 + df2
Out[85]: 
     0
A  3.0
B  4.0
C  NaN
D  NaN
Comparison operators

Comparison operators raise ValueError when .index are different.

Previous Behavior (Series):

Series compared values ignoring the .index as long as both had the same length:

In [1]: s1 == s2
Out[1]:
A    False
B     True
C    False
dtype: bool

New behavior (Series):

In [2]: s1 == s2
Out[2]:
ValueError: Can only compare identically-labeled Series objects

Note

To achieve the same result as previous versions (compare values based on locations ignoring .index), compare both .values.

In [86]: s1.values == s2.values
Out[86]: array([False,  True, False], dtype=bool)

If you want to compare Series aligning its .index, see flexible comparison methods section below:

In [87]: s1.eq(s2)
Out[87]: 
A    False
B     True
C    False
D    False
dtype: bool

Current Behavior (DataFrame, no change):

In [3]: df1 == df2
Out[3]:
ValueError: Can only compare identically-labeled DataFrame objects
Logical operators

Logical operators align both .index of left and right hand side.

Previous behavior (Series), only left hand side index was kept:

In [4]: s1 = pd.Series([True, False, True], index=list('ABC'))
In [5]: s2 = pd.Series([True, True, True], index=list('ABD'))
In [6]: s1 & s2
Out[6]:
A     True
B    False
C    False
dtype: bool

New behavior (Series):

In [88]: s1 = pd.Series([True, False, True], index=list('ABC'))

In [89]: s2 = pd.Series([True, True, True], index=list('ABD'))

In [90]: s1 & s2
Out[90]: 
A     True
B    False
C    False
D    False
dtype: bool

Note

Series logical operators fill a NaN result with False.

Note

To achieve the same result as previous versions (compare values based on only left hand side index), you can use reindex_like:

In [91]: s1 & s2.reindex_like(s1)
Out[91]: 
A     True
B    False
C    False
dtype: bool

Current Behavior (DataFrame, no change):

In [92]: df1 = pd.DataFrame([True, False, True], index=list('ABC'))

In [93]: df2 = pd.DataFrame([True, True, True], index=list('ABD'))

In [94]: df1 & df2
Out[94]: 
       0
A   True
B  False
C    NaN
D    NaN
Flexible comparison methods

Series flexible comparison methods like eq, ne, le, lt, ge and gt now align both index. Use these operators if you want to compare two Series which has the different index.

In [95]: s1 = pd.Series([1, 2, 3], index=['a', 'b', 'c'])

In [96]: s2 = pd.Series([2, 2, 2], index=['b', 'c', 'd'])

In [97]: s1.eq(s2)
Out[97]: 
a    False
b     True
c    False
d    False
dtype: bool

In [98]: s1.ge(s2)
Out[98]: 
a    False
b     True
c     True
d    False
dtype: bool

Previously, this worked the same as comparison operators (see above).

Series type promotion on assignment

A Series will now correctly promote its dtype for assignment with incompat values to the current dtype (GH13234)

In [99]: s = pd.Series()

Previous behavior:

In [2]: s["a"] = pd.Timestamp("2016-01-01")

In [3]: s["b"] = 3.0
TypeError: invalid type promotion

New behavior:

In [100]: s["a"] = pd.Timestamp("2016-01-01")

In [101]: s["b"] = 3.0

In [102]: s
Out[102]: 
a    2016-01-01 00:00:00
b                      3
dtype: object

In [103]: s.dtype
Out[103]: dtype('O')

.to_datetime() changes

Previously if .to_datetime() encountered mixed integers/floats and strings, but no datetimes with errors='coerce' it would convert all to NaT.

Previous behavior:

In [2]: pd.to_datetime([1, 'foo'], errors='coerce')
Out[2]: DatetimeIndex(['NaT', 'NaT'], dtype='datetime64[ns]', freq=None)

Current behavior:

This will now convert integers/floats with the default unit of ns.

In [104]: pd.to_datetime([1, 'foo'], errors='coerce')
Out[104]: DatetimeIndex(['1970-01-01 00:00:00.000000001', 'NaT'], dtype='datetime64[ns]', freq=None)

Bug fixes related to .to_datetime():

  • Bug in pd.to_datetime() when passing integers or floats, and no unit and errors='coerce' (GH13180).
  • Bug in pd.to_datetime() when passing invalid datatypes (e.g. bool); will now respect the errors keyword (GH13176)
  • Bug in pd.to_datetime() which overflowed on int8, and int16 dtypes (GH13451)
  • Bug in pd.to_datetime() raise AttributeError with NaN and the other string is not valid when errors='ignore' (GH12424)
  • Bug in pd.to_datetime() did not cast floats correctly when unit was specified, resulting in truncated datetime (GH13834)

Merging changes

Merging will now preserve the dtype of the join keys (GH8596)

In [105]: df1 = pd.DataFrame({'key': [1], 'v1': [10]})

In [106]: df1
Out[106]: 
   key  v1
0    1  10

In [107]: df2 = pd.DataFrame({'key': [1, 2], 'v1': [20, 30]})

In [108]: df2
Out[108]: 
   key  v1
0    1  20
1    2  30

Previous behavior:

In [5]: pd.merge(df1, df2, how='outer')
Out[5]:
   key    v1
0  1.0  10.0
1  1.0  20.0
2  2.0  30.0

In [6]: pd.merge(df1, df2, how='outer').dtypes
Out[6]:
key    float64
v1     float64
dtype: object

New behavior:

We are able to preserve the join keys

In [109]: pd.merge(df1, df2, how='outer')
Out[109]: 
   key  v1
0    1  10
1    1  20
2    2  30

In [110]: pd.merge(df1, df2, how='outer').dtypes
Out[110]: 
key    int64
v1     int64
dtype: object

Of course if you have missing values that are introduced, then the resulting dtype will be upcast, which is unchanged from previous.

In [111]: pd.merge(df1, df2, how='outer', on='key')
Out[111]: 
   key  v1_x  v1_y
0    1  10.0    20
1    2   NaN    30

In [112]: pd.merge(df1, df2, how='outer', on='key').dtypes
Out[112]: 
key       int64
v1_x    float64
v1_y      int64
dtype: object

.describe() changes

Percentile identifiers in the index of a .describe() output will now be rounded to the least precision that keeps them distinct (GH13104)

In [113]: s = pd.Series([0, 1, 2, 3, 4])

In [114]: df = pd.DataFrame([0, 1, 2, 3, 4])

Previous behavior:

The percentiles were rounded to at most one decimal place, which could raise ValueError for a data frame if the percentiles were duplicated.

In [3]: s.describe(percentiles=[0.0001, 0.0005, 0.001, 0.999, 0.9995, 0.9999])
Out[3]:
count     5.000000
mean      2.000000
std       1.581139
min       0.000000
0.0%      0.000400
0.1%      0.002000
0.1%      0.004000
50%       2.000000
99.9%     3.996000
100.0%    3.998000
100.0%    3.999600
max       4.000000
dtype: float64

In [4]: df.describe(percentiles=[0.0001, 0.0005, 0.001, 0.999, 0.9995, 0.9999])
Out[4]:
...
ValueError: cannot reindex from a duplicate axis

New behavior:

In [115]: s.describe(percentiles=[0.0001, 0.0005, 0.001, 0.999, 0.9995, 0.9999])
Out[115]: 
count     5.000000
mean      2.000000
std       1.581139
min       0.000000
0.01%     0.000400
0.05%     0.002000
0.1%      0.004000
50%       2.000000
99.9%     3.996000
99.95%    3.998000
99.99%    3.999600
max       4.000000
dtype: float64

In [116]: df.describe(percentiles=[0.0001, 0.0005, 0.001, 0.999, 0.9995, 0.9999])
Out[116]: 
               0
count   5.000000
mean    2.000000
std     1.581139
min     0.000000
0.01%   0.000400
0.05%   0.002000
0.1%    0.004000
50%     2.000000
99.9%   3.996000
99.95%  3.998000
99.99%  3.999600
max     4.000000

Furthermore:

  • Passing duplicated percentiles will now raise a ValueError.
  • Bug in .describe() on a DataFrame with a mixed-dtype column index, which would previously raise a TypeError (GH13288)

Period changes

PeriodIndex now has period dtype

PeriodIndex now has its own period dtype. The period dtype is a pandas extension dtype like category or the timezone aware dtype (datetime64[ns, tz]) (GH13941). As a consequence of this change, PeriodIndex no longer has an integer dtype:

Previous behavior:

In [1]: pi = pd.PeriodIndex(['2016-08-01'], freq='D')

In [2]: pi
Out[2]: PeriodIndex(['2016-08-01'], dtype='int64', freq='D')

In [3]: pd.api.types.is_integer_dtype(pi)
Out[3]: True

In [4]: pi.dtype
Out[4]: dtype('int64')

New behavior:

In [117]: pi = pd.PeriodIndex(['2016-08-01'], freq='D')

In [118]: pi
Out[118]: PeriodIndex(['2016-08-01'], dtype='period[D]', freq='D')

In [119]: pd.api.types.is_integer_dtype(pi)
Out[119]: False

In [120]: pd.api.types.is_period_dtype(pi)
Out[120]: True

In [121]: pi.dtype
Out[121]: period[D]

In [122]: type(pi.dtype)
Out[122]: pandas.core.dtypes.dtypes.PeriodDtype
Period('NaT') now returns pd.NaT

Previously, Period has its own Period('NaT') representation different from pd.NaT. Now Period('NaT') has been changed to return pd.NaT. (GH12759, GH13582)

Previous behavior:

In [5]: pd.Period('NaT', freq='D')
Out[5]: Period('NaT', 'D')

New behavior:

These result in pd.NaT without providing freq option.

In [123]: pd.Period('NaT')
Out[123]: NaT

In [124]: pd.Period(None)
Out[124]: NaT

To be compatible with Period addition and subtraction, pd.NaT now supports addition and subtraction with int. Previously it raised ValueError.

Previous behavior:

In [5]: pd.NaT + 1
...
ValueError: Cannot add integral value to Timestamp without freq.

New behavior:

In [125]: pd.NaT + 1
Out[125]: NaT

In [126]: pd.NaT - 1
Out[126]: NaT
PeriodIndex.values now returns array of Period object

.values is changed to return an array of Period objects, rather than an array of integers (GH13988).

Previous behavior:

In [6]: pi = pd.PeriodIndex(['2011-01', '2011-02'], freq='M')
In [7]: pi.values
array([492, 493])

New behavior:

In [127]: pi = pd.PeriodIndex(['2011-01', '2011-02'], freq='M')

In [128]: pi.values
Out[128]: array([Period('2011-01', 'M'), Period('2011-02', 'M')], dtype=object)

Index + / - no longer used for set operations

Addition and subtraction of the base Index type and of DatetimeIndex (not the numeric index types) previously performed set operations (set union and difference). This behavior was already deprecated since 0.15.0 (in favor using the specific .union() and .difference() methods), and is now disabled. When possible, + and - are now used for element-wise operations, for example for concatenating strings or subtracting datetimes (GH8227, GH14127).

Previous behavior:

In [1]: pd.Index(['a', 'b']) + pd.Index(['a', 'c'])
FutureWarning: using '+' to provide set union with Indexes is deprecated, use '|' or .union()
Out[1]: Index(['a', 'b', 'c'], dtype='object')

New behavior: the same operation will now perform element-wise addition:

In [129]: pd.Index(['a', 'b']) + pd.Index(['a', 'c'])
Out[129]: Index(['aa', 'bc'], dtype='object')

Note that numeric Index objects already performed element-wise operations. For example, the behavior of adding two integer Indexes is unchanged. The base Index is now made consistent with this behavior.

In [130]: pd.Index([1, 2, 3]) + pd.Index([2, 3, 4])
Out[130]: Int64Index([3, 5, 7], dtype='int64')

Further, because of this change, it is now possible to subtract two DatetimeIndex objects resulting in a TimedeltaIndex:

Previous behavior:

In [1]: pd.DatetimeIndex(['2016-01-01', '2016-01-02']) - pd.DatetimeIndex(['2016-01-02', '2016-01-03'])
FutureWarning: using '-' to provide set differences with datetimelike Indexes is deprecated, use .difference()
Out[1]: DatetimeIndex(['2016-01-01'], dtype='datetime64[ns]', freq=None)

New behavior:

In [131]: pd.DatetimeIndex(['2016-01-01', '2016-01-02']) - pd.DatetimeIndex(['2016-01-02', '2016-01-03'])
Out[131]: TimedeltaIndex(['-1 days', '-1 days'], dtype='timedelta64[ns]', freq=None)

Index.difference and .symmetric_difference changes

Index.difference and Index.symmetric_difference will now, more consistently, treat NaN values as any other values. (GH13514)

In [132]: idx1 = pd.Index([1, 2, 3, np.nan])

In [133]: idx2 = pd.Index([0, 1, np.nan])

Previous behavior:

In [3]: idx1.difference(idx2)
Out[3]: Float64Index([nan, 2.0, 3.0], dtype='float64')

In [4]: idx1.symmetric_difference(idx2)
Out[4]: Float64Index([0.0, nan, 2.0, 3.0], dtype='float64')

New behavior:

In [134]: idx1.difference(idx2)
Out[134]: Float64Index([2.0, 3.0], dtype='float64')

In [135]: idx1.symmetric_difference(idx2)
Out[135]: Float64Index([0.0, 2.0, 3.0], dtype='float64')

Index.unique consistently returns Index

Index.unique() now returns unique values as an Index of the appropriate dtype. (GH13395). Previously, most Index classes returned np.ndarray, and DatetimeIndex, TimedeltaIndex and PeriodIndex returned Index to keep metadata like timezone.

Previous behavior:

In [1]: pd.Index([1, 2, 3]).unique()
Out[1]: array([1, 2, 3])

In [2]: pd.DatetimeIndex(['2011-01-01', '2011-01-02', '2011-01-03'], tz='Asia/Tokyo').unique()
Out[2]:
DatetimeIndex(['2011-01-01 00:00:00+09:00', '2011-01-02 00:00:00+09:00',
               '2011-01-03 00:00:00+09:00'],
              dtype='datetime64[ns, Asia/Tokyo]', freq=None)

New behavior:

In [136]: pd.Index([1, 2, 3]).unique()
Out[136]: Int64Index([1, 2, 3], dtype='int64')

In [137]: pd.DatetimeIndex(['2011-01-01', '2011-01-02', '2011-01-03'], tz='Asia/Tokyo').unique()
Out[137]: 
DatetimeIndex(['2011-01-01 00:00:00+09:00', '2011-01-02 00:00:00+09:00',
               '2011-01-03 00:00:00+09:00'],
              dtype='datetime64[ns, Asia/Tokyo]', freq=None)

MultiIndex constructors, groupby and set_index preserve categorical dtypes

MultiIndex.from_arrays and MultiIndex.from_product will now preserve categorical dtype in MultiIndex levels (GH13743, GH13854).

In [138]: cat = pd.Categorical(['a', 'b'], categories=list("bac"))

In [139]: lvl1 = ['foo', 'bar']

In [140]: midx = pd.MultiIndex.from_arrays([cat, lvl1])

In [141]: midx
Out[141]: 
MultiIndex(levels=[['b', 'a', 'c'], ['bar', 'foo']],
           labels=[[1, 0], [1, 0]])

Previous behavior:

In [4]: midx.levels[0]
Out[4]: Index(['b', 'a', 'c'], dtype='object')

In [5]: midx.get_level_values[0]
Out[5]: Index(['a', 'b'], dtype='object')

New behavior: the single level is now a CategoricalIndex:

In [142]: midx.levels[0]
Out[142]: CategoricalIndex(['b', 'a', 'c'], categories=['b', 'a', 'c'], ordered=False, dtype='category')

In [143]: midx.get_level_values(0)
Out[143]: CategoricalIndex(['a', 'b'], categories=['b', 'a', 'c'], ordered=False, dtype='category')

An analogous change has been made to MultiIndex.from_product. As a consequence, groupby and set_index also preserve categorical dtypes in indexes

In [144]: df = pd.DataFrame({'A': [0, 1], 'B': [10, 11], 'C': cat})

In [145]: df_grouped = df.groupby(by=['A', 'C']).first()

In [146]: df_set_idx = df.set_index(['A', 'C'])

Previous behavior:

In [11]: df_grouped.index.levels[1]
Out[11]: Index(['b', 'a', 'c'], dtype='object', name='C')
In [12]: df_grouped.reset_index().dtypes
Out[12]:
A      int64
C     object
B    float64
dtype: object

In [13]: df_set_idx.index.levels[1]
Out[13]: Index(['b', 'a', 'c'], dtype='object', name='C')
In [14]: df_set_idx.reset_index().dtypes
Out[14]:
A      int64
C     object
B      int64
dtype: object

New behavior:

In [147]: df_grouped.index.levels[1]
Out[147]: CategoricalIndex(['b', 'a', 'c'], categories=['b', 'a', 'c'], ordered=False, name='C', dtype='category')

In [148]: df_grouped.reset_index().dtypes
Out[148]: 
A       int64
C    category
B     float64
dtype: object

In [149]: df_set_idx.index.levels[1]
Out[149]: CategoricalIndex(['b', 'a', 'c'], categories=['b', 'a', 'c'], ordered=False, name='C', dtype='category')

In [150]: df_set_idx.reset_index().dtypes
Out[150]: 
A       int64
C    category
B       int64
dtype: object

read_csv will progressively enumerate chunks

When read_csv() is called with chunksize=n and without specifying an index, each chunk used to have an independently generated index from 0 to n-1. They are now given instead a progressive index, starting from 0 for the first chunk, from n for the second, and so on, so that, when concatenated, they are identical to the result of calling read_csv() without the chunksize= argument (GH12185).

In [151]: data = 'A,B\n0,1\n2,3\n4,5\n6,7'

Previous behavior:

In [2]: pd.concat(pd.read_csv(StringIO(data), chunksize=2))
Out[2]:
   A  B
0  0  1
1  2  3
0  4  5
1  6  7

New behavior:

In [152]: pd.concat(pd.read_csv(StringIO(data), chunksize=2))
Out[152]: 
   A  B
0  0  1
1  2  3
2  4  5
3  6  7

Sparse Changes

These changes allow pandas to handle sparse data with more dtypes, and for work to make a smoother experience with data handling.

int64 and bool support enhancements

Sparse data structures now gained enhanced support of int64 and bool dtype (GH667, GH13849).

Previously, sparse data were float64 dtype by default, even if all inputs were of int or bool dtype. You had to specify dtype explicitly to create sparse data with int64 dtype. Also, fill_value had to be specified explicitly because the default was np.nan which doesn’t appear in int64 or bool data.

In [1]: pd.SparseArray([1, 2, 0, 0])
Out[1]:
[1.0, 2.0, 0.0, 0.0]
Fill: nan
IntIndex
Indices: array([0, 1, 2, 3], dtype=int32)

# specifying int64 dtype, but all values are stored in sp_values because
# fill_value default is np.nan
In [2]: pd.SparseArray([1, 2, 0, 0], dtype=np.int64)
Out[2]:
[1, 2, 0, 0]
Fill: nan
IntIndex
Indices: array([0, 1, 2, 3], dtype=int32)

In [3]: pd.SparseArray([1, 2, 0, 0], dtype=np.int64, fill_value=0)
Out[3]:
[1, 2, 0, 0]
Fill: 0
IntIndex
Indices: array([0, 1], dtype=int32)

As of v0.19.0, sparse data keeps the input dtype, and uses more appropriate fill_value defaults (0 for int64 dtype, False for bool dtype).

In [153]: pd.SparseArray([1, 2, 0, 0], dtype=np.int64)
Out[153]: 
[1, 2, 0, 0]
Fill: 0
IntIndex
Indices: array([0, 1], dtype=int32)

In [154]: pd.SparseArray([True, False, False, False])
Out[154]: 
[True, False, False, False]
Fill: False
IntIndex
Indices: array([0], dtype=int32)

See the docs for more details.

Operators now preserve dtypes
  • Sparse data structure now can preserve dtype after arithmetic ops (GH13848)

    In [155]: s = pd.SparseSeries([0, 2, 0, 1], fill_value=0, dtype=np.int64)
    
    In [156]: s.dtype
    Out[156]: dtype('int64')
    
    In [157]: s + 1
    Out[157]: 
    0    1
    1    3
    2    1
    3    2
    dtype: int64
    BlockIndex
    Block locations: array([1, 3], dtype=int32)
    Block lengths: array([1, 1], dtype=int32)
    
  • Sparse data structure now support astype to convert internal dtype (GH13900)

    In [158]: s = pd.SparseSeries([1., 0., 2., 0.], fill_value=0)
    
    In [159]: s
    Out[159]: 
    0    1.0
    1    0.0
    2    2.0
    3    0.0
    dtype: float64
    BlockIndex
    Block locations: array([0, 2], dtype=int32)
    Block lengths: array([1, 1], dtype=int32)
    
    In [160]: s.astype(np.int64)
    Out[160]: 
    0    1
    1    0
    2    2
    3    0
    dtype: int64
    BlockIndex
    Block locations: array([0, 2], dtype=int32)
    Block lengths: array([1, 1], dtype=int32)
    

    astype fails if data contains values which cannot be converted to specified dtype. Note that the limitation is applied to fill_value which default is np.nan.

    In [7]: pd.SparseSeries([1., np.nan, 2., np.nan], fill_value=np.nan).astype(np.int64)
    Out[7]:
    ValueError: unable to coerce current fill_value nan to int64 dtype
    
Other sparse fixes
  • Subclassed SparseDataFrame and SparseSeries now preserve class types when slicing or transposing. (GH13787)
  • SparseArray with bool dtype now supports logical (bool) operators (GH14000)
  • Bug in SparseSeries with MultiIndex [] indexing may raise IndexError (GH13144)
  • Bug in SparseSeries with MultiIndex [] indexing result may have normal Index (GH13144)
  • Bug in SparseDataFrame in which axis=None did not default to axis=0 (GH13048)
  • Bug in SparseSeries and SparseDataFrame creation with object dtype may raise TypeError (GH11633)
  • Bug in SparseDataFrame doesn’t respect passed SparseArray or SparseSeries ‘s dtype and fill_value (GH13866)
  • Bug in SparseArray and SparseSeries don’t apply ufunc to fill_value (GH13853)
  • Bug in SparseSeries.abs incorrectly keeps negative fill_value (GH13853)
  • Bug in single row slicing on multi-type SparseDataFrame s, types were previously forced to float (GH13917)
  • Bug in SparseSeries slicing changes integer dtype to float (GH8292)
  • Bug in SparseDataFarme comparison ops may raise TypeError (GH13001)
  • Bug in SparseDataFarme.isnull raises ValueError (GH8276)
  • Bug in SparseSeries representation with bool dtype may raise IndexError (GH13110)
  • Bug in SparseSeries and SparseDataFrame of bool or int64 dtype may display its values like float64 dtype (GH13110)
  • Bug in sparse indexing using SparseArray with bool dtype may return incorrect result (GH13985)
  • Bug in SparseArray created from SparseSeries may lose dtype (GH13999)
  • Bug in SparseSeries comparison with dense returns normal Series rather than SparseSeries (GH13999)

Indexer dtype changes

Note

This change only affects 64 bit python running on Windows, and only affects relatively advanced indexing operations

Methods such as Index.get_indexer that return an indexer array, coerce that array to a “platform int”, so that it can be directly used in 3rd party library operations like numpy.take. Previously, a platform int was defined as np.int_ which corresponds to a C integer, but the correct type, and what is being used now, is np.intp, which corresponds to the C integer size that can hold a pointer (GH3033, GH13972).

These types are the same on many platform, but for 64 bit python on Windows, np.int_ is 32 bits, and np.intp is 64 bits. Changing this behavior improves performance for many operations on that platform.

Previous behavior:

In [1]: i = pd.Index(['a', 'b', 'c'])

In [2]: i.get_indexer(['b', 'b', 'c']).dtype
Out[2]: dtype('int32')

New behavior:

In [1]: i = pd.Index(['a', 'b', 'c'])

In [2]: i.get_indexer(['b', 'b', 'c']).dtype
Out[2]: dtype('int64')

Other API Changes

  • Timestamp.to_pydatetime will issue a UserWarning when warn=True, and the instance has a non-zero number of nanoseconds, previously this would print a message to stdout (GH14101).
  • Series.unique() with datetime and timezone now returns return array of Timestamp with timezone (GH13565).
  • Panel.to_sparse() will raise a NotImplementedError exception when called (GH13778).
  • Index.reshape() will raise a NotImplementedError exception when called (GH12882).
  • .filter() enforces mutual exclusion of the keyword arguments (GH12399).
  • eval‘s upcasting rules for float32 types have been updated to be more consistent with NumPy’s rules. New behavior will not upcast to float64 if you multiply a pandas float32 object by a scalar float64 (GH12388).
  • An UnsupportedFunctionCall error is now raised if NumPy ufuncs like np.mean are called on groupby or resample objects (GH12811).
  • __setitem__ will no longer apply a callable rhs as a function instead of storing it. Call where directly to get the previous behavior (GH13299).
  • Calls to .sample() will respect the random seed set via numpy.random.seed(n) (GH13161)
  • Styler.apply is now more strict about the outputs your function must return. For axis=0 or axis=1, the output shape must be identical. For axis=None, the output must be a DataFrame with identical columns and index labels (GH13222).
  • Float64Index.astype(int) will now raise ValueError if Float64Index contains NaN values (GH13149)
  • TimedeltaIndex.astype(int) and DatetimeIndex.astype(int) will now return Int64Index instead of np.array (GH13209)
  • Passing Period with multiple frequencies to normal Index now returns Index with object dtype (GH13664)
  • PeriodIndex.fillna with Period has different freq now coerces to object dtype (GH13664)
  • Faceted boxplots from DataFrame.boxplot(by=col) now return a Series when return_type is not None. Previously these returned an OrderedDict. Note that when return_type=None, the default, these still return a 2-D NumPy array (GH12216, GH7096).
  • pd.read_hdf will now raise a ValueError instead of KeyError, if a mode other than r, r+ and a is supplied. (GH13623)
  • pd.read_csv(), pd.read_table(), and pd.read_hdf() raise the builtin FileNotFoundError exception for Python 3.x when called on a nonexistent file; this is back-ported as IOError in Python 2.x (GH14086)
  • More informative exceptions are passed through the csv parser. The exception type would now be the original exception type instead of CParserError (GH13652).
  • pd.read_csv() in the C engine will now issue a ParserWarning or raise a ValueError when sep encoded is more than one character long (GH14065)
  • DataFrame.values will now return float64 with a DataFrame of mixed int64 and uint64 dtypes, conforming to np.find_common_type (GH10364, GH13917)
  • .groupby.groups will now return a dictionary of Index objects, rather than a dictionary of np.ndarray or lists (GH14293)

Deprecations

  • Series.reshape and Categorical.reshape have been deprecated and will be removed in a subsequent release (GH12882, GH12882)
  • PeriodIndex.to_datetime has been deprecated in favor of PeriodIndex.to_timestamp (GH8254)
  • Timestamp.to_datetime has been deprecated in favor of Timestamp.to_pydatetime (GH8254)
  • Index.to_datetime and DatetimeIndex.to_datetime have been deprecated in favor of pd.to_datetime (GH8254)
  • pandas.core.datetools module has been deprecated and will be removed in a subsequent release (GH14094)
  • SparseList has been deprecated and will be removed in a future version (GH13784)
  • DataFrame.to_html() and DataFrame.to_latex() have dropped the colSpace parameter in favor of col_space (GH13857)
  • DataFrame.to_sql() has deprecated the flavor parameter, as it is superfluous when SQLAlchemy is not installed (GH13611)
  • Deprecated read_csv keywords:
    • compact_ints and use_unsigned have been deprecated and will be removed in a future version (GH13320)
    • buffer_lines has been deprecated and will be removed in a future version (GH13360)
    • as_recarray has been deprecated and will be removed in a future version (GH13373)
    • skip_footer has been deprecated in favor of skipfooter and will be removed in a future version (GH13349)
  • top-level pd.ordered_merge() has been renamed to pd.merge_ordered() and the original name will be removed in a future version (GH13358)
  • Timestamp.offset property (and named arg in the constructor), has been deprecated in favor of freq (GH12160)
  • pd.tseries.util.pivot_annual is deprecated. Use pivot_table as alternative, an example is here (GH736)
  • pd.tseries.util.isleapyear has been deprecated and will be removed in a subsequent release. Datetime-likes now have a .is_leap_year property (GH13727)
  • Panel4D and PanelND constructors are deprecated and will be removed in a future version. The recommended way to represent these types of n-dimensional data are with the xarray package. Pandas provides a to_xarray() method to automate this conversion (GH13564).
  • pandas.tseries.frequencies.get_standard_freq is deprecated. Use pandas.tseries.frequencies.to_offset(freq).rule_code instead (GH13874)
  • pandas.tseries.frequencies.to_offset‘s freqstr keyword is deprecated in favor of freq (GH13874)
  • Categorical.from_array has been deprecated and will be removed in a future version (GH13854)

Removal of prior version deprecations/changes

  • The SparsePanel class has been removed (GH13778)
  • The pd.sandbox module has been removed in favor of the external library pandas-qt (GH13670)
  • The pandas.io.data and pandas.io.wb modules are removed in favor of the pandas-datareader package (GH13724).
  • The pandas.tools.rplot module has been removed in favor of the seaborn package (GH13855)
  • DataFrame.to_csv() has dropped the engine parameter, as was deprecated in 0.17.1 (GH11274, GH13419)
  • DataFrame.to_dict() has dropped the outtype parameter in favor of orient (GH13627, GH8486)
  • pd.Categorical has dropped setting of the ordered attribute directly in favor of the set_ordered method (GH13671)
  • pd.Categorical has dropped the levels attribute in favor of categories (GH8376)
  • DataFrame.to_sql() has dropped the mysql option for the flavor parameter (GH13611)
  • Panel.shift() has dropped the lags parameter in favor of periods (GH14041)
  • pd.Index has dropped the diff method in favor of difference (GH13669)
  • pd.DataFrame has dropped the to_wide method in favor of to_panel (GH14039)
  • Series.to_csv has dropped the nanRep parameter in favor of na_rep (GH13804)
  • Series.xs, DataFrame.xs, Panel.xs, Panel.major_xs, and Panel.minor_xs have dropped the copy parameter (GH13781)
  • str.split has dropped the return_type parameter in favor of expand (GH13701)
  • Removal of the legacy time rules (offset aliases), deprecated since 0.17.0 (this has been alias since 0.8.0) (GH13590, GH13868). Now legacy time rules raises ValueError. For the list of currently supported offsets, see here.
  • The default value for the return_type parameter for DataFrame.plot.box and DataFrame.boxplot changed from None to "axes". These methods will now return a matplotlib axes by default instead of a dictionary of artists. See here (GH6581).
  • The tquery and uquery functions in the pandas.io.sql module are removed (GH5950).

Performance Improvements

  • Improved performance of sparse IntIndex.intersect (GH13082)
  • Improved performance of sparse arithmetic with BlockIndex when the number of blocks are large, though recommended to use IntIndex in such cases (GH13082)
  • Improved performance of DataFrame.quantile() as it now operates per-block (GH11623)
  • Improved performance of float64 hash table operations, fixing some very slow indexing and groupby operations in python 3 (GH13166, GH13334)
  • Improved performance of DataFrameGroupBy.transform (GH12737)
  • Improved performance of Index and Series .duplicated (GH10235)
  • Improved performance of Index.difference (GH12044)
  • Improved performance of RangeIndex.is_monotonic_increasing and is_monotonic_decreasing (GH13749)
  • Improved performance of datetime string parsing in DatetimeIndex (GH13692)
  • Improved performance of hashing Period (GH12817)
  • Improved performance of factorize of datetime with timezone (GH13750)
  • Improved performance of by lazily creating indexing hashtables on larger Indexes (GH14266)
  • Improved performance of groupby.groups (GH14293)
  • Unecessary materializing of a MultiIndex when introspecting for memory usage (GH14308)

Bug Fixes

  • Bug in groupby().shift(), which could cause a segfault or corruption in rare circumstances when grouping by columns with missing values (GH13813)
  • Bug in groupby().cumsum() calculating cumprod when axis=1. (GH13994)
  • Bug in pd.to_timedelta() in which the errors parameter was not being respected (GH13613)
  • Bug in io.json.json_normalize(), where non-ascii keys raised an exception (GH13213)
  • Bug when passing a not-default-indexed Series as xerr or yerr in .plot() (GH11858)
  • Bug in area plot draws legend incorrectly if subplot is enabled or legend is moved after plot (matplotlib 1.5.0 is required to draw area plot legend properly) (GH9161, GH13544)
  • Bug in DataFrame assignment with an object-dtyped Index where the resultant column is mutable to the original object. (GH13522)
  • Bug in matplotlib AutoDataFormatter; this restores the second scaled formatting and re-adds micro-second scaled formatting (GH13131)
  • Bug in selection from a HDFStore with a fixed format and start and/or stop specified will now return the selected range (GH8287)
  • Bug in Categorical.from_codes() where an unhelpful error was raised when an invalid ordered parameter was passed in (GH14058)
  • Bug in Series construction from a tuple of integers on windows not returning default dtype (int64) (GH13646)
  • Bug in TimedeltaIndex addition with a Datetime-like object where addition overflow was not being caught (GH14068)
  • Bug in .groupby(..).resample(..) when the same object is called multiple times (GH13174)
  • Bug in .to_records() when index name is a unicode string (GH13172)
  • Bug in calling .memory_usage() on object which doesn’t implement (GH12924)
  • Regression in Series.quantile with nans (also shows up in .median() and .describe() ); furthermore now names the Series with the quantile (GH13098, GH13146)
  • Bug in SeriesGroupBy.transform with datetime values and missing groups (GH13191)
  • Bug where empty Series were incorrectly coerced in datetime-like numeric operations (GH13844)
  • Bug in Categorical constructor when passed a Categorical containing datetimes with timezones (GH14190)
  • Bug in Series.str.extractall() with str index raises ValueError (GH13156)
  • Bug in Series.str.extractall() with single group and quantifier (GH13382)
  • Bug in DatetimeIndex and Period subtraction raises ValueError or AttributeError rather than TypeError (GH13078)
  • Bug in Index and Series created with NaN and NaT mixed data may not have datetime64 dtype (GH13324)
  • Bug in Index and Series may ignore np.datetime64('nat') and np.timdelta64('nat') to infer dtype (GH13324)
  • Bug in PeriodIndex and Period subtraction raises AttributeError (GH13071)
  • Bug in PeriodIndex construction returning a float64 index in some circumstances (GH13067)
  • Bug in .resample(..) with a PeriodIndex not changing its freq appropriately when empty (GH13067)
  • Bug in .resample(..) with a PeriodIndex not retaining its type or name with an empty DataFrame appropriately when empty (GH13212)
  • Bug in groupby(..).apply(..) when the passed function returns scalar values per group (GH13468).
  • Bug in groupby(..).resample(..) where passing some keywords would raise an exception (GH13235)
  • Bug in .tz_convert on a tz-aware DateTimeIndex that relied on index being sorted for correct results (GH13306)
  • Bug in .tz_localize with dateutil.tz.tzlocal may return incorrect result (GH13583)
  • Bug in DatetimeTZDtype dtype with dateutil.tz.tzlocal cannot be regarded as valid dtype (GH13583)
  • Bug in pd.read_hdf() where attempting to load an HDF file with a single dataset, that had one or more categorical columns, failed unless the key argument was set to the name of the dataset. (GH13231)
  • Bug in .rolling() that allowed a negative integer window in contruction of the Rolling() object, but would later fail on aggregation (GH13383)
  • Bug in Series indexing with tuple-valued data and a numeric index (GH13509)
  • Bug in printing pd.DataFrame where unusual elements with the object dtype were causing segfaults (GH13717)
  • Bug in ranking Series which could result in segfaults (GH13445)
  • Bug in various index types, which did not propagate the name of passed index (GH12309)
  • Bug in DatetimeIndex, which did not honour the copy=True (GH13205)
  • Bug in DatetimeIndex.is_normalized returns incorrectly for normalized date_range in case of local timezones (GH13459)
  • Bug in pd.concat and .append may coerces datetime64 and timedelta to object dtype containing python built-in datetime or timedelta rather than Timestamp or Timedelta (GH13626)
  • Bug in PeriodIndex.append may raises AttributeError when the result is object dtype (GH13221)
  • Bug in CategoricalIndex.append may accept normal list (GH13626)
  • Bug in pd.concat and .append with the same timezone get reset to UTC (GH7795)
  • Bug in Series and DataFrame .append raises AmbiguousTimeError if data contains datetime near DST boundary (GH13626)
  • Bug in DataFrame.to_csv() in which float values were being quoted even though quotations were specified for non-numeric values only (GH12922, GH13259)
  • Bug in DataFrame.describe() raising ValueError with only boolean columns (GH13898)
  • Bug in MultiIndex slicing where extra elements were returned when level is non-unique (GH12896)
  • Bug in .str.replace does not raise TypeError for invalid replacement (GH13438)
  • Bug in MultiIndex.from_arrays which didn’t check for input array lengths matching (GH13599)
  • Bug in cartesian_product and MultiIndex.from_product which may raise with empty input arrays (GH12258)
  • Bug in pd.read_csv() which may cause a segfault or corruption when iterating in large chunks over a stream/file under rare circumstances (GH13703)
  • Bug in pd.read_csv() which caused errors to be raised when a dictionary containing scalars is passed in for na_values (GH12224)
  • Bug in pd.read_csv() which caused BOM files to be incorrectly parsed by not ignoring the BOM (GH4793)
  • Bug in pd.read_csv() with engine='python' which raised errors when a numpy array was passed in for usecols (GH12546)
  • Bug in pd.read_csv() where the index columns were being incorrectly parsed when parsed as dates with a thousands parameter (GH14066)
  • Bug in pd.read_csv() with engine='python' in which NaN values weren’t being detected after data was converted to numeric values (GH13314)
  • Bug in pd.read_csv() in which the nrows argument was not properly validated for both engines (GH10476)
  • Bug in pd.read_csv() with engine='python' in which infinities of mixed-case forms were not being interpreted properly (GH13274)
  • Bug in pd.read_csv() with engine='python' in which trailing NaN values were not being parsed (GH13320)
  • Bug in pd.read_csv() with engine='python' when reading from a tempfile.TemporaryFile on Windows with Python 3 (GH13398)
  • Bug in pd.read_csv() that prevents usecols kwarg from accepting single-byte unicode strings (GH13219)
  • Bug in pd.read_csv() that prevents usecols from being an empty set (GH13402)
  • Bug in pd.read_csv() in the C engine where the NULL character was not being parsed as NULL (GH14012)
  • Bug in pd.read_csv() with engine='c' in which NULL quotechar was not accepted even though quoting was specified as None (GH13411)
  • Bug in pd.read_csv() with engine='c' in which fields were not properly cast to float when quoting was specified as non-numeric (GH13411)
  • Bug in pd.read_csv() in Python 2.x with non-UTF8 encoded, multi-character separated data (GH3404)
  • Bug in pd.read_csv(), where aliases for utf-xx (e.g. UTF-xx, UTF_xx, utf_xx) raised UnicodeDecodeError (GH13549)
  • Bug in pd.read_csv, pd.read_table, pd.read_fwf, pd.read_stata and pd.read_sas where files were opened by parsers but not closed if both chunksize and iterator were None. (GH13940)
  • Bug in StataReader, StataWriter, XportReader and SAS7BDATReader where a file was not properly closed when an error was raised. (GH13940)
  • Bug in pd.pivot_table() where margins_name is ignored when aggfunc is a list (GH13354)
  • Bug in pd.Series.str.zfill, center, ljust, rjust, and pad when passing non-integers, did not raise TypeError (GH13598)
  • Bug in checking for any null objects in a TimedeltaIndex, which always returned True (GH13603)
  • Bug in Series arithmetic raises TypeError if it contains datetime-like as object dtype (GH13043)
  • Bug Series.isnull() and Series.notnull() ignore Period('NaT') (GH13737)
  • Bug Series.fillna() and Series.dropna() don’t affect to Period('NaT') (GH13737
  • Bug in .fillna(value=np.nan) incorrectly raises KeyError on a category dtyped Series (GH14021)
  • Bug in extension dtype creation where the created types were not is/identical (GH13285)
  • Bug in .resample(..) where incorrect warnings were triggered by IPython introspection (GH13618)
  • Bug in NaT - Period raises AttributeError (GH13071)
  • Bug in Series comparison may output incorrect result if rhs contains NaT (GH9005)
  • Bug in Series and Index comparison may output incorrect result if it contains NaT with object dtype (GH13592)
  • Bug in Period addition raises TypeError if Period is on right hand side (GH13069)
  • Bug in Peirod and Series or Index comparison raises TypeError (GH13200)
  • Bug in pd.set_eng_float_format() that would prevent NaN and Inf from formatting (GH11981)
  • Bug in .unstack with Categorical dtype resets .ordered to True (GH13249)
  • Clean some compile time warnings in datetime parsing (GH13607)
  • Bug in factorize raises AmbiguousTimeError if data contains datetime near DST boundary (GH13750)
  • Bug in .set_index raises AmbiguousTimeError if new index contains DST boundary and multi levels (GH12920)
  • Bug in .shift raises AmbiguousTimeError if data contains datetime near DST boundary (GH13926)
  • Bug in pd.read_hdf() returns incorrect result when a DataFrame with a categorical column and a query which doesn’t match any values (GH13792)
  • Bug in .iloc when indexing with a non lex-sorted MultiIndex (GH13797)
  • Bug in .loc when indexing with date strings in a reverse sorted DatetimeIndex (GH14316)
  • Bug in Series comparison operators when dealing with zero dim NumPy arrays (GH13006)
  • Bug in .combine_first may return incorrect dtype (GH7630, GH10567)
  • Bug in groupby where apply returns different result depending on whether first result is None or not (GH12824)
  • Bug in groupby(..).nth() where the group key is included inconsistently if called after .head()/.tail() (GH12839)
  • Bug in .to_html, .to_latex and .to_string silently ignore custom datetime formatter passed through the formatters key word (GH10690)
  • Bug in DataFrame.iterrows(), not yielding a Series subclasse if defined (GH13977)
  • Bug in pd.to_numeric when errors='coerce' and input contains non-hashable objects (GH13324)
  • Bug in invalid Timedelta arithmetic and comparison may raise ValueError rather than TypeError (GH13624)
  • Bug in invalid datetime parsing in to_datetime and DatetimeIndex may raise TypeError rather than ValueError (GH11169, GH11287)
  • Bug in Index created with tz-aware Timestamp and mismatched tz option incorrectly coerces timezone (GH13692)
  • Bug in DatetimeIndex with nanosecond frequency does not include timestamp specified with end (GH13672)
  • Bug in `Series` when setting a slice with a `np.timedelta64` (GH14155)
  • Bug in Index raises OutOfBoundsDatetime if datetime exceeds datetime64[ns] bounds, rather than coercing to object dtype (GH13663)
  • Bug in Index may ignore specified datetime64 or timedelta64 passed as dtype (GH13981)
  • Bug in RangeIndex can be created without no arguments rather than raises TypeError (GH13793)
  • Bug in .value_counts() raises OutOfBoundsDatetime if data exceeds datetime64[ns] bounds (GH13663)
  • Bug in DatetimeIndex may raise OutOfBoundsDatetime if input np.datetime64 has other unit than ns (GH9114)
  • Bug in Series creation with np.datetime64 which has other unit than ns as object dtype results in incorrect values (GH13876)
  • Bug in resample with timedelta data where data was casted to float (GH13119).
  • Bug in pd.isnull() pd.notnull() raise TypeError if input datetime-like has other unit than ns (GH13389)
  • Bug in pd.merge() may raise TypeError if input datetime-like has other unit than ns (GH13389)
  • Bug in HDFStore/read_hdf() discarded DatetimeIndex.name if tz was set (GH13884)
  • Bug in Categorical.remove_unused_categories() changes .codes dtype to platform int (GH13261)
  • Bug in groupby with as_index=False returns all NaN’s when grouping on multiple columns including a categorical one (GH13204)
  • Bug in df.groupby(...)[...] where getitem with Int64Index raised an error (GH13731)
  • Bug in the CSS classes assigned to DataFrame.style for index names. Previously they were assigned "col_heading level<n> col<c>" where n was the number of levels + 1. Now they are assigned "index_name level<n>", where n is the correct level for that MultiIndex.
  • Bug where pd.read_gbq() could throw ImportError: No module named discovery as a result of a naming conflict with another python package called apiclient (GH13454)
  • Bug in Index.union returns an incorrect result with a named empty index (GH13432)
  • Bugs in Index.difference and DataFrame.join raise in Python3 when using mixed-integer indexes (GH13432, GH12814)
  • Bug in subtract tz-aware datetime.datetime from tz-aware datetime64 series (GH14088)
  • Bug in .to_excel() when DataFrame contains a MultiIndex which contains a label with a NaN value (GH13511)
  • Bug in invalid frequency offset string like “D1”, “-2-3H” may not raise ValueError (GH13930)
  • Bug in concat and groupby for hierarchical frames with RangeIndex levels (GH13542).
  • Bug in Series.str.contains() for Series containing only NaN values of object dtype (GH14171)
  • Bug in agg() function on groupby dataframe changes dtype of datetime64[ns] column to float64 (GH12821)
  • Bug in using NumPy ufunc with PeriodIndex to add or subtract integer raise IncompatibleFrequency. Note that using standard operator like + or - is recommended, because standard operators use more efficient path (GH13980)
  • Bug in operations on NaT returning float instead of datetime64[ns] (GH12941)
  • Bug in Series flexible arithmetic methods (like .add()) raises ValueError when axis=None (GH13894)
  • Bug in DataFrame.to_csv() with MultiIndex columns in which a stray empty line was added (GH6618)
  • Bug in DatetimeIndex, TimedeltaIndex and PeriodIndex.equals() may return True when input isn’t Index but contains the same values (GH13107)
  • Bug in assignment against datetime with timezone may not work if it contains datetime near DST boundary (GH14146)
  • Bug in pd.eval() and HDFStore query truncating long float literals with python 2 (GH14241)
  • Bug in Index raises KeyError displaying incorrect column when column is not in the df and columns contains duplicate values (GH13822)
  • Bug in Period and PeriodIndex creating wrong dates when frequency has combined offset aliases (GH13874)
  • Bug in .to_string() when called with an integer line_width and index=False raises an UnboundLocalError exception because idx referenced before assignment.
  • Bug in eval() where the resolvers argument would not accept a list (GH14095)
  • Bugs in stack, get_dummies, make_axis_dummies which don’t preserve categorical dtypes in (multi)indexes (GH13854)
  • PeriodIndex can now accept list and array which contains pd.NaT (GH13430)
  • Bug in df.groupby where .median() returns arbitrary values if grouped dataframe contains empty bins (GH13629)
  • Bug in Index.copy() where name parameter was ignored (GH14302)

v0.18.1 (May 3, 2016)

This is a minor bug-fix release from 0.18.0 and includes a large number of bug fixes along with several new features, enhancements, and performance improvements. We recommend that all users upgrade to this version.

Highlights include:

  • .groupby(...) has been enhanced to provide convenient syntax when working with .rolling(..), .expanding(..) and .resample(..) per group, see here
  • pd.to_datetime() has gained the ability to assemble dates from a DataFrame, see here
  • Method chaining improvements, see here.
  • Custom business hour offset, see here.
  • Many bug fixes in the handling of sparse, see here
  • Expanded the Tutorials section with a feature on modern pandas, courtesy of @TomAugsburger. (GH13045).

New features

Custom Business Hour

The CustomBusinessHour is a mixture of BusinessHour and CustomBusinessDay which allows you to specify arbitrary holidays. For details, see Custom Business Hour (GH11514)

In [1]: from pandas.tseries.offsets import CustomBusinessHour

In [2]: from pandas.tseries.holiday import USFederalHolidayCalendar

In [3]: bhour_us = CustomBusinessHour(calendar=USFederalHolidayCalendar())

Friday before MLK Day

In [4]: dt = datetime(2014, 1, 17, 15)

In [5]: dt + bhour_us
Out[5]: Timestamp('2014-01-17 16:00:00')

Tuesday after MLK Day (Monday is skipped because it’s a holiday)

In [6]: dt + bhour_us * 2
Out[6]: Timestamp('2014-01-20 09:00:00')

.groupby(..) syntax with window and resample operations

.groupby(...) has been enhanced to provide convenient syntax when working with .rolling(..), .expanding(..) and .resample(..) per group, see (GH12486, GH12738).

You can now use .rolling(..) and .expanding(..) as methods on groupbys. These return another deferred object (similar to what .rolling() and .expanding() do on ungrouped pandas objects). You can then operate on these RollingGroupby objects in a similar manner.

Previously you would have to do this to get a rolling window mean per-group:

In [7]: df = pd.DataFrame({'A': [1] * 20 + [2] * 12 + [3] * 8,
   ...:                    'B': np.arange(40)})
   ...: 

In [8]: df
Out[8]: 
    A   B
0   1   0
1   1   1
2   1   2
3   1   3
4   1   4
5   1   5
6   1   6
.. ..  ..
33  3  33
34  3  34
35  3  35
36  3  36
37  3  37
38  3  38
39  3  39

[40 rows x 2 columns]
In [9]: df.groupby('A').apply(lambda x: x.rolling(4).B.mean())
Out[9]: 
A    
1  0      NaN
   1      NaN
   2      NaN
   3      1.5
   4      2.5
   5      3.5
   6      4.5
         ... 
3  33     NaN
   34     NaN
   35    33.5
   36    34.5
   37    35.5
   38    36.5
   39    37.5
Name: B, Length: 40, dtype: float64

Now you can do:

In [10]: df.groupby('A').rolling(4).B.mean()
Out[10]: 
A    
1  0      NaN
   1      NaN
   2      NaN
   3      1.5
   4      2.5
   5      3.5
   6      4.5
         ... 
3  33     NaN
   34     NaN
   35    33.5
   36    34.5
   37    35.5
   38    36.5
   39    37.5
Name: B, Length: 40, dtype: float64

For .resample(..) type of operations, previously you would have to:

In [11]: df = pd.DataFrame({'date': pd.date_range(start='2016-01-01',
   ....:                                          periods=4,
   ....:                                          freq='W'),
   ....:                    'group': [1, 1, 2, 2],
   ....:                    'val': [5, 6, 7, 8]}).set_index('date')
   ....: 

In [12]: df
Out[12]: 
            group  val
date                  
2016-01-03      1    5
2016-01-10      1    6
2016-01-17      2    7
2016-01-24      2    8
In [13]: df.groupby('group').apply(lambda x: x.resample('1D').ffill())
Out[13]: 
                  group  val
group date                  
1     2016-01-03      1    5
      2016-01-04      1    5
      2016-01-05      1    5
      2016-01-06      1    5
      2016-01-07      1    5
      2016-01-08      1    5
      2016-01-09      1    5
...                 ...  ...
2     2016-01-18      2    7
      2016-01-19      2    7
      2016-01-20      2    7
      2016-01-21      2    7
      2016-01-22      2    7
      2016-01-23      2    7
      2016-01-24      2    8

[16 rows x 2 columns]

Now you can do:

In [14]: df.groupby('group').resample('1D').ffill()
Out[14]: 
                  group  val
group date                  
1     2016-01-03      1    5
      2016-01-04      1    5
      2016-01-05      1    5
      2016-01-06      1    5
      2016-01-07      1    5
      2016-01-08      1    5
      2016-01-09      1    5
...                 ...  ...
2     2016-01-18      2    7
      2016-01-19      2    7
      2016-01-20      2    7
      2016-01-21      2    7
      2016-01-22      2    7
      2016-01-23      2    7
      2016-01-24      2    8

[16 rows x 2 columns]

Method chaininng improvements

The following methods / indexers now accept a callable. It is intended to make these more useful in method chains, see the documentation. (GH11485, GH12533)

  • .where() and .mask()
  • .loc[], iloc[] and .ix[]
  • [] indexing
.where() and .mask()

These can accept a callable for the condition and other arguments.

In [15]: df = pd.DataFrame({'A': [1, 2, 3],
   ....:                    'B': [4, 5, 6],
   ....:                    'C': [7, 8, 9]})
   ....: 

In [16]: df.where(lambda x: x > 4, lambda x: x + 10)
Out[16]: 
    A   B  C
0  11  14  7
1  12   5  8
2  13   6  9
.loc[], .iloc[], .ix[]

These can accept a callable, and a tuple of callable as a slicer. The callable can return a valid boolean indexer or anything which is valid for these indexer’s input.

# callable returns bool indexer
In [17]: df.loc[lambda x: x.A >= 2, lambda x: x.sum() > 10]
Out[17]: 
   B  C
1  5  8
2  6  9

# callable returns list of labels
In [18]: df.loc[lambda x: [1, 2], lambda x: ['A', 'B']]
Out[18]: 
   A  B
1  2  5
2  3  6
[] indexing

Finally, you can use a callable in [] indexing of Series, DataFrame and Panel. The callable must return a valid input for [] indexing depending on its class and index type.

In [19]: df[lambda x: 'A']
Out[19]: 
0    1
1    2
2    3
Name: A, dtype: int64

Using these methods / indexers, you can chain data selection operations without using temporary variable.

In [20]: bb = pd.read_csv('data/baseball.csv', index_col='id')

In [21]: (bb.groupby(['year', 'team'])
   ....:    .sum()
   ....:    .loc[lambda df: df.r > 100]
   ....: )
   ....: 
Out[21]: 
           stint    g    ab    r    h  X2b  X3b  hr    rbi    sb   cs   bb  \
year team                                                                    
2007 CIN       6  379   745  101  203   35    2  36  125.0  10.0  1.0  105   
     DET       5  301  1062  162  283   54    4  37  144.0  24.0  7.0   97   
     HOU       4  311   926  109  218   47    6  14   77.0  10.0  4.0   60   
     LAN      11  413  1021  153  293   61    3  36  154.0   7.0  5.0  114   
     NYN      13  622  1854  240  509  101    3  61  243.0  22.0  4.0  174   
     SFN       5  482  1305  198  337   67    6  40  171.0  26.0  7.0  235   
     TEX       2  198   729  115  200   40    4  28  115.0  21.0  4.0   73   
     TOR       4  459  1408  187  378   96    2  58  223.0   4.0  2.0  190   

              so   ibb   hbp    sh    sf  gidp  
year team                                       
2007 CIN   127.0  14.0   1.0   1.0  15.0  18.0  
     DET   176.0   3.0  10.0   4.0   8.0  28.0  
     HOU   212.0   3.0   9.0  16.0   6.0  17.0  
     LAN   141.0   8.0   9.0   3.0   8.0  29.0  
     NYN   310.0  24.0  23.0  18.0  15.0  48.0  
     SFN   188.0  51.0   8.0  16.0   6.0  41.0  
     TEX   140.0   4.0   5.0   2.0   8.0  16.0  
     TOR   265.0  16.0  12.0   4.0  16.0  38.0  

Partial string indexing on DateTimeIndex when part of a MultiIndex

Partial string indexing now matches on DateTimeIndex when part of a MultiIndex (GH10331)

In [22]: dft2 = pd.DataFrame(np.random.randn(20, 1),
   ....:                     columns=['A'],
   ....:                     index=pd.MultiIndex.from_product([pd.date_range('20130101',
   ....:                                                                     periods=10,
   ....:                                                                     freq='12H'),
   ....:                                                      ['a', 'b']]))
   ....: 

In [23]: dft2
Out[23]: 
                              A
2013-01-01 00:00:00 a  0.156998
                    b -0.571455
2013-01-01 12:00:00 a  1.057633
                    b -0.791489
2013-01-02 00:00:00 a -0.524627
                    b  0.071878
2013-01-02 12:00:00 a  1.910759
...                         ...
2013-01-04 00:00:00 b  1.015405
2013-01-04 12:00:00 a  0.749185
                    b -0.675521
2013-01-05 00:00:00 a  0.440266
                    b  0.688972
2013-01-05 12:00:00 a -0.276646
                    b  1.924533

[20 rows x 1 columns]

In [24]: dft2.loc['2013-01-05']
Out[24]: 
                              A
2013-01-05 00:00:00 a  0.440266
                    b  0.688972
2013-01-05 12:00:00 a -0.276646
                    b  1.924533

On other levels

In [25]: idx = pd.IndexSlice

In [26]: dft2 = dft2.swaplevel(0, 1).sort_index()

In [27]: dft2
Out[27]: 
                              A
a 2013-01-01 00:00:00  0.156998
  2013-01-01 12:00:00  1.057633
  2013-01-02 00:00:00 -0.524627
  2013-01-02 12:00:00  1.910759
  2013-01-03 00:00:00  0.513082
  2013-01-03 12:00:00  1.043945
  2013-01-04 00:00:00  1.459927
...                         ...
b 2013-01-02 12:00:00  0.787965
  2013-01-03 00:00:00 -0.546416
  2013-01-03 12:00:00  2.107785
  2013-01-04 00:00:00  1.015405
  2013-01-04 12:00:00 -0.675521
  2013-01-05 00:00:00  0.688972
  2013-01-05 12:00:00  1.924533

[20 rows x 1 columns]

In [28]: dft2.loc[idx[:, '2013-01-05'], :]
Out[28]: 
                              A
a 2013-01-05 00:00:00  0.440266
  2013-01-05 12:00:00 -0.276646
b 2013-01-05 00:00:00  0.688972
  2013-01-05 12:00:00  1.924533

Assembling Datetimes

pd.to_datetime() has gained the ability to assemble datetimes from a passed in DataFrame or a dict. (GH8158).

In [29]: df = pd.DataFrame({'year': [2015, 2016],
   ....:                    'month': [2, 3],
   ....:                    'day': [4, 5],
   ....:                    'hour': [2, 3]})
   ....: 

In [30]: df
Out[30]: 
   day  hour  month  year
0    4     2      2  2015
1    5     3      3  2016

Assembling using the passed frame.

In [31]: pd.to_datetime(df)
Out[31]: 
0   2015-02-04 02:00:00
1   2016-03-05 03:00:00
dtype: datetime64[ns]

You can pass only the columns that you need to assemble.

In [32]: pd.to_datetime(df[['year', 'month', 'day']])
Out[32]: 
0   2015-02-04
1   2016-03-05
dtype: datetime64[ns]

Other Enhancements

  • pd.read_csv() now supports delim_whitespace=True for the Python engine (GH12958)

  • pd.read_csv() now supports opening ZIP files that contains a single CSV, via extension inference or explict compression='zip' (GH12175)

  • pd.read_csv() now supports opening files using xz compression, via extension inference or explicit compression='xz' is specified; xz compressions is also supported by DataFrame.to_csv in the same way (GH11852)

  • pd.read_msgpack() now always gives writeable ndarrays even when compression is used (GH12359).

  • pd.read_msgpack() now supports serializing and de-serializing categoricals with msgpack (GH12573)

  • .to_json() now supports NDFrames that contain categorical and sparse data (GH10778)

  • interpolate() now supports method='akima' (GH7588).

  • pd.read_excel() now accepts path objects (e.g. pathlib.Path, py.path.local) for the file path, in line with other read_* functions (GH12655)

  • Added .weekday_name property as a component to DatetimeIndex and the .dt accessor. (GH11128)

  • Index.take now handles allow_fill and fill_value consistently (GH12631)

    In [33]: idx = pd.Index([1., 2., 3., 4.], dtype='float')
    
    # default, allow_fill=True, fill_value=None
    In [34]: idx.take([2, -1])
    Out[34]: Float64Index([3.0, 4.0], dtype='float64')
    
    In [35]: idx.take([2, -1], fill_value=True)
    Out[35]: Float64Index([3.0, nan], dtype='float64')
    
  • Index now supports .str.get_dummies() which returns MultiIndex, see Creating Indicator Variables (GH10008, GH10103)

    In [36]: idx = pd.Index(['a|b', 'a|c', 'b|c'])
    
    In [37]: idx.str.get_dummies('|')
    Out[37]: 
    MultiIndex(levels=[[0, 1], [0, 1], [0, 1]],
               labels=[[1, 1, 0], [1, 0, 1], [0, 1, 1]],
               names=['a', 'b', 'c'])
    
  • pd.crosstab() has gained a normalize argument for normalizing frequency tables (GH12569). Examples in the updated docs here.

  • .resample(..).interpolate() is now supported (GH12925)

  • .isin() now accepts passed sets (GH12988)

Sparse changes

These changes conform sparse handling to return the correct types and work to make a smoother experience with indexing.

SparseArray.take now returns a scalar for scalar input, SparseArray for others. Furthermore, it handles a negative indexer with the same rule as Index (GH10560, GH12796)

In [38]: s = pd.SparseArray([np.nan, np.nan, 1, 2, 3, np.nan, 4, 5, np.nan, 6])

In [39]: s.take(0)
Out[39]: nan

In [40]: s.take([1, 2, 3])
Out[40]: 
[nan, 1.0, 2.0]
Fill: nan
IntIndex
Indices: array([1, 2], dtype=int32)
  • Bug in SparseSeries[] indexing with Ellipsis raises KeyError (GH9467)
  • Bug in SparseArray[] indexing with tuples are not handled properly (GH12966)
  • Bug in SparseSeries.loc[] with list-like input raises TypeError (GH10560)
  • Bug in SparseSeries.iloc[] with scalar input may raise IndexError (GH10560)
  • Bug in SparseSeries.loc[], .iloc[] with slice returns SparseArray, rather than SparseSeries (GH10560)
  • Bug in SparseDataFrame.loc[], .iloc[] may results in dense Series, rather than SparseSeries (GH12787)
  • Bug in SparseArray addition ignores fill_value of right hand side (GH12910)
  • Bug in SparseArray mod raises AttributeError (GH12910)
  • Bug in SparseArray pow calculates 1 ** np.nan as np.nan which must be 1 (GH12910)
  • Bug in SparseArray comparison output may incorrect result or raise ValueError (GH12971)
  • Bug in SparseSeries.__repr__ raises TypeError when it is longer than max_rows (GH10560)
  • Bug in SparseSeries.shape ignores fill_value (GH10452)
  • Bug in SparseSeries and SparseArray may have different dtype from its dense values (GH12908)
  • Bug in SparseSeries.reindex incorrectly handle fill_value (GH12797)
  • Bug in SparseArray.to_frame() results in DataFrame, rather than SparseDataFrame (GH9850)
  • Bug in SparseSeries.value_counts() does not count fill_value (GH6749)
  • Bug in SparseArray.to_dense() does not preserve dtype (GH10648)
  • Bug in SparseArray.to_dense() incorrectly handle fill_value (GH12797)
  • Bug in pd.concat() of SparseSeries results in dense (GH10536)
  • Bug in pd.concat() of SparseDataFrame incorrectly handle fill_value (GH9765)
  • Bug in pd.concat() of SparseDataFrame may raise AttributeError (GH12174)
  • Bug in SparseArray.shift() may raise NameError or TypeError (GH12908)

API changes

.groupby(..).nth() changes

The index in .groupby(..).nth() output is now more consistent when the as_index argument is passed (GH11039):

In [41]: df = DataFrame({'A' : ['a', 'b', 'a'],
   ....:                 'B' : [1, 2, 3]})
   ....: 

In [42]: df
Out[42]: 
   A  B
0  a  1
1  b  2
2  a  3

Previous Behavior:

In [3]: df.groupby('A', as_index=True)['B'].nth(0)
Out[3]:
0    1
1    2
Name: B, dtype: int64

In [4]: df.groupby('A', as_index=False)['B'].nth(0)
Out[4]:
0    1
1    2
Name: B, dtype: int64

New Behavior:

In [43]: df.groupby('A', as_index=True)['B'].nth(0)
Out[43]: 
A
a    1
b    2
Name: B, dtype: int64

In [44]: df.groupby('A', as_index=False)['B'].nth(0)
Out[44]: 
0    1
1    2
Name: B, dtype: int64

Furthermore, previously, a .groupby would always sort, regardless if sort=False was passed with .nth().

In [45]: np.random.seed(1234)

In [46]: df = pd.DataFrame(np.random.randn(100, 2), columns=['a', 'b'])

In [47]: df['c'] = np.random.randint(0, 4, 100)

Previous Behavior:

In [4]: df.groupby('c', sort=True).nth(1)
Out[4]:
          a         b
c
0 -0.334077  0.002118
1  0.036142 -2.074978
2 -0.720589  0.887163
3  0.859588 -0.636524

In [5]: df.groupby('c', sort=False).nth(1)
Out[5]:
          a         b
c
0 -0.334077  0.002118
1  0.036142 -2.074978
2 -0.720589  0.887163
3  0.859588 -0.636524

New Behavior:

In [48]: df.groupby('c', sort=True).nth(1)
Out[48]: 
          a         b
c                    
0 -0.334077  0.002118
1  0.036142 -2.074978
2 -0.720589  0.887163
3  0.859588 -0.636524

In [49]: df.groupby('c', sort=False).nth(1)
Out[49]: 
          a         b
c                    
2 -0.720589  0.887163
3  0.859588 -0.636524
0 -0.334077  0.002118
1  0.036142 -2.074978

numpy function compatibility

Compatibility between pandas array-like methods (e.g. sum and take) and their numpy counterparts has been greatly increased by augmenting the signatures of the pandas methods so as to accept arguments that can be passed in from numpy, even if they are not necessarily used in the pandas implementation (GH12644, GH12638, GH12687)

  • .searchsorted() for Index and TimedeltaIndex now accept a sorter argument to maintain compatibility with numpy’s searchsorted function (GH12238)
  • Bug in numpy compatibility of np.round() on a Series (GH12600)

An example of this signature augmentation is illustrated below:

In [50]: sp = pd.SparseDataFrame([1, 2, 3])

In [51]: sp
Out[51]: 
   0
0  1
1  2
2  3

Previous behaviour:

In [2]: np.cumsum(sp, axis=0)
...
TypeError: cumsum() takes at most 2 arguments (4 given)

New behaviour:

In [52]: np.cumsum(sp, axis=0)
Out[52]: 
   0
0  1
1  3
2  6

Using .apply on groupby resampling

Using apply on resampling groupby operations (using a pd.TimeGrouper) now has the same output types as similar apply calls on other groupby operations. (GH11742).

In [53]: df = pd.DataFrame({'date': pd.to_datetime(['10/10/2000', '11/10/2000']),
   ....:                   'value': [10, 13]})
   ....: 

In [54]: df
Out[54]: 
        date  value
0 2000-10-10     10
1 2000-11-10     13

Previous behavior:

In [1]: df.groupby(pd.TimeGrouper(key='date', freq='M')).apply(lambda x: x.value.sum())
Out[1]:
...
TypeError: cannot concatenate a non-NDFrame object

# Output is a Series
In [2]: df.groupby(pd.TimeGrouper(key='date', freq='M')).apply(lambda x: x[['value']].sum())
Out[2]:
date
2000-10-31  value    10
2000-11-30  value    13
dtype: int64

New Behavior:

# Output is a Series
In [55]: df.groupby(pd.TimeGrouper(key='date', freq='M')).apply(lambda x: x.value.sum())
Out[55]:
date
2000-10-31    10
2000-11-30    13
Freq: M, dtype: int64

# Output is a DataFrame
In [56]: df.groupby(pd.TimeGrouper(key='date', freq='M')).apply(lambda x: x[['value']].sum())
Out[56]:
            value
date
2000-10-31     10
2000-11-30     13

Changes in read_csv exceptions

In order to standardize the read_csv API for both the c and python engines, both will now raise an EmptyDataError, a subclass of ValueError, in response to empty columns or header (GH12493, GH12506)

Previous behaviour:

In [1]: df = pd.read_csv(StringIO(''), engine='c')
...
ValueError: No columns to parse from file

In [2]: df = pd.read_csv(StringIO(''), engine='python')
...
StopIteration

New behaviour:

In [1]: df = pd.read_csv(StringIO(''), engine='c')
...
pandas.io.common.EmptyDataError: No columns to parse from file

In [2]: df = pd.read_csv(StringIO(''), engine='python')
...
pandas.io.common.EmptyDataError: No columns to parse from file

In addition to this error change, several others have been made as well:

  • CParserError now sub-classes ValueError instead of just a Exception (GH12551)
  • A CParserError is now raised instead of a generic Exception in read_csv when the c engine cannot parse a column (GH12506)
  • A ValueError is now raised instead of a generic Exception in read_csv when the c engine encounters a NaN value in an integer column (GH12506)
  • A ValueError is now raised instead of a generic Exception in read_csv when true_values is specified, and the c engine encounters an element in a column containing unencodable bytes (GH12506)
  • pandas.parser.OverflowError exception has been removed and has been replaced with Python’s built-in OverflowError exception (GH12506)
  • pd.read_csv() no longer allows a combination of strings and integers for the usecols parameter (GH12678)

to_datetime error changes

Bugs in pd.to_datetime() when passing a unit with convertible entries and errors='coerce' or non-convertible with errors='ignore'. Furthermore, an OutOfBoundsDateime exception will be raised when an out-of-range value is encountered for that unit when errors='raise'. (GH11758, GH13052, GH13059)

Previous behaviour:

In [27]: pd.to_datetime(1420043460, unit='s', errors='coerce')
Out[27]: NaT

In [28]: pd.to_datetime(11111111, unit='D', errors='ignore')
OverflowError: Python int too large to convert to C long

In [29]: pd.to_datetime(11111111, unit='D', errors='raise')
OverflowError: Python int too large to convert to C long

New behaviour:

In [2]: pd.to_datetime(1420043460, unit='s', errors='coerce')
Out[2]: Timestamp('2014-12-31 16:31:00')

In [3]: pd.to_datetime(11111111, unit='D', errors='ignore')
Out[3]: 11111111

In [4]: pd.to_datetime(11111111, unit='D', errors='raise')
OutOfBoundsDatetime: cannot convert input with unit 'D'

Other API changes

  • .swaplevel() for Series, DataFrame, Panel, and MultiIndex now features defaults for its first two parameters i and j that swap the two innermost levels of the index. (GH12934)
  • .searchsorted() for Index and TimedeltaIndex now accept a sorter argument to maintain compatibility with numpy’s searchsorted function (GH12238)
  • Period and PeriodIndex now raises IncompatibleFrequency error which inherits ValueError rather than raw ValueError (GH12615)
  • Series.apply for category dtype now applies the passed function to each of the .categories (and not the .codes), and returns a category dtype if possible (GH12473)
  • read_csv will now raise a TypeError if parse_dates is neither a boolean, list, or dictionary (matches the doc-string) (GH5636)
  • The default for .query()/.eval() is now engine=None, which will use numexpr if it’s installed; otherwise it will fallback to the python engine. This mimics the pre-0.18.1 behavior if numexpr is installed (and which, previously, if numexpr was not installed, .query()/.eval() would raise). (GH12749)
  • pd.show_versions() now includes pandas_datareader version (GH12740)
  • Provide a proper __name__ and __qualname__ attributes for generic functions (GH12021)
  • pd.concat(ignore_index=True) now uses RangeIndex as default (GH12695)
  • pd.merge() and DataFrame.join() will show a UserWarning when merging/joining a single- with a multi-leveled dataframe (GH9455, GH12219)
  • Compat with scipy > 0.17 for deprecated piecewise_polynomial interpolation method; support for the replacement from_derivatives method (GH12887)

Deprecations

  • The method name Index.sym_diff() is deprecated and can be replaced by Index.symmetric_difference() (GH12591)
  • The method name Categorical.sort() is deprecated in favor of Categorical.sort_values() (GH12882)

Performance Improvements

  • Improved speed of SAS reader (GH12656, GH12961)
  • Performance improvements in .groupby(..).cumcount() (GH11039)
  • Improved memory usage in pd.read_csv() when using skiprows=an_integer (GH13005)
  • Improved performance of DataFrame.to_sql when checking case sensitivity for tables. Now only checks if table has been created correctly when table name is not lower case. (GH12876)
  • Improved performance of Period construction and time series plotting (GH12903, GH11831).
  • Improved performance of .str.encode() and .str.decode() methods (GH13008)
  • Improved performance of to_numeric if input is numeric dtype (GH12777)
  • Improved performance of sparse arithmetic with IntIndex (GH13036)

Bug Fixes

  • usecols parameter in pd.read_csv is now respected even when the lines of a CSV file are not even (GH12203)
  • Bug in groupby.transform(..) when axis=1 is specified with a non-monotonic ordered index (GH12713)
  • Bug in Period and PeriodIndex creation raises KeyError if freq="Minute" is specified. Note that “Minute” freq is deprecated in v0.17.0, and recommended to use freq="T" instead (GH11854)
  • Bug in .resample(...).count() with a PeriodIndex always raising a TypeError (GH12774)
  • Bug in .resample(...) with a PeriodIndex casting to a DatetimeIndex when empty (GH12868)
  • Bug in .resample(...) with a PeriodIndex when resampling to an existing frequency (GH12770)
  • Bug in printing data which contains Period with different freq raises ValueError (GH12615)
  • Bug in Series construction with Categorical and dtype='category' is specified (GH12574)
  • Bugs in concatenation with a coercable dtype was too aggressive, resulting in different dtypes in outputformatting when an object was longer than display.max_rows (GH12411, GH12045, GH11594, GH10571, GH12211)
  • Bug in float_format option with option not being validated as a callable. (GH12706)
  • Bug in GroupBy.filter when dropna=False and no groups fulfilled the criteria (GH12768)
  • Bug in __name__ of .cum* functions (GH12021)
  • Bug in .astype() of a Float64Inde/Int64Index to an Int64Index (GH12881)
  • Bug in roundtripping an integer based index in .to_json()/.read_json() when orient='index' (the default) (GH12866)
  • Bug in plotting Categorical dtypes cause error when attempting stacked bar plot (GH13019)
  • Compat with >= numpy 1.11 for NaT comparions (GH12969)
  • Bug in .drop() with a non-unique MultiIndex. (GH12701)
  • Bug in .concat of datetime tz-aware and naive DataFrames (GH12467)
  • Bug in correctly raising