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.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  1.474071 -0.064034 -1.282782
2000-01-02  0.781836 -1.071357  0.441153
2000-01-03  2.353925  0.583787  0.221471
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  0.901805  1.171216  0.520260
2000-01-09 -1.197071 -1.066969 -0.303421
2000-01-10 -0.858447  0.306996 -0.028665

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    3.456119
B   -0.140361
C   -0.431984
dtype: float64

Multiple aggregations with a list of functions.

In [5]: df.agg(['sum', 'min'])
Out[5]: 
            A         B         C
sum  3.456119 -0.140361 -0.431984
min -1.197071 -1.071357 -1.282782

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]: 
            B         A
max  1.171216       NaN
min -1.071357 -1.197071
sum       NaN  3.456119

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  1.474071  2.671143  0.064034  1.007322  1.282782  0.000000
2000-01-02  0.781836  1.978907  1.071357  0.000000  0.441153  1.723935
2000-01-03  2.353925  3.550996  0.583787  1.655143  0.221471  1.504252
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  0.901805  2.098877  1.171216  2.242573  0.520260  1.803042
2000-01-09  1.197071  0.000000  1.066969  0.004388  0.303421  0.979361
2000-01-10  0.858447  0.338624  0.306996  1.378353  0.028665  1.254117

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.384316  foo 2013-01-01 00:00:00
1  1.574159  foo 2013-01-01 00:00:01
2  1.588931  foo 2013-01-01 00:00:02
3  0.476720  foo 2013-01-01 00:00:03
4  0.473424  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.384316  foo 2013-01-01 00:00:00
1  1.574159  foo 2013-01-01 00:00:01
2  1.588931  foo 2013-01-01 00:00:02
3  0.476720  foo 2013-01-01 00:00:03
4  0.473424  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.384316
1    1.574159
2    1.588931
3    0.476720
4    0.473424
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   21  62  10          17
1   21  62  10           Y
2   21  62  10          13
3   21  62  10           8
4   21  62  10          22
5   21  62  10           3
6   21  62  10          19
..  ..  ..  ..         ...
93  21  62  10          17
94  21  62  10           Y
95  21  62  10           Y
96  21  62  10          22
97  21  62  10           5
98  21  62  10          20
99  21  62  10           X

[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             42.0  124.0  20.0
3            105.0  310.0  50.0
4             63.0  186.0  30.0
5             84.0  248.0  40.0
6             84.0  248.0  40.0
7             63.0  186.0  30.0
8            189.0  558.0  90.0
...            ...    ...   ...
20           126.0  372.0  60.0
21            42.0  124.0  20.0
22            84.0  248.0  40.0
X             63.0  186.0  30.0
Y            126.0  372.0  60.0
1              NaN    NaN   NaN
12             NaN    NaN   NaN

[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":[{"type":"integer","name":"idx"},{"type":"integer","name":"A"},{"type":"string","name":"B"},{"type":"datetime","name":"C"}],"pandas_version":"0.20.0","primaryKey":["idx"]}, "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 500 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 NaN       NaN
2         NaN NaN NaN NaN       NaN
3         NaN NaN NaN NaN  0.997522
4         NaN NaN NaN NaN       NaN
5         NaN NaN NaN NaN  0.911034
6         NaN NaN NaN NaN       NaN
..        ...  ..  ..  ..       ...
993  0.925879 NaN NaN NaN       NaN
994       NaN NaN NaN NaN  0.955585
995       NaN NaN NaN NaN       NaN
996       NaN NaN NaN NaN       NaN
997       NaN NaN NaN NaN       NaN
998       NaN NaN NaN NaN  0.904855
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 500 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]: 
   C  B
A      
1  0  3
2  3  7

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]: 
   bar  foo
A          
1    0    3
2    3    7

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)

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 a ValueError in .resample(..).fillna(..) when passing a non-string (GH12952)
  • Bug fixes in various encoding and header processing issues in pd.read_sas() (GH12659, GH12654, GH12647, GH12809)
  • Bug in pd.crosstab() where would silently ignore aggfunc if values=None (GH12569).
  • Potential segfault in DataFrame.to_json when serialising datetime.time (GH11473).
  • Potential segfault in DataFrame.to_json when attempting to serialise 0d array (GH11299).
  • Segfault in to_json when attempting to serialise a DataFrame or Series with non-ndarray values; now supports serialization of category, sparse, and datetime64[ns, tz] dtypes (GH10778).
  • Bug in DataFrame.to_json with unsupported dtype not passed to default handler (GH12554).
  • Bug in .align not returning the sub-class (GH12983)
  • Bug in aligning a Series with a DataFrame (GH13037)
  • Bug in ABCPanel in which Panel4D was not being considered as a valid instance of this generic type (GH12810)
  • Bug in consistency of .name on .groupby(..).apply(..) cases (GH12363)
  • Bug in Timestamp.__repr__ that caused pprint to fail in nested structures (GH12622)
  • Bug in Timedelta.min and Timedelta.max, the properties now report the true minimum/maximum timedeltas as recognized by pandas. See the documentation. (GH12727)
  • Bug in .quantile() with interpolation may coerce to float unexpectedly (GH12772)
  • Bug in .quantile() with empty Series may return scalar rather than empty Series (GH12772)
  • Bug in .loc with out-of-bounds in a large indexer would raise IndexError rather than KeyError (GH12527)
  • Bug in resampling when using a TimedeltaIndex and .asfreq(), would previously not include the final fencepost (GH12926)
  • Bug in equality testing with a Categorical in a DataFrame (GH12564)
  • Bug in GroupBy.first(), .last() returns incorrect row when TimeGrouper is used (GH7453)
  • Bug in pd.read_csv() with the c engine when specifying skiprows with newlines in quoted items (GH10911, GH12775)
  • Bug in DataFrame timezone lost when assigning tz-aware datetime Series with alignment (GH12981)
  • Bug in .value_counts() when normalize=True and dropna=True where nulls still contributed to the normalized count (GH12558)
  • Bug in Series.value_counts() loses name if its dtype is category (GH12835)
  • Bug in Series.value_counts() loses timezone info (GH12835)
  • Bug in Series.value_counts(normalize=True) with Categorical raises UnboundLocalError (GH12835)
  • Bug in Panel.fillna() ignoring inplace=True (GH12633)
  • Bug in pd.read_csv() when specifying names, usecols, and parse_dates simultaneously with the c engine (GH9755)
  • Bug in pd.read_csv() when specifying delim_whitespace=True and lineterminator simultaneously with the c engine (GH12912)
  • Bug in Series.rename, DataFrame.rename and DataFrame.rename_axis not treating Series as mappings to relabel (GH12623).
  • Clean in .rolling.min and .rolling.max to enhance dtype handling (GH12373)
  • Bug in groupby where complex types are coerced to float (GH12902)
  • Bug in Series.map raises TypeError if its dtype is category or tz-aware datetime (GH12473)
  • Bugs on 32bit platforms for some test comparisons (GH12972)
  • Bug in index coercion when falling back from RangeIndex construction (GH12893)
  • Better error message in window functions when invalid argument (e.g. a float window) is passed (GH12669)
  • Bug in slicing subclassed DataFrame defined to return subclassed Series may return normal Series (GH11559)
  • Bug in .str accessor methods may raise ValueError if input has name and the result is DataFrame or MultiIndex (GH12617)
  • Bug in DataFrame.last_valid_index() and DataFrame.first_valid_index() on empty frames (GH12800)
  • Bug in CategoricalIndex.get_loc returns different result from regular Index (GH12531)
  • Bug in PeriodIndex.resample where name not propagated (GH12769)
  • Bug in date_range closed keyword and timezones (GH12684).
  • Bug in pd.concat raises AttributeError when input data contains tz-aware datetime and timedelta (GH12620)
  • Bug in pd.concat did not handle empty Series properly (GH11082)
  • Bug in .plot.bar alginment when width is specified with int (GH12979)
  • Bug in fill_value is ignored if the argument to a binary operator is a constant (GH12723)
  • Bug in pd.read_html() when using bs4 flavor and parsing table with a header and only one column (GH9178)
  • Bug in .pivot_table when margins=True and dropna=True where nulls still contributed to margin count (GH12577)
  • Bug in .pivot_table when dropna=False where table index/column names disappear (GH12133)
  • Bug in pd.crosstab() when margins=True and dropna=False which raised (GH12642)
  • Bug in Series.name when name attribute can be a hashable type (GH12610)
  • Bug in .describe() resets categorical columns information (GH11558)
  • Bug where loffset argument was not applied when calling resample().count() on a timeseries (GH12725)
  • pd.read_excel() now accepts column names associated with keyword argument names (GH12870)
  • Bug in pd.to_numeric() with Index returns np.ndarray, rather than Index (GH12777)
  • Bug in pd.to_numeric() with datetime-like may raise TypeError (GH12777)
  • Bug in pd.to_numeric() with scalar raises ValueError (GH12777)

v0.18.0 (March 13, 2016)

This is a major release from 0.17.1 and includes a small 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.

Warning

pandas >= 0.18.0 no longer supports compatibility with Python version 2.6 and 3.3 (GH7718, GH11273)

Warning

numexpr version 2.4.4 will now show a warning and not be used as a computation back-end for pandas because of some buggy behavior. This does not affect other versions (>= 2.1 and >= 2.4.6). (GH12489)

Highlights include:

  • Moving and expanding window functions are now methods on Series and DataFrame, similar to .groupby, see here.
  • Adding support for a RangeIndex as a specialized form of the Int64Index for memory savings, see here.
  • API breaking change to the .resample method to make it more .groupby like, see here.
  • Removal of support for positional indexing with floats, which was deprecated since 0.14.0. This will now raise a TypeError, see here.
  • The .to_xarray() function has been added for compatibility with the xarray package, see here.
  • The read_sas function has been enhanced to read sas7bdat files, see here.
  • Addition of the .str.extractall() method, and API changes to the .str.extract() method and .str.cat() method.
  • pd.test() top-level nose test runner is available (GH4327).

Check the API Changes and deprecations before updating.

New features

Window functions are now methods

Window functions have been refactored to be methods on Series/DataFrame objects, rather than top-level functions, which are now deprecated. This allows these window-type functions, to have a similar API to that of .groupby. See the full documentation here (GH11603, GH12373)

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

In [2]: df = pd.DataFrame({'A' : range(10), 'B' : np.random.randn(10)})

In [3]: df
Out[3]: 
   A         B
0  0  0.471435
1  1 -1.190976
2  2  1.432707
3  3 -0.312652
4  4 -0.720589
5  5  0.887163
6  6  0.859588
7  7 -0.636524
8  8  0.015696
9  9 -2.242685

Previous Behavior:

In [8]: pd.rolling_mean(df,window=3)
        FutureWarning: pd.rolling_mean is deprecated for DataFrame and will be removed in a future version, replace with
                       DataFrame.rolling(window=3,center=False).mean()
Out[8]:
    A         B
0 NaN       NaN
1 NaN       NaN
2   1  0.237722
3   2 -0.023640
4   3  0.133155
5   4 -0.048693
6   5  0.342054
7   6  0.370076
8   7  0.079587
9   8 -0.954504

New Behavior:

In [4]: r = df.rolling(window=3)

These show a descriptive repr

In [5]: r
Out[5]: Rolling [window=3,center=False,axis=0]

with tab-completion of available methods and properties.

In [9]: r.
r.A           r.agg         r.apply       r.count       r.exclusions  r.max         r.median      r.name        r.skew        r.sum
r.B           r.aggregate   r.corr        r.cov         r.kurt        r.mean        r.min         r.quantile    r.std         r.var

The methods operate on the Rolling object itself

In [6]: r.mean()
Out[6]: 
     A         B
0  NaN       NaN
1  NaN       NaN
2  1.0  0.237722
3  2.0 -0.023640
4  3.0  0.133155
5  4.0 -0.048693
6  5.0  0.342054
7  6.0  0.370076
8  7.0  0.079587
9  8.0 -0.954504

They provide getitem accessors

In [7]: r['A'].mean()
Out[7]: 
0    NaN
1    NaN
2    1.0
3    2.0
4    3.0
5    4.0
6    5.0
7    6.0
8    7.0
9    8.0
Name: A, dtype: float64

And multiple aggregations

In [8]: r.agg({'A' : ['mean','std'],
   ...:        'B' : ['mean','std']})
   ...: 
Out[8]: 
          B              A     
       mean       std mean  std
0       NaN       NaN  NaN  NaN
1       NaN       NaN  NaN  NaN
2  0.237722  1.327364  1.0  1.0
3 -0.023640  1.335505  2.0  1.0
4  0.133155  1.143778  3.0  1.0
5 -0.048693  0.835747  4.0  1.0
6  0.342054  0.920379  5.0  1.0
7  0.370076  0.871850  6.0  1.0
8  0.079587  0.750099  7.0  1.0
9 -0.954504  1.162285  8.0  1.0

Changes to rename

Series.rename and NDFrame.rename_axis can now take a scalar or list-like argument for altering the Series or axis name, in addition to their old behaviors of altering labels. (GH9494, GH11965)

In [9]: s = pd.Series(np.random.randn(5))

In [10]: s.rename('newname')
Out[10]: 
0    1.150036
1    0.991946
2    0.953324
3   -2.021255
4   -0.334077
Name: newname, dtype: float64
In [11]: df = pd.DataFrame(np.random.randn(5, 2))

In [12]: (df.rename_axis("indexname")
   ....:    .rename_axis("columns_name", axis="columns"))
   ....: 
Out[12]: 
columns_name         0         1
indexname                       
0             0.002118  0.405453
1             0.289092  1.321158
2            -1.546906 -0.202646
3            -0.655969  0.193421
4             0.553439  1.318152

The new functionality works well in method chains. Previously these methods only accepted functions or dicts mapping a label to a new label. This continues to work as before for function or dict-like values.

Range Index

A RangeIndex has been added to the Int64Index sub-classes to support a memory saving alternative for common use cases. This has a similar implementation to the python range object (xrange in python 2), in that it only stores the start, stop, and step values for the index. It will transparently interact with the user API, converting to Int64Index if needed.

This will now be the default constructed index for NDFrame objects, rather than previous an Int64Index. (GH939, GH12070, GH12071, GH12109, GH12888)

Previous Behavior:

In [3]: s = pd.Series(range(1000))

In [4]: s.index
Out[4]:
Int64Index([  0,   1,   2,   3,   4,   5,   6,   7,   8,   9,
            ...
            990, 991, 992, 993, 994, 995, 996, 997, 998, 999], dtype='int64', length=1000)

In [6]: s.index.nbytes
Out[6]: 8000

New Behavior:

In [13]: s = pd.Series(range(1000))

In [14]: s.index
Out[14]: RangeIndex(start=0, stop=1000, step=1)

In [15]: s.index.nbytes
Out[15]: 80

Changes to str.extract

The .str.extract method takes a regular expression with capture groups, finds the first match in each subject string, and returns the contents of the capture groups (GH11386).

In v0.18.0, the expand argument was added to extract.

  • expand=False: it returns a Series, Index, or DataFrame, depending on the subject and regular expression pattern (same behavior as pre-0.18.0).
  • expand=True: it always returns a DataFrame, which is more consistent and less confusing from the perspective of a user.

Currently the default is expand=None which gives a FutureWarning and uses expand=False. To avoid this warning, please explicitly specify expand.

In [1]: pd.Series(['a1', 'b2', 'c3']).str.extract('[ab](\d)', expand=None)
FutureWarning: currently extract(expand=None) means expand=False (return Index/Series/DataFrame)
but in a future version of pandas this will be changed to expand=True (return DataFrame)

Out[1]:
0      1
1      2
2    NaN
dtype: object

Extracting a regular expression with one group returns a Series if expand=False.

In [16]: pd.Series(['a1', 'b2', 'c3']).str.extract('[ab](\d)', expand=False)
Out[16]: 
0      1
1      2
2    NaN
dtype: object

It returns a DataFrame with one column if expand=True.

In [17]: pd.Series(['a1', 'b2', 'c3']).str.extract('[ab](\d)', expand=True)
Out[17]: 
     0
0    1
1    2
2  NaN

Calling on an Index with a regex with exactly one capture group returns an Index if expand=False.

In [18]: s = pd.Series(["a1", "b2", "c3"], ["A11", "B22", "C33"])

In [19]: s.index
Out[19]: Index(['A11', 'B22', 'C33'], dtype='object')

In [20]: s.index.str.extract("(?P<letter>[a-zA-Z])", expand=False)
Out[20]: Index(['A', 'B', 'C'], dtype='object', name='letter')

It returns a DataFrame with one column if expand=True.

In [21]: s.index.str.extract("(?P<letter>[a-zA-Z])", expand=True)
Out[21]: 
  letter
0      A
1      B
2      C

Calling on an Index with a regex with more than one capture group raises ValueError if expand=False.

>>> s.index.str.extract("(?P<letter>[a-zA-Z])([0-9]+)", expand=False)
ValueError: only one regex group is supported with Index

It returns a DataFrame if expand=True.

In [22]: s.index.str.extract("(?P<letter>[a-zA-Z])([0-9]+)", expand=True)
Out[22]: 
  letter   1
0      A  11
1      B  22
2      C  33

In summary, extract(expand=True) always returns a DataFrame with a row for every subject string, and a column for every capture group.

Addition of str.extractall

The .str.extractall method was added (GH11386). Unlike extract, which returns only the first match.

In [23]: s = pd.Series(["a1a2", "b1", "c1"], ["A", "B", "C"])

In [24]: s
Out[24]: 
A    a1a2
B      b1
C      c1
dtype: object

In [25]: s.str.extract("(?P<letter>[ab])(?P<digit>\d)", expand=False)
Out[25]: 
  letter digit
A      a     1
B      b     1
C    NaN   NaN

The extractall method returns all matches.

In [26]: s.str.extractall("(?P<letter>[ab])(?P<digit>\d)")
Out[26]: 
        letter digit
  match             
A 0          a     1
  1          a     2
B 0          b     1

Changes to str.cat

The method .str.cat() concatenates the members of a Series. Before, if NaN values were present in the Series, calling .str.cat() on it would return NaN, unlike the rest of the Series.str.* API. This behavior has been amended to ignore NaN values by default. (GH11435).

A new, friendlier ValueError is added to protect against the mistake of supplying the sep as an arg, rather than as a kwarg. (GH11334).

In [27]: pd.Series(['a','b',np.nan,'c']).str.cat(sep=' ')
Out[27]: 'a b c'

In [28]: pd.Series(['a','b',np.nan,'c']).str.cat(sep=' ', na_rep='?')
Out[28]: 'a b ? c'
In [2]: pd.Series(['a','b',np.nan,'c']).str.cat(' ')
ValueError: Did you mean to supply a `sep` keyword?

Datetimelike rounding

DatetimeIndex, Timestamp, TimedeltaIndex, Timedelta have gained the .round(), .floor() and .ceil() method for datetimelike rounding, flooring and ceiling. (GH4314, GH11963)

Naive datetimes

In [29]: dr = pd.date_range('20130101 09:12:56.1234', periods=3)

In [30]: dr
Out[30]: 
DatetimeIndex(['2013-01-01 09:12:56.123400', '2013-01-02 09:12:56.123400',
               '2013-01-03 09:12:56.123400'],
              dtype='datetime64[ns]', freq='D')

In [31]: dr.round('s')
Out[31]: 
DatetimeIndex(['2013-01-01 09:12:56', '2013-01-02 09:12:56',
               '2013-01-03 09:12:56'],
              dtype='datetime64[ns]', freq=None)

# Timestamp scalar
In [32]: dr[0]
Out[32]: Timestamp('2013-01-01 09:12:56.123400', freq='D')

In [33]: dr[0].round('10s')
Out[33]: Timestamp('2013-01-01 09:13:00')

Tz-aware are rounded, floored and ceiled in local times

In [34]: dr = dr.tz_localize('US/Eastern')

In [35]: dr
Out[35]: 
DatetimeIndex(['2013-01-01 09:12:56.123400-05:00',
               '2013-01-02 09:12:56.123400-05:00',
               '2013-01-03 09:12:56.123400-05:00'],
              dtype='datetime64[ns, US/Eastern]', freq='D')

In [36]: dr.round('s')
Out[36]: 
DatetimeIndex(['2013-01-01 09:12:56-05:00', '2013-01-02 09:12:56-05:00',
               '2013-01-03 09:12:56-05:00'],
              dtype='datetime64[ns, US/Eastern]', freq=None)

Timedeltas

In [37]: t = timedelta_range('1 days 2 hr 13 min 45 us',periods=3,freq='d')

In [38]: t
Out[38]: 
TimedeltaIndex(['1 days 02:13:00.000045', '2 days 02:13:00.000045',
                '3 days 02:13:00.000045'],
               dtype='timedelta64[ns]', freq='D')

In [39]: t.round('10min')
Out[39]: TimedeltaIndex(['1 days 02:10:00', '2 days 02:10:00', '3 days 02:10:00'], dtype='timedelta64[ns]', freq=None)

# Timedelta scalar
In [40]: t[0]
Out[40]: Timedelta('1 days 02:13:00.000045')

In [41]: t[0].round('2h')
Out[41]: Timedelta('1 days 02:00:00')

In addition, .round(), .floor() and .ceil() will be available thru the .dt accessor of Series.

In [42]: s = pd.Series(dr)

In [43]: s
Out[43]: 
0   2013-01-01 09:12:56.123400-05:00
1   2013-01-02 09:12:56.123400-05:00
2   2013-01-03 09:12:56.123400-05:00
dtype: datetime64[ns, US/Eastern]

In [44]: s.dt.round('D')
Out[44]: 
0   2013-01-01 00:00:00-05:00
1   2013-01-02 00:00:00-05:00
2   2013-01-03 00:00:00-05:00
dtype: datetime64[ns, US/Eastern]

Formatting of Integers in FloatIndex

Integers in FloatIndex, e.g. 1., are now formatted with a decimal point and a 0 digit, e.g. 1.0 (GH11713) This change not only affects the display to the console, but also the output of IO methods like .to_csv or .to_html.

Previous Behavior:

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

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

In [4]: s.index
Out[4]: Float64Index([0.0, 1.0, 2.0], dtype='float64')

In [5]: print(s.to_csv(path=None))
0,1
1,2
2,3

New Behavior:

In [45]: s = pd.Series([1,2,3], index=np.arange(3.))

In [46]: s
Out[46]: 
0.0    1
1.0    2
2.0    3
dtype: int64

In [47]: s.index
Out[47]: Float64Index([0.0, 1.0, 2.0], dtype='float64')

In [48]: print(s.to_csv(path=None))
0.0,1
1.0,2
2.0,3

Changes to dtype assignment behaviors

When a DataFrame’s slice is updated with a new slice of the same dtype, the dtype of the DataFrame will now remain the same. (GH10503)

Previous Behavior:

In [5]: df = pd.DataFrame({'a': [0, 1, 1],
                           'b': pd.Series([100, 200, 300], dtype='uint32')})

In [7]: df.dtypes
Out[7]:
a     int64
b    uint32
dtype: object

In [8]: ix = df['a'] == 1

In [9]: df.loc[ix, 'b'] = df.loc[ix, 'b']

In [11]: df.dtypes
Out[11]:
a    int64
b    int64
dtype: object

New Behavior:

In [49]: df = pd.DataFrame({'a': [0, 1, 1],
   ....:                    'b': pd.Series([100, 200, 300], dtype='uint32')})
   ....: 

In [50]: df.dtypes
Out[50]: 
a     int64
b    uint32
dtype: object

In [51]: ix = df['a'] == 1

In [52]: df.loc[ix, 'b'] = df.loc[ix, 'b']

In [53]: df.dtypes
Out[53]: 
a     int64
b    uint32
dtype: object

When a DataFrame’s integer slice is partially updated with a new slice of floats that could potentially be downcasted to integer without losing precision, the dtype of the slice will be set to float instead of integer.

Previous Behavior:

In [4]: df = pd.DataFrame(np.array(range(1,10)).reshape(3,3),
                          columns=list('abc'),
                          index=[[4,4,8], [8,10,12]])

In [5]: df
Out[5]:
      a  b  c
4 8   1  2  3
  10  4  5  6
8 12  7  8  9

In [7]: df.ix[4, 'c'] = np.array([0., 1.])

In [8]: df
Out[8]:
      a  b  c
4 8   1  2  0
  10  4  5  1
8 12  7  8  9

New Behavior:

In [54]: df = pd.DataFrame(np.array(range(1,10)).reshape(3,3),
   ....:                   columns=list('abc'),
   ....:                   index=[[4,4,8], [8,10,12]])
   ....: 

In [55]: df
Out[55]: 
      a  b  c
4 8   1  2  3
  10  4  5  6
8 12  7  8  9

In [56]: df.loc[4, 'c'] = np.array([0., 1.])

In [57]: df
Out[57]: 
      a  b    c
4 8   1  2  0.0
  10  4  5  1.0
8 12  7  8  9.0

to_xarray

In a future version of pandas, we will be deprecating Panel and other > 2 ndim objects. In order to provide for continuity, all NDFrame objects have gained the .to_xarray() method in order to convert to xarray objects, which has a pandas-like interface for > 2 ndim. (GH11972)

See the xarray full-documentation here.

In [1]: p = Panel(np.arange(2*3*4).reshape(2,3,4))

In [2]: p.to_xarray()
Out[2]:
<xarray.DataArray (items: 2, major_axis: 3, minor_axis: 4)>
array([[[ 0,  1,  2,  3],
        [ 4,  5,  6,  7],
        [ 8,  9, 10, 11]],

       [[12, 13, 14, 15],
        [16, 17, 18, 19],
        [20, 21, 22, 23]]])
Coordinates:
  * items       (items) int64 0 1
  * major_axis  (major_axis) int64 0 1 2
  * minor_axis  (minor_axis) int64 0 1 2 3

Latex Representation

DataFrame has gained a ._repr_latex_() method in order to allow for conversion to latex in a ipython/jupyter notebook using nbconvert. (GH11778)

Note that this must be activated by setting the option pd.display.latex.repr=True (GH12182)

For example, if you have a jupyter notebook you plan to convert to latex using nbconvert, place the statement pd.display.latex.repr=True in the first cell to have the contained DataFrame output also stored as latex.

The options display.latex.escape and display.latex.longtable have also been added to the configuration and are used automatically by the to_latex method. See the available options docs for more info.

pd.read_sas() changes

read_sas has gained the ability to read SAS7BDAT files, including compressed files. The files can be read in entirety, or incrementally. For full details see here. (GH4052)

Other enhancements

  • Handle truncated floats in SAS xport files (GH11713)
  • Added option to hide index in Series.to_string (GH11729)
  • read_excel now supports s3 urls of the format s3://bucketname/filename (GH11447)
  • add support for AWS_S3_HOST env variable when reading from s3 (GH12198)
  • A simple version of Panel.round() is now implemented (GH11763)
  • For Python 3.x, round(DataFrame), round(Series), round(Panel) will work (GH11763)
  • sys.getsizeof(obj) returns the memory usage of a pandas object, including the values it contains (GH11597)
  • Series gained an is_unique attribute (GH11946)
  • DataFrame.quantile and Series.quantile now accept interpolation keyword (GH10174).
  • Added DataFrame.style.format for more flexible formatting of cell values (GH11692)
  • DataFrame.select_dtypes now allows the np.float16 typecode (GH11990)
  • pivot_table() now accepts most iterables for the values parameter (GH12017)
  • Added Google BigQuery service account authentication support, which enables authentication on remote servers. (GH11881, GH12572). For further details see here
  • HDFStore is now iterable: for k in store is equivalent to for k in store.keys() (GH12221).
  • Add missing methods/fields to .dt for Period (GH8848)
  • The entire codebase has been PEP-ified (GH12096)

Backwards incompatible API changes

  • the leading whitespaces have been removed from the output of .to_string(index=False) method (GH11833)
  • the out parameter has been removed from the Series.round() method. (GH11763)
  • DataFrame.round() leaves non-numeric columns unchanged in its return, rather than raises. (GH11885)
  • DataFrame.head(0) and DataFrame.tail(0) return empty frames, rather than self. (GH11937)
  • Series.head(0) and Series.tail(0) return empty series, rather than self. (GH11937)
  • to_msgpack and read_msgpack encoding now defaults to 'utf-8'. (GH12170)
  • the order of keyword arguments to text file parsing functions (.read_csv(), .read_table(), .read_fwf()) changed to group related arguments. (GH11555)
  • NaTType.isoformat now returns the string 'NaT to allow the result to be passed to the constructor of Timestamp. (GH12300)

NaT and Timedelta operations

NaT and Timedelta have expanded arithmetic operations, which are extended to Series arithmetic where applicable. Operations defined for datetime64[ns] or timedelta64[ns] are now also defined for NaT (GH11564).

NaT now supports arithmetic operations with integers and floats.

In [58]: pd.NaT * 1
Out[58]: NaT

In [59]: pd.NaT * 1.5
Out[59]: NaT

In [60]: pd.NaT / 2
Out[60]: NaT

In [61]: pd.NaT * np.nan
Out[61]: NaT

NaT defines more arithmetic operations with datetime64[ns] and timedelta64[ns].

In [62]: pd.NaT / pd.NaT
Out[62]: nan

In [63]: pd.Timedelta('1s') / pd.NaT
Out[63]: nan

NaT may represent either a datetime64[ns] null or a timedelta64[ns] null. Given the ambiguity, it is treated as a timedelta64[ns], which allows more operations to succeed.

In [64]: pd.NaT + pd.NaT
Out[64]: NaT

# same as
In [65]: pd.Timedelta('1s') + pd.Timedelta('1s')
Out[65]: Timedelta('0 days 00:00:02')

as opposed to

In [3]: pd.Timestamp('19900315') + pd.Timestamp('19900315')
TypeError: unsupported operand type(s) for +: 'Timestamp' and 'Timestamp'

However, when wrapped in a Series whose dtype is datetime64[ns] or timedelta64[ns], the dtype information is respected.

In [1]: pd.Series([pd.NaT], dtype='<M8[ns]') + pd.Series([pd.NaT], dtype='<M8[ns]')
TypeError: can only operate on a datetimes for subtraction,
           but the operator [__add__] was passed
In [66]: pd.Series([pd.NaT], dtype='<m8[ns]') + pd.Series([pd.NaT], dtype='<m8[ns]')
Out[66]: 
0   NaT
dtype: timedelta64[ns]

Timedelta division by floats now works.

In [67]: pd.Timedelta('1s') / 2.0
Out[67]: Timedelta('0 days 00:00:00.500000')

Subtraction by Timedelta in a Series by a Timestamp works (GH11925)

In [68]: ser = pd.Series(pd.timedelta_range('1 day', periods=3))

In [69]: ser
Out[69]: 
0   1 days
1   2 days
2   3 days
dtype: timedelta64[ns]

In [70]: pd.Timestamp('2012-01-01') - ser
Out[70]: 
0   2011-12-31
1   2011-12-30
2   2011-12-29
dtype: datetime64[ns]

NaT.isoformat() now returns 'NaT'. This change allows allows pd.Timestamp to rehydrate any timestamp like object from its isoformat (GH12300).

Changes to msgpack

Forward incompatible changes in msgpack writing format were made over 0.17.0 and 0.18.0; older versions of pandas cannot read files packed by newer versions (GH12129, GH10527)

Bugs in to_msgpack and read_msgpack introduced in 0.17.0 and fixed in 0.18.0, caused files packed in Python 2 unreadable by Python 3 (GH12142). The following table describes the backward and forward compat of msgpacks.

Warning

Packed with Can be unpacked with
pre-0.17 / Python 2 any
pre-0.17 / Python 3 any
0.17 / Python 2
  • ==0.17 / Python 2
  • >=0.18 / any Python
0.17 / Python 3 >=0.18 / any Python
0.18 >= 0.18

0.18.0 is backward-compatible for reading files packed by older versions, except for files packed with 0.17 in Python 2, in which case only they can only be unpacked in Python 2.

Signature change for .rank

Series.rank and DataFrame.rank now have the same signature (GH11759)

Previous signature

In [3]: pd.Series([0,1]).rank(method='average', na_option='keep',
                              ascending=True, pct=False)
Out[3]:
0    1
1    2
dtype: float64

In [4]: pd.DataFrame([0,1]).rank(axis=0, numeric_only=None,
                                 method='average', na_option='keep',
                                 ascending=True, pct=False)
Out[4]:
   0
0  1
1  2

New signature

In [71]: pd.Series([0,1]).rank(axis=0, method='average', numeric_only=None,
   ....:                       na_option='keep', ascending=True, pct=False)
   ....: 
Out[71]: 
0    1.0
1    2.0
dtype: float64

In [72]: pd.DataFrame([0,1]).rank(axis=0, method='average', numeric_only=None,
   ....:                          na_option='keep', ascending=True, pct=False)
   ....: 
Out[72]: 
     0
0  1.0
1  2.0

Bug in QuarterBegin with n=0

In previous versions, the behavior of the QuarterBegin offset was inconsistent depending on the date when the n parameter was 0. (GH11406)

The general semantics of anchored offsets for n=0 is to not move the date when it is an anchor point (e.g., a quarter start date), and otherwise roll forward to the next anchor point.

In [73]: d = pd.Timestamp('2014-02-01')

In [74]: d
Out[74]: Timestamp('2014-02-01 00:00:00')

In [75]: d + pd.offsets.QuarterBegin(n=0, startingMonth=2)
Out[75]: Timestamp('2014-02-01 00:00:00')

In [76]: d + pd.offsets.QuarterBegin(n=0, startingMonth=1)
Out[76]: Timestamp('2014-04-01 00:00:00')

For the QuarterBegin offset in previous versions, the date would be rolled backwards if date was in the same month as the quarter start date.

In [3]: d = pd.Timestamp('2014-02-15')

In [4]: d + pd.offsets.QuarterBegin(n=0, startingMonth=2)
Out[4]: Timestamp('2014-02-01 00:00:00')

This behavior has been corrected in version 0.18.0, which is consistent with other anchored offsets like MonthBegin and YearBegin.

In [77]: d = pd.Timestamp('2014-02-15')

In [78]: d + pd.offsets.QuarterBegin(n=0, startingMonth=2)
Out[78]: Timestamp('2014-05-01 00:00:00')

Resample API

Like the change in the window functions API above, .resample(...) is changing to have a more groupby-like API. (GH11732, GH12702, GH12202, GH12332, GH12334, GH12348, GH12448).

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

In [80]: df = pd.DataFrame(np.random.rand(10,4),
   ....:                   columns=list('ABCD'),
   ....:                   index=pd.date_range('2010-01-01 09:00:00', periods=10, freq='s'))
   ....: 

In [81]: df
Out[81]: 
                            A         B         C         D
2010-01-01 09:00:00  0.191519  0.622109  0.437728  0.785359
2010-01-01 09:00:01  0.779976  0.272593  0.276464  0.801872
2010-01-01 09:00:02  0.958139  0.875933  0.357817  0.500995
2010-01-01 09:00:03  0.683463  0.712702  0.370251  0.561196
2010-01-01 09:00:04  0.503083  0.013768  0.772827  0.882641
2010-01-01 09:00:05  0.364886  0.615396  0.075381  0.368824
2010-01-01 09:00:06  0.933140  0.651378  0.397203  0.788730
2010-01-01 09:00:07  0.316836  0.568099  0.869127  0.436173
2010-01-01 09:00:08  0.802148  0.143767  0.704261  0.704581
2010-01-01 09:00:09  0.218792  0.924868  0.442141  0.909316

Previous API:

You would write a resampling operation that immediately evaluates. If a how parameter was not provided, it would default to how='mean'.

In [6]: df.resample('2s')
Out[6]:
                         A         B         C         D
2010-01-01 09:00:00  0.485748  0.447351  0.357096  0.793615
2010-01-01 09:00:02  0.820801  0.794317  0.364034  0.531096
2010-01-01 09:00:04  0.433985  0.314582  0.424104  0.625733
2010-01-01 09:00:06  0.624988  0.609738  0.633165  0.612452
2010-01-01 09:00:08  0.510470  0.534317  0.573201  0.806949

You could also specify a how directly

In [7]: df.resample('2s', how='sum')
Out[7]:
                         A         B         C         D
2010-01-01 09:00:00  0.971495  0.894701  0.714192  1.587231
2010-01-01 09:00:02  1.641602  1.588635  0.728068  1.062191
2010-01-01 09:00:04  0.867969  0.629165  0.848208  1.251465
2010-01-01 09:00:06  1.249976  1.219477  1.266330  1.224904
2010-01-01 09:00:08  1.020940  1.068634  1.146402  1.613897

New API:

Now, you can write .resample(..) as a 2-stage operation like .groupby(...), which yields a Resampler.

In [82]: r = df.resample('2s')

In [83]: r
Out[83]: DatetimeIndexResampler [freq=<2 * Seconds>, axis=0, closed=left, label=left, convention=start, base=0]
Downsampling

You can then use this object to perform operations. These are downsampling operations (going from a higher frequency to a lower one).

In [84]: r.mean()
Out[84]: 
                            A         B         C         D
2010-01-01 09:00:00  0.485748  0.447351  0.357096  0.793615
2010-01-01 09:00:02  0.820801  0.794317  0.364034  0.531096
2010-01-01 09:00:04  0.433985  0.314582  0.424104  0.625733
2010-01-01 09:00:06  0.624988  0.609738  0.633165  0.612452
2010-01-01 09:00:08  0.510470  0.534317  0.573201  0.806949
In [85]: r.sum()
Out[85]: 
                            A         B         C         D
2010-01-01 09:00:00  0.971495  0.894701  0.714192  1.587231
2010-01-01 09:00:02  1.641602  1.588635  0.728068  1.062191
2010-01-01 09:00:04  0.867969  0.629165  0.848208  1.251465
2010-01-01 09:00:06  1.249976  1.219477  1.266330  1.224904
2010-01-01 09:00:08  1.020940  1.068634  1.146402  1.613897

Furthermore, resample now supports getitem operations to perform the resample on specific columns.

In [86]: r[['A','C']].mean()
Out[86]: 
                            A         C
2010-01-01 09:00:00  0.485748  0.357096
2010-01-01 09:00:02  0.820801  0.364034
2010-01-01 09:00:04  0.433985  0.424104
2010-01-01 09:00:06  0.624988  0.633165
2010-01-01 09:00:08  0.510470  0.573201

and .aggregate type operations.

In [87]: r.agg({'A' : 'mean', 'B' : 'sum'})
Out[87]: 
                            B         A
2010-01-01 09:00:00  0.894701  0.485748
2010-01-01 09:00:02  1.588635  0.820801
2010-01-01 09:00:04  0.629165  0.433985
2010-01-01 09:00:06  1.219477  0.624988
2010-01-01 09:00:08  1.068634  0.510470

These accessors can of course, be combined

In [88]: r[['A','B']].agg(['mean','sum'])
Out[88]: 
                            A                   B          
                         mean       sum      mean       sum
2010-01-01 09:00:00  0.485748  0.971495  0.447351  0.894701
2010-01-01 09:00:02  0.820801  1.641602  0.794317  1.588635
2010-01-01 09:00:04  0.433985  0.867969  0.314582  0.629165
2010-01-01 09:00:06  0.624988  1.249976  0.609738  1.219477
2010-01-01 09:00:08  0.510470  1.020940  0.534317  1.068634
Upsampling

Upsampling operations take you from a lower frequency to a higher frequency. These are now performed with the Resampler objects with backfill(), ffill(), fillna() and asfreq() methods.

In [89]: s = pd.Series(np.arange(5,dtype='int64'),
   ....:               index=date_range('2010-01-01', periods=5, freq='Q'))
   ....: 

In [90]: s
Out[90]: 
2010-03-31    0
2010-06-30    1
2010-09-30    2
2010-12-31    3
2011-03-31    4
Freq: Q-DEC, dtype: int64

Previously

In [6]: s.resample('M', fill_method='ffill')
Out[6]:
2010-03-31    0
2010-04-30    0
2010-05-31    0
2010-06-30    1
2010-07-31    1
2010-08-31    1
2010-09-30    2
2010-10-31    2
2010-11-30    2
2010-12-31    3
2011-01-31    3
2011-02-28    3
2011-03-31    4
Freq: M, dtype: int64

New API

In [91]: s.resample('M').ffill()
Out[91]: 
2010-03-31    0
2010-04-30    0
2010-05-31    0
2010-06-30    1
2010-07-31    1
2010-08-31    1
2010-09-30    2
2010-10-31    2
2010-11-30    2
2010-12-31    3
2011-01-31    3
2011-02-28    3
2011-03-31    4
Freq: M, dtype: int64

Note

In the new API, you can either downsample OR upsample. The prior implementation would allow you to pass an aggregator function (like mean) even though you were upsampling, providing a bit of confusion.

Previous API will work but with deprecations

Warning

This new API for resample includes some internal changes for the prior-to-0.18.0 API, to work with a deprecation warning in most cases, as the resample operation returns a deferred object. We can intercept operations and just do what the (pre 0.18.0) API did (with a warning). Here is a typical use case:

In [4]: r = df.resample('2s')

In [6]: r*10
pandas/tseries/resample.py:80: FutureWarning: .resample() is now a deferred operation
use .resample(...).mean() instead of .resample(...)

Out[6]:
                      A         B         C         D
2010-01-01 09:00:00  4.857476  4.473507  3.570960  7.936154
2010-01-01 09:00:02  8.208011  7.943173  3.640340  5.310957
2010-01-01 09:00:04  4.339846  3.145823  4.241039  6.257326
2010-01-01 09:00:06  6.249881  6.097384  6.331650  6.124518
2010-01-01 09:00:08  5.104699  5.343172  5.732009  8.069486

However, getting and assignment operations directly on a Resampler will raise a ValueError:

In [7]: r.iloc[0] = 5
ValueError: .resample() is now a deferred operation
use .resample(...).mean() instead of .resample(...)

There is a situation where the new API can not perform all the operations when using original code. This code is intending to resample every 2s, take the mean AND then take the min of those results.

In [4]: df.resample('2s').min()
Out[4]:
A    0.433985
B    0.314582
C    0.357096
D    0.531096
dtype: float64

The new API will:

In [92]: df.resample('2s').min()
Out[92]: 
                            A         B         C         D
2010-01-01 09:00:00  0.191519  0.272593  0.276464  0.785359
2010-01-01 09:00:02  0.683463  0.712702  0.357817  0.500995
2010-01-01 09:00:04  0.364886  0.013768  0.075381  0.368824
2010-01-01 09:00:06  0.316836  0.568099  0.397203  0.436173
2010-01-01 09:00:08  0.218792  0.143767  0.442141  0.704581

The good news is the return dimensions will differ between the new API and the old API, so this should loudly raise an exception.

To replicate the original operation

In [93]: df.resample('2s').mean().min()
Out[93]: 
A    0.433985
B    0.314582
C    0.357096
D    0.531096
dtype: float64

Changes to eval

In prior versions, new columns assignments in an eval expression resulted in an inplace change to the DataFrame. (GH9297, GH8664, GH10486)

In [94]: df = pd.DataFrame({'a': np.linspace(0, 10, 5), 'b': range(5)})

In [95]: df
Out[95]: 
      a  b
0   0.0  0
1   2.5  1
2   5.0  2
3   7.5  3
4  10.0  4
In [12]: df.eval('c = a + b')
FutureWarning: eval expressions containing an assignment currentlydefault to operating inplace.
This will change in a future version of pandas, use inplace=True to avoid this warning.

In [13]: df
Out[13]:
      a  b     c
0   0.0  0   0.0
1   2.5  1   3.5
2   5.0  2   7.0
3   7.5  3  10.5
4  10.0  4  14.0

In version 0.18.0, a new inplace keyword was added to choose whether the assignment should be done inplace or return a copy.

In [96]: df
Out[96]: 
      a  b     c
0   0.0  0   0.0
1   2.5  1   3.5
2   5.0  2   7.0
3   7.5  3  10.5
4  10.0  4  14.0

In [97]: df.eval('d = c - b', inplace=False)
Out[97]: 
      a  b     c     d
0   0.0  0   0.0   0.0
1   2.5  1   3.5   2.5
2   5.0  2   7.0   5.0
3   7.5  3  10.5   7.5
4  10.0  4  14.0  10.0

In [98]: df
Out[98]: 
      a  b     c
0   0.0  0   0.0
1   2.5  1   3.5
2   5.0  2   7.0
3   7.5  3  10.5
4  10.0  4  14.0

In [99]: df.eval('d = c - b', inplace=True)

In [100]: df
Out[100]: 
      a  b     c     d
0   0.0  0   0.0   0.0
1   2.5  1   3.5   2.5
2   5.0  2   7.0   5.0
3   7.5  3  10.5   7.5
4  10.0  4  14.0  10.0

Warning

For backwards compatability, inplace defaults to True if not specified. This will change in a future version of pandas. If your code depends on an inplace assignment you should update to explicitly set inplace=True

The inplace keyword parameter was also added the query method.

In [101]: df.query('a > 5')
Out[101]: 
      a  b     c     d
3   7.5  3  10.5   7.5
4  10.0  4  14.0  10.0

In [102]: df.query('a > 5', inplace=True)

In [103]: df
Out[103]: 
      a  b     c     d
3   7.5  3  10.5   7.5
4  10.0  4  14.0  10.0

Warning

Note that the default value for inplace in a query is False, which is consistent with prior versions.

eval has also been updated to allow multi-line expressions for multiple assignments. These expressions will be evaluated one at a time in order. Only assignments are valid for multi-line expressions.

In [104]: df
Out[104]: 
      a  b     c     d
3   7.5  3  10.5   7.5
4  10.0  4  14.0  10.0

In [105]: df.eval("""
   .....: e = d + a
   .....: f = e - 22
   .....: g = f / 2.0""", inplace=True)
   .....: 

In [106]: df
Out[106]: 
      a  b     c     d     e    f    g
3   7.5  3  10.5   7.5  15.0 -7.0 -3.5
4  10.0  4  14.0  10.0  20.0 -2.0 -1.0

Other API Changes

  • DataFrame.between_time and Series.between_time now only parse a fixed set of time strings. Parsing of date strings is no longer supported and raises a ValueError. (GH11818)

    In [107]: s = pd.Series(range(10), pd.date_range('2015-01-01', freq='H', periods=10))
    
    In [108]: s.between_time("7:00am", "9:00am")
    Out[108]: 
    2015-01-01 07:00:00    7
    2015-01-01 08:00:00    8
    2015-01-01 09:00:00    9
    Freq: H, dtype: int64
    

    This will now raise.

    In [2]: s.between_time('20150101 07:00:00','20150101 09:00:00')
    ValueError: Cannot convert arg ['20150101 07:00:00'] to a time.
    
  • .memory_usage() now includes values in the index, as does memory_usage in .info() (GH11597)

  • DataFrame.to_latex() now supports non-ascii encodings (eg utf-8) in Python 2 with the parameter encoding (GH7061)

  • pandas.merge() and DataFrame.merge() will show a specific error message when trying to merge with an object that is not of type DataFrame or a subclass (GH12081)

  • DataFrame.unstack and Series.unstack now take fill_value keyword to allow direct replacement of missing values when an unstack results in missing values in the resulting DataFrame. As an added benefit, specifying fill_value will preserve the data type of the original stacked data. (GH9746)

  • As part of the new API for window functions and resampling, aggregation functions have been clarified, raising more informative error messages on invalid aggregations. (GH9052). A full set of examples are presented in groupby.

  • Statistical functions for NDFrame objects (like sum(), mean(), min()) will now raise if non-numpy-compatible arguments are passed in for **kwargs (GH12301)

  • .to_latex and .to_html gain a decimal parameter like .to_csv; the default is '.' (GH12031)

  • More helpful error message when constructing a DataFrame with empty data but with indices (GH8020)

  • .describe() will now properly handle bool dtype as a categorical (GH6625)

  • More helpful error message with an invalid .transform with user defined input (GH10165)

  • Exponentially weighted functions now allow specifying alpha directly (GH10789) and raise ValueError if parameters violate 0 < alpha <= 1 (GH12492)

Deprecations

  • The functions pd.rolling_*, pd.expanding_*, and pd.ewm* are deprecated and replaced by the corresponding method call. Note that the new suggested syntax includes all of the arguments (even if default) (GH11603)

    In [1]: s = pd.Series(range(3))
    
    In [2]: pd.rolling_mean(s,window=2,min_periods=1)
            FutureWarning: pd.rolling_mean is deprecated for Series and
                 will be removed in a future version, replace with
                 Series.rolling(min_periods=1,window=2,center=False).mean()
    Out[2]:
            0    0.0
            1    0.5
            2    1.5
            dtype: float64
    
    In [3]: pd.rolling_cov(s, s, window=2)
            FutureWarning: pd.rolling_cov is deprecated for Series and
                 will be removed in a future version, replace with
                 Series.rolling(window=2).cov(other=<Series>)
    Out[3]:
            0    NaN
            1    0.5
            2    0.5
            dtype: float64
    
  • The the freq and how arguments to the .rolling, .expanding, and .ewm (new) functions are deprecated, and will be removed in a future version. You can simply resample the input prior to creating a window function. (GH11603).

    For example, instead of s.rolling(window=5,freq='D').max() to get the max value on a rolling 5 Day window, one could use s.resample('D').mean().rolling(window=5).max(), which first resamples the data to daily data, then provides a rolling 5 day window.

  • pd.tseries.frequencies.get_offset_name function is deprecated. Use offset’s .freqstr property as alternative (GH11192)

  • pandas.stats.fama_macbeth routines are deprecated and will be removed in a future version (GH6077)

  • pandas.stats.ols, pandas.stats.plm and pandas.stats.var routines are deprecated and will be removed in a future version (GH6077)

  • show a FutureWarning rather than a DeprecationWarning on using long-time deprecated syntax in HDFStore.select, where the where clause is not a string-like (GH12027)

  • The pandas.options.display.mpl_style configuration has been deprecated and will be removed in a future version of pandas. This functionality is better handled by matplotlib’s style sheets (GH11783).

Removal of deprecated float indexers

In GH4892 indexing with floating point numbers on a non-Float64Index was deprecated (in version 0.14.0). In 0.18.0, this deprecation warning is removed and these will now raise a TypeError. (GH12165, GH12333)

In [109]: s = pd.Series([1, 2, 3], index=[4, 5, 6])

In [110]: s
Out[110]: 
4    1
5    2
6    3
dtype: int64

In [111]: s2 = pd.Series([1, 2, 3], index=list('abc'))

In [112]: s2
Out[112]: 
a    1
b    2
c    3
dtype: int64

Previous Behavior:

# this is label indexing
In [2]: s[5.0]
FutureWarning: scalar indexers for index type Int64Index should be integers and not floating point
Out[2]: 2

# this is positional indexing
In [3]: s.iloc[1.0]
FutureWarning: scalar indexers for index type Int64Index should be integers and not floating point
Out[3]: 2

# this is label indexing
In [4]: s.loc[5.0]
FutureWarning: scalar indexers for index type Int64Index should be integers and not floating point
Out[4]: 2

# .ix would coerce 1.0 to the positional 1, and index
In [5]: s2.ix[1.0] = 10
FutureWarning: scalar indexers for index type Index should be integers and not floating point

In [6]: s2
Out[6]:
a     1
b    10
c     3
dtype: int64

New Behavior:

For iloc, getting & setting via a float scalar will always raise.

In [3]: s.iloc[2.0]
TypeError: cannot do label indexing on <class 'pandas.indexes.numeric.Int64Index'> with these indexers [2.0] of <type 'float'>

Other indexers will coerce to a like integer for both getting and setting. The FutureWarning has been dropped for .loc, .ix and [].

In [113]: s[5.0]
Out[113]: 2

In [114]: s.loc[5.0]
Out[114]: 2

and setting

In [115]: s_copy = s.copy()

In [116]: s_copy[5.0] = 10

In [117]: s_copy
Out[117]: 
4     1
5    10
6     3
dtype: int64

In [118]: s_copy = s.copy()

In [119]: s_copy.loc[5.0] = 10

In [120]: s_copy
Out[120]: 
4     1
5    10
6     3
dtype: int64

Positional setting with .ix and a float indexer will ADD this value to the index, rather than previously setting the value by position.

In [3]: s2.ix[1.0] = 10
In [4]: s2
Out[4]:
a       1
b       2
c       3
1.0    10
dtype: int64

Slicing will also coerce integer-like floats to integers for a non-Float64Index.

In [121]: s.loc[5.0:6]
Out[121]: 
5    2
6    3
dtype: int64

Note that for floats that are NOT coercible to ints, the label based bounds will be excluded

In [122]: s.loc[5.1:6]
Out[122]: 
6    3
dtype: int64

Float indexing on a Float64Index is unchanged.

In [123]: s = pd.Series([1, 2, 3], index=np.arange(3.))

In [124]: s[1.0]
Out[124]: 2

In [125]: s[1.0:2.5]
Out[125]: 
1.0    2
2.0    3
dtype: int64

Removal of prior version deprecations/changes

  • Removal of rolling_corr_pairwise in favor of .rolling().corr(pairwise=True) (GH4950)
  • Removal of expanding_corr_pairwise in favor of .expanding().corr(pairwise=True) (GH4950)
  • Removal of DataMatrix module. This was not imported into the pandas namespace in any event (GH12111)
  • Removal of cols keyword in favor of subset in DataFrame.duplicated() and DataFrame.drop_duplicates() (GH6680)
  • Removal of the read_frame and frame_query (both aliases for pd.read_sql) and write_frame (alias of to_sql) functions in the pd.io.sql namespace, deprecated since 0.14.0 (GH6292).
  • Removal of the order keyword from .factorize() (GH6930)

Performance Improvements

  • Improved performance of andrews_curves (GH11534)
  • Improved huge DatetimeIndex, PeriodIndex and TimedeltaIndex‘s ops performance including NaT (GH10277)
  • Improved performance of pandas.concat (GH11958)
  • Improved performance of StataReader (GH11591)
  • Improved performance in construction of Categoricals with Series of datetimes containing NaT (GH12077)
  • Improved performance of ISO 8601 date parsing for dates without separators (GH11899), leading zeros (GH11871) and with whitespace preceding the time zone (GH9714)

Bug Fixes

  • Bug in GroupBy.size when data-frame is empty. (GH11699)
  • Bug in Period.end_time when a multiple of time period is requested (GH11738)
  • Regression in .clip with tz-aware datetimes (GH11838)
  • Bug in date_range when the boundaries fell on the frequency (GH11804, GH12409)
  • Bug in consistency of passing nested dicts to .groupby(...).agg(...) (GH9052)
  • Accept unicode in Timedelta constructor (GH11995)
  • Bug in value label reading for StataReader when reading incrementally (GH12014)
  • Bug in vectorized DateOffset when n parameter is 0 (GH11370)
  • Compat for numpy 1.11 w.r.t. NaT comparison changes (GH12049)
  • Bug in read_csv when reading from a StringIO in threads (GH11790)
  • Bug in not treating NaT as a missing value in datetimelikes when factorizing & with Categoricals (GH12077)
  • Bug in getitem when the values of a Series were tz-aware (GH12089)
  • Bug in Series.str.get_dummies when one of the variables was ‘name’ (GH12180)
  • Bug in pd.concat while concatenating tz-aware NaT series. (GH11693, GH11755, GH12217)
  • Bug in pd.read_stata with version <= 108 files (GH12232)
  • Bug in Series.resample using a frequency of Nano when the index is a DatetimeIndex and contains non-zero nanosecond parts (GH12037)
  • Bug in resampling with .nunique and a sparse index (GH12352)
  • Removed some compiler warnings (GH12471)
  • Work around compat issues with boto in python 3.5 (GH11915)
  • Bug in NaT subtraction from Timestamp or DatetimeIndex with timezones (GH11718)
  • Bug in subtraction of Series of a single tz-aware Timestamp (GH12290)
  • Use compat iterators in PY2 to support .next() (GH12299)
  • Bug in Timedelta.round with negative values (GH11690)
  • Bug in .loc against CategoricalIndex may result in normal Index (GH11586)
  • Bug in DataFrame.info when duplicated column names exist (GH11761)
  • Bug in .copy of datetime tz-aware objects (GH11794)
  • Bug in Series.apply and Series.map where timedelta64 was not boxed (GH11349)
  • Bug in DataFrame.set_index() with tz-aware Series (GH12358)
  • Bug in subclasses of DataFrame where AttributeError did not propagate (GH11808)
  • Bug groupby on tz-aware data where selection not returning Timestamp (GH11616)
  • Bug in pd.read_clipboard and pd.to_clipboard functions not supporting Unicode; upgrade included pyperclip to v1.5.15 (GH9263)
  • Bug in DataFrame.query containing an assignment (GH8664)
  • Bug in from_msgpack where __contains__() fails for columns of the unpacked DataFrame, if the DataFrame has object columns. (GH11880)
  • Bug in .resample on categorical data with TimedeltaIndex (GH12169)
  • Bug in timezone info lost when broadcasting scalar datetime to DataFrame (GH11682)
  • Bug in Index creation from Timestamp with mixed tz coerces to UTC (GH11488)
  • Bug in to_numeric where it does not raise if input is more than one dimension (GH11776)
  • Bug in parsing timezone offset strings with non-zero minutes (GH11708)
  • Bug in df.plot using incorrect colors for bar plots under matplotlib 1.5+ (GH11614)
  • Bug in the groupby plot method when using keyword arguments (GH11805).
  • Bug in DataFrame.duplicated and drop_duplicates causing spurious matches when setting keep=False (GH11864)
  • Bug in .loc result with duplicated key may have Index with incorrect dtype (GH11497)
  • Bug in pd.rolling_median where memory allocation failed even with sufficient memory (GH11696)
  • Bug in DataFrame.style with spurious zeros (GH12134)
  • Bug in DataFrame.style with integer columns not starting at 0 (GH12125)
  • Bug in .style.bar may not rendered properly using specific browser (GH11678)
  • Bug in rich comparison of Timedelta with a numpy.array of Timedelta that caused an infinite recursion (GH11835)
  • Bug in DataFrame.round dropping column index name (GH11986)
  • Bug in df.replace while replacing value in mixed dtype Dataframe (GH11698)
  • Bug in Index prevents copying name of passed Index, when a new name is not provided (GH11193)
  • Bug in read_excel failing to read any non-empty sheets when empty sheets exist and sheetname=None (GH11711)
  • Bug in read_excel failing to raise NotImplemented error when keywords parse_dates and date_parser are provided (GH11544)
  • Bug in read_sql with pymysql connections failing to return chunked data (GH11522)
  • Bug in .to_csv ignoring formatting parameters decimal, na_rep, float_format for float indexes (GH11553)
  • Bug in Int64Index and Float64Index preventing the use of the modulo operator (GH9244)
  • Bug in MultiIndex.drop for not lexsorted multi-indexes (GH12078)
  • Bug in DataFrame when masking an empty DataFrame (GH11859)
  • Bug in .plot potentially modifying the colors input when the number of columns didn’t match the number of series provided (GH12039).
  • Bug in Series.plot failing when index has a CustomBusinessDay frequency (GH7222).
  • Bug in .to_sql for datetime.time values with sqlite fallback (GH8341)
  • Bug in read_excel failing to read data with one column when squeeze=True (GH12157)
  • Bug in read_excel failing to read one empty column (GH12292, GH9002)
  • Bug in .groupby where a KeyError was not raised for a wrong column if there was only one row in the dataframe (GH11741)
  • Bug in .read_csv with dtype specified on empty data producing an error (GH12048)
  • Bug in .read_csv where strings like '2E' are treated as valid floats (GH12237)
  • Bug in building pandas with debugging symbols (GH12123)
  • Removed millisecond property of DatetimeIndex. This would always raise a ValueError (GH12019).
  • Bug in Series constructor with read-only data (GH11502)
  • Removed pandas.util.testing.choice(). Should use np.random.choice(), instead. (GH12386)
  • Bug in .loc setitem indexer preventing the use of a TZ-aware DatetimeIndex (GH12050)
  • Bug in .style indexes and multi-indexes not appearing (GH11655)
  • Bug in to_msgpack and from_msgpack which did not correctly serialize or deserialize NaT (GH12307).
  • Bug in .skew and .kurt due to roundoff error for highly similar values (GH11974)
  • Bug in Timestamp constructor where microsecond resolution was lost if HHMMSS were not separated with ‘:’ (GH10041)
  • Bug in buffer_rd_bytes src->buffer could be freed more than once if reading failed, causing a segfault (GH12098)
  • Bug in crosstab where arguments with non-overlapping indexes would return a KeyError (GH10291)
  • Bug in DataFrame.apply in which reduction was not being prevented for cases in which dtype was not a numpy dtype (GH12244)
  • Bug when initializing categorical series with a scalar value. (GH12336)
  • Bug when specifying a UTC DatetimeIndex by setting utc=True in .to_datetime (GH11934)
  • Bug when increasing the buffer size of CSV reader in read_csv (GH12494)
  • Bug when setting columns of a DataFrame with duplicate column names (GH12344)

v0.17.1 (November 21, 2015)

Note

We are proud to announce that pandas has become a sponsored project of the (NUMFocus organization). This will help ensure the success of development of pandas as a world-class open-source project.

This is a minor bug-fix release from 0.17.0 and includes a large number of bug fixes along several new features, enhancements, and performance improvements. We recommend that all users upgrade to this version.

Highlights include:

  • Support for Conditional HTML Formatting, see here
  • Releasing the GIL on the csv reader & other ops, see here
  • Fixed regression in DataFrame.drop_duplicates from 0.16.2, causing incorrect results on integer values (GH11376)

New features

Conditional HTML Formatting

Warning

This is a new feature and is under active development. We’ll be adding features an possibly making breaking changes in future releases. Feedback is welcome.

We’ve added experimental support for conditional HTML formatting: the visual styling of a DataFrame based on the data. The styling is accomplished with HTML and CSS. Acesses the styler class with the pandas.DataFrame.style, attribute, an instance of Styler with your data attached.

Here’s a quick example:

In [1]: np.random.seed(123)

In [2]: df = DataFrame(np.random.randn(10, 5), columns=list('abcde'))

In [3]: html = df.style.background_gradient(cmap='viridis', low=.5)

We can render the HTML to get the following table.

a b c d e
0 -1.085631 0.997345 0.282978 -1.506295 -0.5786
1 1.651437 -2.426679 -0.428913 1.265936 -0.86674
2 -0.678886 -0.094709 1.49139 -0.638902 -0.443982
3 -0.434351 2.20593 2.186786 1.004054 0.386186
4 0.737369 1.490732 -0.935834 1.175829 -1.253881
5 -0.637752 0.907105 -1.428681 -0.140069 -0.861755
6 -0.255619 -2.798589 -1.771533 -0.699877 0.927462
7 -0.173636 0.002846 0.688223 -0.879536 0.283627
8 -0.805367 -1.727669 -0.3909 0.573806 0.338589
9 -0.01183 2.392365 0.412912 0.978736 2.238143

Styler interacts nicely with the Jupyter Notebook. See the documentation for more.

Enhancements

  • DatetimeIndex now supports conversion to strings with astype(str) (GH10442)

  • Support for compression (gzip/bz2) in pandas.DataFrame.to_csv() (GH7615)

  • pd.read_* functions can now also accept pathlib.Path, or py._path.local.LocalPath objects for the filepath_or_buffer argument. (GH11033) - The DataFrame and Series functions .to_csv(), .to_html() and .to_latex() can now handle paths beginning with tildes (e.g. ~/Documents/) (GH11438)

  • DataFrame now uses the fields of a namedtuple as columns, if columns are not supplied (GH11181)

  • DataFrame.itertuples() now returns namedtuple objects, when possible. (GH11269, GH11625)

  • Added axvlines_kwds to parallel coordinates plot (GH10709)

  • Option to .info() and .memory_usage() to provide for deep introspection of memory consumption. Note that this can be expensive to compute and therefore is an optional parameter. (GH11595)

    In [4]: df = DataFrame({'A' : ['foo']*1000})
    
    In [5]: df['B'] = df['A'].astype('category')
    
    # shows the '+' as we have object dtypes
    In [6]: df.info()
    <class 'pandas.core.frame.DataFrame'>
    RangeIndex: 1000 entries, 0 to 999
    Data columns (total 2 columns):
    A    1000 non-null object
    B    1000 non-null category
    dtypes: category(1), object(1)
    memory usage: 9.0+ KB
    
    # we have an accurate memory assessment (but can be expensive to compute this)
    In [7]: df.info(memory_usage='deep')
    <class 'pandas.core.frame.DataFrame'>
    RangeIndex: 1000 entries, 0 to 999
    Data columns (total 2 columns):
    A    1000 non-null object
    B    1000 non-null category
    dtypes: category(1), object(1)
    memory usage: 75.4 KB
    
  • Index now has a fillna method (GH10089)

    In [8]: pd.Index([1, np.nan, 3]).fillna(2)
    Out[8]: Float64Index([1.0, 2.0, 3.0], dtype='float64')
    
  • Series of type category now make .str.<...> and .dt.<...> accessor methods / properties available, if the categories are of that type. (GH10661)

    In [9]: s = pd.Series(list('aabb')).astype('category')
    
    In [10]: s
    Out[10]: 
    0    a
    1    a
    2    b
    3    b
    dtype: category
    Categories (2, object): [a, b]
    
    In [11]: s.str.contains("a")
    Out[11]: 
    0     True
    1     True
    2    False
    3    False
    dtype: bool
    
    In [12]: date = pd.Series(pd.date_range('1/1/2015', periods=5)).astype('category')
    
    In [13]: date
    Out[13]: 
    0   2015-01-01
    1   2015-01-02
    2   2015-01-03
    3   2015-01-04
    4   2015-01-05
    dtype: category
    Categories (5, datetime64[ns]): [2015-01-01, 2015-01-02, 2015-01-03, 2015-01-04, 2015-01-05]
    
    In [14]: date.dt.day
    Out[14]: 
    0    1
    1    2
    2    3
    3    4
    4    5
    dtype: int64
    
  • pivot_table now has a margins_name argument so you can use something other than the default of ‘All’ (GH3335)

  • Implement export of datetime64[ns, tz] dtypes with a fixed HDF5 store (GH11411)

  • Pretty printing sets (e.g. in DataFrame cells) now uses set literal syntax ({x, y}) instead of Legacy Python syntax (set([x, y])) (GH11215)

  • Improve the error message in pandas.io.gbq.to_gbq() when a streaming insert fails (GH11285) and when the DataFrame does not match the schema of the destination table (GH11359)

API changes

  • raise NotImplementedError in Index.shift for non-supported index types (GH8038)
  • min and max reductions on datetime64 and timedelta64 dtyped series now result in NaT and not nan (GH11245).
  • Indexing with a null key will raise a TypeError, instead of a ValueError (GH11356)
  • Series.ptp will now ignore missing values by default (GH11163)

Deprecations

  • The pandas.io.ga module which implements google-analytics support is deprecated and will be removed in a future version (GH11308)
  • Deprecate the engine keyword in .to_csv(), which will be removed in a future version (GH11274)

Performance Improvements

  • Checking monotonic-ness before sorting on an index (GH11080)
  • Series.dropna performance improvement when its dtype can’t contain NaN (GH11159)
  • Release the GIL on most datetime field operations (e.g. DatetimeIndex.year, Series.dt.year), normalization, and conversion to and from Period, DatetimeIndex.to_period and PeriodIndex.to_timestamp (GH11263)
  • Release the GIL on some rolling algos: rolling_median, rolling_mean, rolling_max, rolling_min, rolling_var, rolling_kurt, rolling_skew (GH11450)
  • Release the GIL when reading and parsing text files in read_csv, read_table (GH11272)
  • Improved performance of rolling_median (GH11450)
  • Improved performance of to_excel (GH11352)
  • Performance bug in repr of Categorical categories, which was rendering the strings before chopping them for display (GH11305)
  • Performance improvement in Categorical.remove_unused_categories, (GH11643).
  • Improved performance of Series constructor with no data and DatetimeIndex (GH11433)
  • Improved performance of shift, cumprod, and cumsum with groupby (GH4095)

Bug Fixes

  • SparseArray.__iter__() now does not cause PendingDeprecationWarning in Python 3.5 (GH11622)
  • Regression from 0.16.2 for output formatting of long floats/nan, restored in (GH11302)
  • Series.sort_index() now correctly handles the inplace option (GH11402)
  • Incorrectly distributed .c file in the build on PyPi when reading a csv of floats and passing na_values=<a scalar> would show an exception (GH11374)
  • Bug in .to_latex() output broken when the index has a name (GH10660)
  • Bug in HDFStore.append with strings whose encoded length exceded the max unencoded length (GH11234)
  • Bug in merging datetime64[ns, tz] dtypes (GH11405)
  • Bug in HDFStore.select when comparing with a numpy scalar in a where clause (GH11283)
  • Bug in using DataFrame.ix with a multi-index indexer (GH11372)
  • Bug in date_range with ambigous endpoints (GH11626)
  • Prevent adding new attributes to the accessors .str, .dt and .cat. Retrieving such a value was not possible, so error out on setting it. (GH10673)
  • Bug in tz-conversions with an ambiguous time and .dt accessors (GH11295)
  • Bug in output formatting when using an index of ambiguous times (GH11619)
  • Bug in comparisons of Series vs list-likes (GH11339)
  • Bug in DataFrame.replace with a datetime64[ns, tz] and a non-compat to_replace (GH11326, GH11153)
  • Bug in isnull where numpy.datetime64('NaT') in a numpy.array was not determined to be null(GH11206)
  • Bug in list-like indexing with a mixed-integer Index (GH11320)
  • Bug in pivot_table with margins=True when indexes are of Categorical dtype (GH10993)
  • Bug in DataFrame.plot cannot use hex strings colors (GH10299)
  • Regression in DataFrame.drop_duplicates from 0.16.2, causing incorrect results on integer values (GH11376)
  • Bug in pd.eval where unary ops in a list error (GH11235)
  • Bug in squeeze() with zero length arrays (GH11230, GH8999)
  • Bug in describe() dropping column names for hierarchical indexes (GH11517)
  • Bug in DataFrame.pct_change() not propagating axis keyword on .fillna method (GH11150)
  • Bug in .to_csv() when a mix of integer and string column names are passed as the columns parameter (GH11637)
  • Bug in indexing with a range, (GH11652)
  • Bug in inference of numpy scalars and preserving dtype when setting columns (GH11638)
  • Bug in to_sql using unicode column names giving UnicodeEncodeError with (GH11431).
  • Fix regression in setting of xticks in plot (GH11529).
  • Bug in holiday.dates where observance rules could not be applied to holiday and doc enhancement (GH11477, GH11533)
  • Fix plotting issues when having plain Axes instances instead of SubplotAxes (GH11520, GH11556).
  • Bug in DataFrame.to_latex() produces an extra rule when header=False (GH7124)
  • Bug in df.groupby(...).apply(func) when a func returns a Series containing a new datetimelike column (GH11324)
  • Bug in pandas.json when file to load is big (GH11344)
  • Bugs in to_excel with duplicate columns (GH11007, GH10982, GH10970)
  • Fixed a bug that prevented the construction of an empty series of dtype datetime64[ns, tz] (GH11245).
  • Bug in read_excel with multi-index containing integers (GH11317)
  • Bug in to_excel with openpyxl 2.2+ and merging (GH11408)
  • Bug in DataFrame.to_dict() produces a np.datetime64 object instead of Timestamp when only datetime is present in data (GH11327)
  • Bug in DataFrame.corr() raises exception when computes Kendall correlation for DataFrames with boolean and not boolean columns (GH11560)
  • Bug in the link-time error caused by C inline functions on FreeBSD 10+ (with clang) (GH10510)
  • Bug in DataFrame.to_csv in passing through arguments for formatting MultiIndexes, including date_format (GH7791)
  • Bug in DataFrame.join() with how='right' producing a TypeError (GH11519)
  • Bug in Series.quantile with empty list results has Index with object dtype (GH11588)
  • Bug in pd.merge results in empty Int64Index rather than Index(dtype=object) when the merge result is empty (GH11588)
  • Bug in Categorical.remove_unused_categories when having NaN values (GH11599)
  • Bug in DataFrame.to_sparse() loses column names for MultiIndexes (GH11600)
  • Bug in DataFrame.round() with non-unique column index producing a Fatal Python error (GH11611)
  • Bug in DataFrame.round() with decimals being a non-unique indexed Series producing extra columns (GH11618)

v0.17.0 (October 9, 2015)

This is a major release from 0.16.2 and includes a small 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.

Warning

pandas >= 0.17.0 will no longer support compatibility with Python version 3.2 (GH9118)

Warning

The pandas.io.data package is deprecated and will be replaced by the pandas-datareader package. This will allow the data modules to be independently updated to your pandas installation. The API for pandas-datareader v0.1.1 is exactly the same as in pandas v0.17.0 (GH8961, GH10861).

After installing pandas-datareader, you can easily change your imports:

from pandas.io import data, wb

becomes

from pandas_datareader import data, wb

Highlights include:

  • Release the Global Interpreter Lock (GIL) on some cython operations, see here
  • Plotting methods are now available as attributes of the .plot accessor, see here
  • The sorting API has been revamped to remove some long-time inconsistencies, see here
  • Support for a datetime64[ns] with timezones as a first-class dtype, see here
  • The default for to_datetime will now be to raise when presented with unparseable formats, previously this would return the original input. Also, date parse functions now return consistent results. See here
  • The default for dropna in HDFStore has changed to False, to store by default all rows even if they are all NaN, see here
  • Datetime accessor (dt) now supports Series.dt.strftime to generate formatted strings for datetime-likes, and Series.dt.total_seconds to generate each duration of the timedelta in seconds. See here
  • Period and PeriodIndex can handle multiplied freq like 3D, which corresponding to 3 days span. See here
  • Development installed versions of pandas will now have PEP440 compliant version strings (GH9518)
  • Development support for benchmarking with the Air Speed Velocity library (GH8361)
  • Support for reading SAS xport files, see here
  • Documentation comparing SAS to pandas, see here
  • Removal of the automatic TimeSeries broadcasting, deprecated since 0.8.0, see here
  • Display format with plain text can optionally align with Unicode East Asian Width, see here
  • Compatibility with Python 3.5 (GH11097)
  • Compatibility with matplotlib 1.5.0 (GH11111)

Check the API Changes and deprecations before updating.

New features

Datetime with TZ

We are adding an implementation that natively supports datetime with timezones. A Series or a DataFrame column previously could be assigned a datetime with timezones, and would work as an object dtype. This had performance issues with a large number rows. See the docs for more details. (GH8260, GH10763, GH11034).

The new implementation allows for having a single-timezone across all rows, with operations in a performant manner.

In [1]: df = DataFrame({'A' : date_range('20130101',periods=3),
   ...:                 'B' : date_range('20130101',periods=3,tz='US/Eastern'),
   ...:                 'C' : date_range('20130101',periods=3,tz='CET')})
   ...: 

In [2]: df
Out[2]: 
           A                         B                         C
0 2013-01-01 2013-01-01 00:00:00-05:00 2013-01-01 00:00:00+01:00
1 2013-01-02 2013-01-02 00:00:00-05:00 2013-01-02 00:00:00+01:00
2 2013-01-03 2013-01-03 00:00:00-05:00 2013-01-03 00:00:00+01:00

In [3]: df.dtypes
Out[3]: 
A                datetime64[ns]
B    datetime64[ns, US/Eastern]
C           datetime64[ns, CET]
dtype: object
In [4]: df.B
Out[4]: 
0   2013-01-01 00:00:00-05:00
1   2013-01-02 00:00:00-05:00
2   2013-01-03 00:00:00-05:00
Name: B, dtype: datetime64[ns, US/Eastern]

In [5]: df.B.dt.tz_localize(None)
Out[5]: 
0   2013-01-01
1   2013-01-02
2   2013-01-03
Name: B, dtype: datetime64[ns]

This uses a new-dtype representation as well, that is very similar in look-and-feel to its numpy cousin datetime64[ns]

In [6]: df['B'].dtype
Out[6]: datetime64[ns, US/Eastern]

In [7]: type(df['B'].dtype)
Out[7]: pandas.core.dtypes.dtypes.DatetimeTZDtype

Note

There is a slightly different string repr for the underlying DatetimeIndex as a result of the dtype changes, but functionally these are the same.

Previous Behavior:

In [1]: pd.date_range('20130101',periods=3,tz='US/Eastern')
Out[1]: DatetimeIndex(['2013-01-01 00:00:00-05:00', '2013-01-02 00:00:00-05:00',
                       '2013-01-03 00:00:00-05:00'],
                      dtype='datetime64[ns]', freq='D', tz='US/Eastern')

In [2]: pd.date_range('20130101',periods=3,tz='US/Eastern').dtype
Out[2]: dtype('<M8[ns]')

New Behavior:

In [8]: pd.date_range('20130101',periods=3,tz='US/Eastern')
Out[8]: 
DatetimeIndex(['2013-01-01 00:00:00-05:00', '2013-01-02 00:00:00-05:00',
               '2013-01-03 00:00:00-05:00'],
              dtype='datetime64[ns, US/Eastern]', freq='D')

In [9]: pd.date_range('20130101',periods=3,tz='US/Eastern').dtype
Out[9]: datetime64[ns, US/Eastern]

Releasing the GIL

We are releasing the global-interpreter-lock (GIL) on some cython operations. This will allow other threads to run simultaneously during computation, potentially allowing performance improvements from multi-threading. Notably groupby, nsmallest, value_counts and some indexing operations benefit from this. (GH8882)

For example the groupby expression in the following code will have the GIL released during the factorization step, e.g. df.groupby('key') as well as the .sum() operation.

N = 1000000
ngroups = 10
df = DataFrame({'key' : np.random.randint(0,ngroups,size=N),
                'data' : np.random.randn(N) })
df.groupby('key')['data'].sum()

Releasing of the GIL could benefit an application that uses threads for user interactions (e.g. QT), or performing multi-threaded computations. A nice example of a library that can handle these types of computation-in-parallel is the dask library.

Plot submethods

The Series and DataFrame .plot() method allows for customizing plot types by supplying the kind keyword arguments. Unfortunately, many of these kinds of plots use different required and optional keyword arguments, which makes it difficult to discover what any given plot kind uses out of the dozens of possible arguments.

To alleviate this issue, we have added a new, optional plotting interface, which exposes each kind of plot as a method of the .plot attribute. Instead of writing series.plot(kind=<kind>, ...), you can now also use series.plot.<kind>(...):

In [10]: df = pd.DataFrame(np.random.rand(10, 2), columns=['a', 'b'])

In [11]: df.plot.bar()
_images/whatsnew_plot_submethods.png

As a result of this change, these methods are now all discoverable via tab-completion:

In [12]: df.plot.<TAB>
df.plot.area     df.plot.barh     df.plot.density  df.plot.hist     df.plot.line     df.plot.scatter
df.plot.bar      df.plot.box      df.plot.hexbin   df.plot.kde      df.plot.pie

Each method signature only includes relevant arguments. Currently, these are limited to required arguments, but in the future these will include optional arguments, as well. For an overview, see the new Plotting API documentation.

Additional methods for dt accessor

strftime

We are now supporting a Series.dt.strftime method for datetime-likes to generate a formatted string (GH10110). Examples:

# DatetimeIndex
In [13]: s = pd.Series(pd.date_range('20130101', periods=4))

In [14]: s
Out[14]: 
0   2013-01-01
1   2013-01-02
2   2013-01-03
3   2013-01-04
dtype: datetime64[ns]

In [15]: s.dt.strftime('%Y/%m/%d')
Out[15]: 
0    2013/01/01
1    2013/01/02
2    2013/01/03
3    2013/01/04
dtype: object
# PeriodIndex
In [16]: s = pd.Series(pd.period_range('20130101', periods=4))

In [17]: s
Out[17]: 
0   2013-01-01
1   2013-01-02
2   2013-01-03
3   2013-01-04
dtype: object

In [18]: s.dt.strftime('%Y/%m/%d')
Out[18]: 
0    2013/01/01
1    2013/01/02
2    2013/01/03
3    2013/01/04
dtype: object

The string format is as the python standard library and details can be found here

total_seconds

pd.Series of type timedelta64 has new method .dt.total_seconds() returning the duration of the timedelta in seconds (GH10817)

# TimedeltaIndex
In [19]: s = pd.Series(pd.timedelta_range('1 minutes', periods=4))

In [20]: s
Out[20]: 
0   0 days 00:01:00
1   1 days 00:01:00
2   2 days 00:01:00
3   3 days 00:01:00
dtype: timedelta64[ns]

In [21]: s.dt.total_seconds()
Out[21]: 
0        60.0
1     86460.0
2    172860.0
3    259260.0
dtype: float64

Period Frequency Enhancement

Period, PeriodIndex and period_range can now accept multiplied freq. Also, Period.freq and PeriodIndex.freq are now stored as a DateOffset instance like DatetimeIndex, and not as