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.12.0 (July 24, 2013)

This is a major release from 0.11.0 and includes several new features and enhancements along with a large number of bug fixes.

Highlites include a consistent I/O API naming scheme, routines to read html, write multi-indexes to csv files, read & write STATA data files, read & write JSON format files, Python 3 support for HDFStore, filtering of groupby expressions via filter, and a revamped replace routine that accepts regular expressions.

API changes

  • The I/O API is now much more consistent with a set of top level reader functions accessed like pd.read_csv() that generally return a pandas object.

    • read_csv
    • read_excel
    • read_hdf
    • read_sql
    • read_json
    • read_html
    • read_stata
    • read_clipboard

    The corresponding writer functions are object methods that are accessed like df.to_csv()

    • to_csv
    • to_excel
    • to_hdf
    • to_sql
    • to_json
    • to_html
    • to_stata
    • to_clipboard
  • Fix modulo and integer division on Series,DataFrames to act similary to float dtypes to return np.nan or np.inf as appropriate (GH3590). This correct a numpy bug that treats integer and float dtypes differently.

    In [1]: p = DataFrame({ 'first' : [4,5,8], 'second' : [0,0,3] })
    
    In [2]: p % 0
    
       first  second
    0    NaN     NaN
    1    NaN     NaN
    2    NaN     NaN
    
    In [3]: p % p
    
       first  second
    0      0     NaN
    1      0     NaN
    2      0       0
    
    In [4]: p / p
    
       first    second
    0      1       inf
    1      1       inf
    2      1  1.000000
    
    In [5]: p / 0
    
       first  second
    0    inf     inf
    1    inf     inf
    2    inf     inf
    
  • Add squeeze keyword to groupby to allow reduction from DataFrame -> Series if groups are unique. This is a Regression from 0.10.1. We are reverting back to the prior behavior. This means groupby will return the same shaped objects whether the groups are unique or not. Revert this issue (GH2893) with (GH3596).

    In [6]: df2 = DataFrame([{"val1": 1, "val2" : 20}, {"val1":1, "val2": 19},
       ...:                  {"val1":1, "val2": 27}, {"val1":1, "val2": 12}])
       ...: 
    
    In [7]: def func(dataf):
       ...:     return dataf["val2"]  - dataf["val2"].mean()
       ...: 
    
    # squeezing the result frame to a series (because we have unique groups)
    In [8]: df2.groupby("val1", squeeze=True).apply(func)
    
    0    0.5
    1   -0.5
    2    7.5
    3   -7.5
    Name: 1, dtype: float64
    
    # no squeezing (the default, and behavior in 0.10.1)
    In [9]: df2.groupby("val1").apply(func)
    
            0    1    2    3
    val1                    
    1     0.5 -0.5  7.5 -7.5
    
  • Raise on iloc when boolean indexing with a label based indexer mask e.g. a boolean Series, even with integer labels, will raise. Since iloc is purely positional based, the labels on the Series are not alignable (GH3631)

    This case is rarely used, and there are plently of alternatives. This preserves the iloc API to be purely positional based.

    In [10]: df = DataFrame(range(5), list('ABCDE'), columns=['a'])
    
    In [11]: mask = (df.a%2 == 0)
    
    In [12]: mask
    
    A     True
    B    False
    C     True
    D    False
    E     True
    Name: a, dtype: bool
    
    # this is what you should use
    In [13]: df.loc[mask]
    
       a
    A  0
    C  2
    E  4
    
    # this will work as well
    In [14]: df.iloc[mask.values]
    
       a
    A  0
    C  2
    E  4
    

    df.iloc[mask] will raise a ValueError

  • The raise_on_error argument to plotting functions is removed. Instead, plotting functions raise a TypeError when the dtype of the object is object to remind you to avoid object arrays whenever possible and thus you should cast to an appropriate numeric dtype if you need to plot something.

  • Add colormap keyword to DataFrame plotting methods. Accepts either a matplotlib colormap object (ie, matplotlib.cm.jet) or a string name of such an object (ie, ‘jet’). The colormap is sampled to select the color for each column. Please see Colormaps for more information. (GH3860)

  • DataFrame.interpolate() is now deprecated. Please use DataFrame.fillna() and DataFrame.replace() instead. (GH3582, GH3675, GH3676)

  • the method and axis arguments of DataFrame.replace() are deprecated

  • DataFrame.replace ‘s infer_types parameter is removed and now performs conversion by default. (GH3907)

  • Add the keyword allow_duplicates to DataFrame.insert to allow a duplicate column to be inserted if True, default is False (same as prior to 0.12) (GH3679)

  • Implement __nonzero__ for NDFrame objects (GH3691, GH3696)

  • IO api

    • added top-level function read_excel to replace the following, The original API is deprecated and will be removed in a future version

      from pandas.io.parsers import ExcelFile
      xls = ExcelFile('path_to_file.xls')
      xls.parse('Sheet1', index_col=None, na_values=['NA'])
      

      With

      import pandas as pd
      pd.read_excel('path_to_file.xls', 'Sheet1', index_col=None, na_values=['NA'])
      
    • added top-level function read_sql that is equivalent to the following

      from pandas.io.sql import read_frame
      read_frame(....)
      
  • DataFrame.to_html and DataFrame.to_latex now accept a path for their first argument (GH3702)

  • Do not allow astypes on datetime64[ns] except to object, and timedelta64[ns] to object/int (GH3425)

  • The behavior of datetime64 dtypes has changed with respect to certain so-called reduction operations (GH3726). The following operations now raise a TypeError when perfomed on a Series and return an empty Series when performed on a DataFrame similar to performing these operations on, for example, a DataFrame of slice objects:

    • sum, prod, mean, std, var, skew, kurt, corr, and cov
  • read_html now defaults to None when reading, and falls back on bs4 + html5lib when lxml fails to parse. a list of parsers to try until success is also valid

  • The internal pandas class hierarchy has changed (slightly). The previous PandasObject now is called PandasContainer and a new PandasObject has become the baseclass for PandasContainer as well as Index, Categorical, GroupBy, SparseList, and SparseArray (+ their base classes). Currently, PandasObject provides string methods (from StringMixin). (GH4090, GH4092)

  • New StringMixin that, given a __unicode__ method, gets python 2 and python 3 compatible string methods (__str__, __bytes__, and __repr__). Plus string safety throughout. Now employed in many places throughout the pandas library. (GH4090, GH4092)

I/O Enhancements

  • pd.read_html() can now parse HTML strings, files or urls and return DataFrames, courtesy of @cpcloud. (GH3477, GH3605, GH3606, GH3616). It works with a single parser backend: BeautifulSoup4 + html5lib See the docs

    You can use pd.read_html() to read the output from DataFrame.to_html() like so

    In [15]: df = DataFrame({'a': range(3), 'b': list('abc')})
    
    In [16]: print df
       a  b
    0  0  a
    1  1  b
    2  2  c
    
    In [17]: html = df.to_html()
    
    In [18]: alist = pd.read_html(html, infer_types=True, index_col=0)
    
    In [19]: print df == alist[0]
          a     b
    0  True  True
    1  True  True
    2  True  True
    

    Note that alist here is a Python list so pd.read_html() and DataFrame.to_html() are not inverses.

    • pd.read_html() no longer performs hard conversion of date strings (GH3656).

    Warning

    You may have to install an older version of BeautifulSoup4, See the installation docs

  • Added module for reading and writing Stata files: pandas.io.stata (GH1512) accessable via read_stata top-level function for reading, and to_stata DataFrame method for writing, See the docs

  • Added module for reading and writing json format files: pandas.io.json accessable via read_json top-level function for reading, and to_json DataFrame method for writing, See the docs various issues (GH1226, GH3804, GH3876, GH3867, GH1305)

  • MultiIndex column support for reading and writing csv format files

    • The header option in read_csv now accepts a list of the rows from which to read the index.

    • The option, tupleize_cols can now be specified in both to_csv and read_csv, to provide compatiblity for the pre 0.12 behavior of writing and reading MultIndex columns via a list of tuples. The default in 0.12 is to write lists of tuples and not interpret list of tuples as a MultiIndex column.

      Note: The default behavior in 0.12 remains unchanged from prior versions, but starting with 0.13, the default to write and read MultiIndex columns will be in the new format. (GH3571, GH1651, GH3141)

    • If an index_col is not specified (e.g. you don’t have an index, or wrote it with df.to_csv(..., index=False), then any names on the columns index will be lost.

      In [20]: from pandas.util.testing import makeCustomDataframe as mkdf
      
      In [21]: df = mkdf(5,3,r_idx_nlevels=2,c_idx_nlevels=4)
      
      In [22]: df.to_csv('mi.csv',tupleize_cols=False)
      
      In [23]: print open('mi.csv').read()
      C0,,C_l0_g0,C_l0_g1,C_l0_g2
      C1,,C_l1_g0,C_l1_g1,C_l1_g2
      C2,,C_l2_g0,C_l2_g1,C_l2_g2
      C3,,C_l3_g0,C_l3_g1,C_l3_g2
      R0,R1,,,
      R_l0_g0,R_l1_g0,R0C0,R0C1,R0C2
      R_l0_g1,R_l1_g1,R1C0,R1C1,R1C2
      R_l0_g2,R_l1_g2,R2C0,R2C1,R2C2
      R_l0_g3,R_l1_g3,R3C0,R3C1,R3C2
      R_l0_g4,R_l1_g4,R4C0,R4C1,R4C2
      
      In [24]: pd.read_csv('mi.csv',header=[0,1,2,3],index_col=[0,1],tupleize_cols=False)
      
      C0              C_l0_g0 C_l0_g1 C_l0_g2
      C1              C_l1_g0 C_l1_g1 C_l1_g2
      C2              C_l2_g0 C_l2_g1 C_l2_g2
      C3              C_l3_g0 C_l3_g1 C_l3_g2
      R0      R1                             
      R_l0_g0 R_l1_g0    R0C0    R0C1    R0C2
      R_l0_g1 R_l1_g1    R1C0    R1C1    R1C2
      R_l0_g2 R_l1_g2    R2C0    R2C1    R2C2
      R_l0_g3 R_l1_g3    R3C0    R3C1    R3C2
      R_l0_g4 R_l1_g4    R4C0    R4C1    R4C2
      
  • Support for HDFStore (via PyTables 3.0.0) on Python3

  • Iterator support via read_hdf that automatically opens and closes the store when iteration is finished. This is only for tables

    In [25]: path = 'store_iterator.h5'
    
    In [26]: DataFrame(randn(10,2)).to_hdf(path,'df',table=True)
    
    In [27]: for df in read_hdf(path,'df', chunksize=3):
       ....:    print df
       ....: 
              0         1
    0  0.713216 -0.778461
    1 -0.661062  0.862877
    2  0.344342  0.149565
              0         1
    3 -0.626968 -0.875772
    4 -0.930687 -0.218983
    5  0.949965 -0.442354
              0         1
    6 -0.402985  1.111358
    7 -0.241527 -0.670477
    8  0.049355  0.632633
              0         1
    9 -1.502767 -1.225492
    
  • read_csv will now throw a more informative error message when a file contains no columns, e.g., all newline characters

Other Enhancements

  • DataFrame.replace() now allows regular expressions on contained Series with object dtype. See the examples section in the regular docs Replacing via String Expression

    For example you can do

    In [28]: df = DataFrame({'a': list('ab..'), 'b': [1, 2, 3, 4]})
    
    In [29]: df.replace(regex=r'\s*\.\s*', value=np.nan)
    
         a  b
    0    a  1
    1    b  2
    2  NaN  3
    3  NaN  4
    

    to replace all occurrences of the string '.' with zero or more instances of surrounding whitespace with NaN.

    Regular string replacement still works as expected. For example, you can do

    In [30]: df.replace('.', np.nan)
    
         a  b
    0    a  1
    1    b  2
    2  NaN  3
    3  NaN  4
    

    to replace all occurrences of the string '.' with NaN.

  • pd.melt() now accepts the optional parameters var_name and value_name to specify custom column names of the returned DataFrame.

  • pd.set_option() now allows N option, value pairs (GH3667).

    Let’s say that we had an option 'a.b' and another option 'b.c'. We can set them at the same time:

    In [31]: pd.get_option('a.b')
    2
    
    In [32]: pd.get_option('b.c')
    3
    
    In [33]: pd.set_option('a.b', 1, 'b.c', 4)
    
    In [34]: pd.get_option('a.b')
    1
    
    In [35]: pd.get_option('b.c')
    4
    
  • The filter method for group objects returns a subset of the original object. Suppose we want to take only elements that belong to groups with a group sum greater than 2.

    In [36]: sf = Series([1, 1, 2, 3, 3, 3])
    
    In [37]: sf.groupby(sf).filter(lambda x: x.sum() > 2)
    
    3    3
    4    3
    5    3
    dtype: int64
    

    The argument of filter must a function that, applied to the group as a whole, returns True or False.

    Another useful operation is filtering out elements that belong to groups with only a couple members.

    In [38]: dff = DataFrame({'A': np.arange(8), 'B': list('aabbbbcc')})
    
    In [39]: dff.groupby('B').filter(lambda x: len(x) > 2)
    
       A  B
    2  2  b
    3  3  b
    4  4  b
    5  5  b
    

    Alternatively, instead of dropping the offending groups, we can return a like-indexed objects where the groups that do not pass the filter are filled with NaNs.

    In [40]: dff.groupby('B').filter(lambda x: len(x) > 2, dropna=False)
    
        A    B
    0 NaN  NaN
    1 NaN  NaN
    2   2    b
    3   3    b
    4   4    b
    5   5    b
    6 NaN  NaN
    7 NaN  NaN
    
  • Series and DataFrame hist methods now take a figsize argument (GH3834)

  • DatetimeIndexes no longer try to convert mixed-integer indexes during join operations (GH3877)

  • Timestamp.min and Timestamp.max now represent valid Timestamp instances instead of the default datetime.min and datetime.max (respectively), thanks @SleepingPills

  • read_html now raises when no tables are found and BeautifulSoup==4.2.0 is detected (GH4214)

Experimental Features

  • Added experimental CustomBusinessDay class to support DateOffsets with custom holiday calendars and custom weekmasks. (GH2301)

    Note

    This uses the numpy.busdaycalendar API introduced in Numpy 1.7 and therefore requires Numpy 1.7.0 or newer.

    In [41]: from pandas.tseries.offsets import CustomBusinessDay
    
    # As an interesting example, let's look at Egypt where
    # a Friday-Saturday weekend is observed.
    In [42]: weekmask_egypt = 'Sun Mon Tue Wed Thu'
    
    # They also observe International Workers' Day so let's
    # add that for a couple of years
    In [43]: holidays = ['2012-05-01', datetime(2013, 5, 1), np.datetime64('2014-05-01')]
    
    In [44]: bday_egypt = CustomBusinessDay(holidays=holidays, weekmask=weekmask_egypt)
    
    In [45]: dt = datetime(2013, 4, 30)
    
    In [46]: print dt + 2 * bday_egypt
    2013-05-05 00:00:00
    
    In [47]: dts = date_range(dt, periods=5, freq=bday_egypt).to_series()
    
    In [48]: print Series(dts.weekday, dts).map(Series('Mon Tue Wed Thu Fri Sat Sun'.split()))
    2013-04-30    Tue
    2013-05-02    Thu
    2013-05-05    Sun
    2013-05-06    Mon
    2013-05-07    Tue
    dtype: object
    

Bug Fixes

  • Plotting functions now raise a TypeError before trying to plot anything if the associated objects have have a dtype of object (GH1818, GH3572, GH3911, GH3912), but they will try to convert object arrays to numeric arrays if possible so that you can still plot, for example, an object array with floats. This happens before any drawing takes place which elimnates any spurious plots from showing up.

  • fillna methods now raise a TypeError if the value parameter is a list or tuple.

  • Series.str now supports iteration (GH3638). You can iterate over the individual elements of each string in the Series. Each iteration yields yields a Series with either a single character at each index of the original Series or NaN. For example,

    In [49]: strs = 'go', 'bow', 'joe', 'slow'
    
    In [50]: ds = Series(strs)
    
    In [51]: for s in ds.str:
       ....:     print s
       ....: 
    0    g
    1    b
    2    j
    3    s
    dtype: object
    0    o
    1    o
    2    o
    3    l
    dtype: object
    0    NaN
    1      w
    2      e
    3      o
    dtype: object
    0    NaN
    1    NaN
    2    NaN
    3      w
    dtype: object
    
    In [52]: s
    
    0    NaN
    1    NaN
    2    NaN
    3      w
    dtype: object
    
    In [53]: s.dropna().values.item() == 'w'
    True
    

    The last element yielded by the iterator will be a Series containing the last element of the longest string in the Series with all other elements being NaN. Here since 'slow' is the longest string and there are no other strings with the same length 'w' is the only non-null string in the yielded Series.

  • HDFStore

    • will retain index attributes (freq,tz,name) on recreation (GH3499)
    • will warn with a AttributeConflictWarning if you are attempting to append an index with a different frequency than the existing, or attempting to append an index with a different name than the existing
    • support datelike columns with a timezone as data_columns (GH2852)
  • Non-unique index support clarified (GH3468).

    • Fix assigning a new index to a duplicate index in a DataFrame would fail (GH3468)
    • Fix construction of a DataFrame with a duplicate index
    • ref_locs support to allow duplicative indices across dtypes, allows iget support to always find the index (even across dtypes) (GH2194)
    • applymap on a DataFrame with a non-unique index now works (removed warning) (GH2786), and fix (GH3230)
    • Fix to_csv to handle non-unique columns (GH3495)
    • Duplicate indexes with getitem will return items in the correct order (GH3455, GH3457) and handle missing elements like unique indices (GH3561)
    • Duplicate indexes with and empty DataFrame.from_records will return a correct frame (GH3562)
    • Concat to produce a non-unique columns when duplicates are across dtypes is fixed (GH3602)
    • Allow insert/delete to non-unique columns (GH3679)
    • Non-unique indexing with a slice via loc and friends fixed (GH3659)
    • Allow insert/delete to non-unique columns (GH3679)
    • Extend reindex to correctly deal with non-unique indices (GH3679)
    • DataFrame.itertuples() now works with frames with duplicate column names (GH3873)
    • Bug in non-unique indexing via iloc (GH4017); added takeable argument to reindex for location-based taking
    • Allow non-unique indexing in series via .ix/.loc and __getitem__ (GH4246)
    • Fixed non-unique indexing memory allocation issue with .ix/.loc (GH4280)
  • DataFrame.from_records did not accept empty recarrays (GH3682)

  • read_html now correctly skips tests (GH3741)

  • Fixed a bug where DataFrame.replace with a compiled regular expression in the to_replace argument wasn’t working (GH3907)

  • Improved network test decorator to catch IOError (and therefore URLError as well). Added with_connectivity_check decorator to allow explicitly checking a website as a proxy for seeing if there is network connectivity. Plus, new optional_args decorator factory for decorators. (GH3910, GH3914)

  • Fixed testing issue where too many sockets where open thus leading to a connection reset issue (GH3982, GH3985, GH4028, GH4054)

  • Fixed failing tests in test_yahoo, test_google where symbols were not retrieved but were being accessed (GH3982, GH3985, GH4028, GH4054)

  • Series.hist will now take the figure from the current environment if one is not passed

  • Fixed bug where a 1xN DataFrame would barf on a 1xN mask (GH4071)

  • Fixed running of tox under python3 where the pickle import was getting rewritten in an incompatible way (GH4062, GH4063)

  • Fixed bug where sharex and sharey were not being passed to grouped_hist (GH4089)

  • Fixed bug in DataFrame.replace where a nested dict wasn’t being iterated over when regex=False (GH4115)

  • Fixed bug in the parsing of microseconds when using the format argument in to_datetime (GH4152)

  • Fixed bug in PandasAutoDateLocator where invert_xaxis triggered incorrectly MilliSecondLocator (GH3990)

  • Fixed bug in plotting that wasn’t raising on invalid colormap for matplotlib 1.1.1 (GH4215)

  • Fixed the legend displaying in DataFrame.plot(kind='kde') (GH4216)

  • Fixed bug where Index slices weren’t carrying the name attribute (GH4226)

  • Fixed bug in initializing DatetimeIndex with an array of strings in a certain time zone (GH4229)

  • Fixed bug where html5lib wasn’t being properly skipped (GH4265)

  • Fixed bug where get_data_famafrench wasn’t using the correct file edges (GH4281)

See the full release notes or issue tracker on GitHub for a complete list.

v0.11.0 (April 22, 2013)

This is a major release from 0.10.1 and includes many new features and enhancements along with a large number of bug fixes. The methods of Selecting Data have had quite a number of additions, and Dtype support is now full-fledged. There are also a number of important API changes that long-time pandas users should pay close attention to.

There is a new section in the documentation, 10 Minutes to Pandas, primarily geared to new users.

There is a new section in the documentation, Cookbook, a collection of useful recipes in pandas (and that we want contributions!).

There are several libraries that are now Recommended Dependencies

Selection Choices

Starting in 0.11.0, object selection has had a number of user-requested additions in order to support more explicit location based indexing. Pandas now supports three types of multi-axis indexing.

  • .loc is strictly label based, will raise KeyError when the items are not found, allowed inputs are:

    • A single label, e.g. 5 or 'a', (note that 5 is interpreted as a label of the index. This use is not an integer position along the index)
    • A list or array of labels ['a', 'b', 'c']
    • A slice object with labels 'a':'f', (note that contrary to usual python slices, both the start and the stop are included!)
    • A boolean array

    See more at Selection by Label

  • .iloc is strictly integer position based (from 0 to length-1 of the axis), will raise IndexError when the requested indicies are out of bounds. Allowed inputs are:

    • An integer e.g. 5
    • A list or array of integers [4, 3, 0]
    • A slice object with ints 1:7
    • A boolean array

    See more at Selection by Position

  • .ix supports mixed integer and label based access. It is primarily label based, but will fallback to integer positional access. .ix is the most general and will support any of the inputs to .loc and .iloc, as well as support for floating point label schemes. .ix is especially useful when dealing with mixed positional and label based hierarchial indexes.

    As using integer slices with .ix have different behavior depending on whether the slice is interpreted as position based or label based, it’s usually better to be explicit and use .iloc or .loc.

    See more at Advanced Indexing, Advanced Hierarchical and Fallback Indexing

Selection Deprecations

Starting in version 0.11.0, these methods may be deprecated in future versions.

  • irow
  • icol
  • iget_value

See the section Selection by Position for substitutes.

Dtypes

Numeric dtypes will propagate and can coexist in DataFrames. If a dtype is passed (either directly via the dtype keyword, a passed ndarray, or a passed Series, then it will be preserved in DataFrame operations. Furthermore, different numeric dtypes will NOT be combined. The following example will give you a taste.

In [1]: df1 = DataFrame(randn(8, 1), columns = ['A'], dtype = 'float32')

In [2]: df1

          A
0 -0.700262
1 -0.237922
2  0.803216
3  0.323302
4 -0.419578
5 -0.159861
6  0.286230
7 -0.311358

In [3]: df1.dtypes

A    float32
dtype: object

In [4]: df2 = DataFrame(dict( A = Series(randn(8),dtype='float16'),
   ...:                       B = Series(randn(8)),
   ...:                       C = Series(randn(8),dtype='uint8') ))
   ...: 

In [5]: df2

          A         B    C
0  1.144531  1.785587    1
1 -0.726562  1.135875    0
2 -0.178345  0.699592    1
3  0.386230  0.245373    0
4  0.309326 -0.301134  255
5 -0.328857  0.461004    0
6  0.056335 -0.666262    0
7  1.495117  0.276584    0

In [6]: df2.dtypes

A    float16
B    float64
C      uint8
dtype: object

# here you get some upcasting
In [7]: df3 = df1.reindex_like(df2).fillna(value=0.0) + df2

In [8]: df3

          A         B    C
0  0.444270  1.785587    1
1 -0.964485  1.135875    0
2  0.624871  0.699592    1
3  0.709532  0.245373    0
4 -0.110252 -0.301134  255
5 -0.488719  0.461004    0
6  0.342566 -0.666262    0
7  1.183759  0.276584    0

In [9]: df3.dtypes

A    float32
B    float64
C    float64
dtype: object

Dtype Conversion

This is lower-common-denomicator upcasting, meaning you get the dtype which can accomodate all of the types

In [10]: df3.values.dtype
dtype('float64')

Conversion

In [11]: df3.astype('float32').dtypes

A    float32
B    float32
C    float32
dtype: object

Mixed Conversion

In [12]: df3['D'] = '1.'

In [13]: df3['E'] = '1'

In [14]: df3.convert_objects(convert_numeric=True).dtypes

A    float32
B    float64
C    float64
D    float64
E      int64
dtype: object

# same, but specific dtype conversion
In [15]: df3['D'] = df3['D'].astype('float16')

In [16]: df3['E'] = df3['E'].astype('int32')

In [17]: df3.dtypes

A    float32
B    float64
C    float64
D    float16
E      int32
dtype: object

Forcing Date coercion (and setting NaT when not datelike)

In [18]: s = Series([datetime(2001,1,1,0,0), 'foo', 1.0, 1,
   ....:             Timestamp('20010104'), '20010105'],dtype='O')
   ....: 

In [19]: s.convert_objects(convert_dates='coerce')

0   2001-01-01 00:00:00
1                   NaT
2                   NaT
3                   NaT
4   2001-01-04 00:00:00
5   2001-01-05 00:00:00
dtype: datetime64[ns]

Dtype Gotchas

Platform Gotchas

Starting in 0.11.0, construction of DataFrame/Series will use default dtypes of int64 and float64, regardless of platform. This is not an apparent change from earlier versions of pandas. If you specify dtypes, they WILL be respected, however (GH2837)

The following will all result in int64 dtypes

In [20]: DataFrame([1,2],columns=['a']).dtypes

a    int64
dtype: object

In [21]: DataFrame({'a' : [1,2] }).dtypes

a    int64
dtype: object

In [22]: DataFrame({'a' : 1 }, index=range(2)).dtypes

a    int64
dtype: object

Keep in mind that DataFrame(np.array([1,2])) WILL result in int32 on 32-bit platforms!

Upcasting Gotchas

Performing indexing operations on integer type data can easily upcast the data. The dtype of the input data will be preserved in cases where nans are not introduced.

In [23]: dfi = df3.astype('int32')

In [24]: dfi['D'] = dfi['D'].astype('int64')

In [25]: dfi

   A  B    C  D  E
0  0  1    1  1  1
1  0  1    0  1  1
2  0  0    1  1  1
3  0  0    0  1  1
4  0  0  255  1  1
5  0  0    0  1  1
6  0  0    0  1  1
7  1  0    0  1  1

In [26]: dfi.dtypes

A    int32
B    int32
C    int32
D    int64
E    int32
dtype: object

In [27]: casted = dfi[dfi>0]

In [28]: casted

    A   B    C  D  E
0 NaN   1    1  1  1
1 NaN   1  NaN  1  1
2 NaN NaN    1  1  1
3 NaN NaN  NaN  1  1
4 NaN NaN  255  1  1
5 NaN NaN  NaN  1  1
6 NaN NaN  NaN  1  1
7   1 NaN  NaN  1  1

In [29]: casted.dtypes

A    float64
B    float64
C    float64
D      int64
E      int32
dtype: object

While float dtypes are unchanged.

In [30]: df4 = df3.copy()

In [31]: df4['A'] = df4['A'].astype('float32')

In [32]: df4.dtypes

A    float32
B    float64
C    float64
D    float16
E      int32
dtype: object

In [33]: casted = df4[df4>0]

In [34]: casted

          A         B    C  D  E
0  0.444270  1.785587    1  1  1
1       NaN  1.135875  NaN  1  1
2  0.624871  0.699592    1  1  1
3  0.709532  0.245373  NaN  1  1
4       NaN       NaN  255  1  1
5       NaN  0.461004  NaN  1  1
6  0.342566       NaN  NaN  1  1
7  1.183759  0.276584  NaN  1  1

In [35]: casted.dtypes

A    float32
B    float64
C    float64
D    float16
E      int32
dtype: object

Datetimes Conversion

Datetime64[ns] columns in a DataFrame (or a Series) allow the use of np.nan to indicate a nan value, in addition to the traditional NaT, or not-a-time. This allows convenient nan setting in a generic way. Furthermore datetime64[ns] columns are created by default, when passed datetimelike objects (this change was introduced in 0.10.1) (GH2809, GH2810)

In [36]: df = DataFrame(randn(6,2),date_range('20010102',periods=6),columns=['A','B'])

In [37]: df['timestamp'] = Timestamp('20010103')

In [38]: df

                   A         B           timestamp
2001-01-02  1.063611  1.082236 2001-01-03 00:00:00
2001-01-03 -0.108453  0.435635 2001-01-03 00:00:00
2001-01-04 -0.517893 -0.859124 2001-01-03 00:00:00
2001-01-05  0.090706  0.125211 2001-01-03 00:00:00
2001-01-06  0.638435  1.105163 2001-01-03 00:00:00
2001-01-07 -0.958029 -0.444508 2001-01-03 00:00:00

# datetime64[ns] out of the box
In [39]: df.get_dtype_counts()

datetime64[ns]    1
float64           2
dtype: int64

# use the traditional nan, which is mapped to NaT internally
In [40]: df.ix[2:4,['A','timestamp']] = np.nan

In [41]: df

                   A         B           timestamp
2001-01-02  1.063611  1.082236 2001-01-03 00:00:00
2001-01-03 -0.108453  0.435635 2001-01-03 00:00:00
2001-01-04       NaN -0.859124                 NaT
2001-01-05       NaN  0.125211                 NaT
2001-01-06  0.638435  1.105163 2001-01-03 00:00:00
2001-01-07 -0.958029 -0.444508 2001-01-03 00:00:00

Astype conversion on datetime64[ns] to object, implicity converts NaT to np.nan

In [42]: import datetime

In [43]: s = Series([datetime.datetime(2001, 1, 2, 0, 0) for i in range(3)])

In [44]: s.dtype
dtype('<M8[ns]')

In [45]: s[1] = np.nan

In [46]: s

0   2001-01-02 00:00:00
1                   NaT
2   2001-01-02 00:00:00
dtype: datetime64[ns]

In [47]: s.dtype
dtype('<M8[ns]')

In [48]: s = s.astype('O')

In [49]: s

0    2001-01-02 00:00:00
1                    NaN
2    2001-01-02 00:00:00
dtype: object

In [50]: s.dtype
dtype('O')

API changes

  • Added to_series() method to indicies, to facilitate the creation of indexers (GH3275)
  • HDFStore
    • added the method select_column to select a single column from a table as a Series.
    • deprecated the unique method, can be replicated by select_column(key,column).unique()
    • min_itemsize parameter to append will now automatically create data_columns for passed keys

Enhancements

  • Improved performance of df.to_csv() by up to 10x in some cases. (GH3059)

  • Numexpr is now a Recommended Dependencies, to accelerate certain types of numerical and boolean operations

  • Bottleneck is now a Recommended Dependencies, to accelerate certain types of nan operations

  • HDFStore

    • support read_hdf/to_hdf API similar to read_csv/to_csv

      In [51]: df = DataFrame(dict(A=range(5), B=range(5)))
      
      In [52]: df.to_hdf('store.h5','table',append=True)
      
      In [53]: read_hdf('store.h5', 'table', where = ['index>2'])
      
         A  B
      3  3  3
      4  4  4
      
    • provide dotted attribute access to get from stores, e.g. store.df == store['df']

    • new keywords iterator=boolean, and chunksize=number_in_a_chunk are provided to support iteration on select and select_as_multiple (GH3076)

  • You can now select timestamps from an unordered timeseries similarly to an ordered timeseries (GH2437)

  • You can now select with a string from a DataFrame with a datelike index, in a similar way to a Series (GH3070)

    In [54]: idx = date_range("2001-10-1", periods=5, freq='M')
    
    In [55]: ts = Series(np.random.rand(len(idx)),index=idx)
    
    In [56]: ts['2001']
    
    2001-10-31    0.106719
    2001-11-30    0.587050
    2001-12-31    0.786046
    Freq: M, dtype: float64
    
    In [57]: df = DataFrame(dict(A = ts))
    
    In [58]: df['2001']
    
                       A
    2001-10-31  0.106719
    2001-11-30  0.587050
    2001-12-31  0.786046
    
  • Squeeze to possibly remove length 1 dimensions from an object.

    In [59]: p = Panel(randn(3,4,4),items=['ItemA','ItemB','ItemC'],
       ....:                    major_axis=date_range('20010102',periods=4),
       ....:                    minor_axis=['A','B','C','D'])
       ....: 
    
    In [60]: p
    
    <class 'pandas.core.panel.Panel'>
    Dimensions: 3 (items) x 4 (major_axis) x 4 (minor_axis)
    Items axis: ItemA to ItemC
    Major_axis axis: 2001-01-02 00:00:00 to 2001-01-05 00:00:00
    Minor_axis axis: A to D
    
    In [61]: p.reindex(items=['ItemA']).squeeze()
    
                       A         B         C         D
    2001-01-02 -0.120299  0.689789 -1.583395  0.231558
    2001-01-03 -1.426036 -0.772086 -1.492508 -0.850913
    2001-01-04 -0.165161  0.601913 -1.942011  0.168730
    2001-01-05  0.988615  0.073211  1.093337  0.527013
    
    In [62]: p.reindex(items=['ItemA'],minor=['B']).squeeze()
    
    2001-01-02    0.689789
    2001-01-03   -0.772086
    2001-01-04    0.601913
    2001-01-05    0.073211
    Freq: D, Name: B, dtype: float64
    
  • In pd.io.data.Options,

    • Fix bug when trying to fetch data for the current month when already past expiry.
    • Now using lxml to scrape html instead of BeautifulSoup (lxml was faster).
    • New instance variables for calls and puts are automatically created when a method that creates them is called. This works for current month where the instance variables are simply calls and puts. Also works for future expiry months and save the instance variable as callsMMYY or putsMMYY, where MMYY are, respectively, the month and year of the option’s expiry.
    • Options.get_near_stock_price now allows the user to specify the month for which to get relevant options data.
    • Options.get_forward_data now has optional kwargs near and above_below. This allows the user to specify if they would like to only return forward looking data for options near the current stock price. This just obtains the data from Options.get_near_stock_price instead of Options.get_xxx_data() (GH2758).
  • Cursor coordinate information is now displayed in time-series plots.

  • added option display.max_seq_items to control the number of elements printed per sequence pprinting it. (GH2979)

  • added option display.chop_threshold to control display of small numerical values. (GH2739)

  • added option display.max_info_rows to prevent verbose_info from being calculated for frames above 1M rows (configurable). (GH2807, GH2918)

  • value_counts() now accepts a “normalize” argument, for normalized histograms. (GH2710).

  • DataFrame.from_records now accepts not only dicts but any instance of the collections.Mapping ABC.

  • added option display.mpl_style providing a sleeker visual style for plots. Based on https://gist.github.com/huyng/816622 (GH3075).

  • Treat boolean values as integers (values 1 and 0) for numeric operations. (GH2641)

  • to_html() now accepts an optional “escape” argument to control reserved HTML character escaping (enabled by default) and escapes &, in addition to < and >. (GH2919)

See the full release notes or issue tracker on GitHub for a complete list.

v0.10.1 (January 22, 2013)

This is a minor release from 0.10.0 and includes new features, enhancements, and bug fixes. In particular, there is substantial new HDFStore functionality contributed by Jeff Reback.

An undesired API breakage with functions taking the inplace option has been reverted and deprecation warnings added.

API changes

  • Functions taking an inplace option return the calling object as before. A deprecation message has been added
  • Groupby aggregations Max/Min no longer exclude non-numeric data (GH2700)
  • Resampling an empty DataFrame now returns an empty DataFrame instead of raising an exception (GH2640)
  • The file reader will now raise an exception when NA values are found in an explicitly specified integer column instead of converting the column to float (GH2631)
  • DatetimeIndex.unique now returns a DatetimeIndex with the same name and
  • timezone instead of an array (GH2563)

New features

  • MySQL support for database (contribution from Dan Allan)

HDFStore

You may need to upgrade your existing data files. Please visit the compatibility section in the main docs.

You can designate (and index) certain columns that you want to be able to perform queries on a table, by passing a list to data_columns

In [1]: store = HDFStore('store.h5')

In [2]: df = DataFrame(randn(8, 3), index=date_range('1/1/2000', periods=8),
   ...:            columns=['A', 'B', 'C'])
   ...: 

In [3]: df['string'] = 'foo'

In [4]: df.ix[4:6,'string'] = np.nan

In [5]: df.ix[7:9,'string'] = 'bar'

In [6]: df['string2'] = 'cool'

In [7]: df

                   A         B         C string string2
2000-01-01 -0.769489  0.424965 -2.399628    foo    cool
2000-01-02 -2.192836 -0.473283 -1.308975    foo    cool
2000-01-03 -1.514850  0.078231  0.381254    foo    cool
2000-01-04 -2.146455 -0.371330  0.620463    foo    cool
2000-01-05  0.002826  0.472304 -2.245639    NaN    cool
2000-01-06 -0.849584 -1.002201 -0.303299    NaN    cool
2000-01-07 -0.982759  0.209295  0.908561    foo    cool
2000-01-08 -1.089538  0.054213 -0.264808    bar    cool

# on-disk operations
In [8]: store.append('df', df, data_columns = ['B','C','string','string2'])

In [9]: store.select('df',[ 'B > 0', 'string == foo' ])

                   A         B         C string string2
2000-01-01 -0.769489  0.424965 -2.399628    foo    cool
2000-01-03 -1.514850  0.078231  0.381254    foo    cool
2000-01-07 -0.982759  0.209295  0.908561    foo    cool

# this is in-memory version of this type of selection
In [10]: df[(df.B > 0) & (df.string == 'foo')]

                   A         B         C string string2
2000-01-01 -0.769489  0.424965 -2.399628    foo    cool
2000-01-03 -1.514850  0.078231  0.381254    foo    cool
2000-01-07 -0.982759  0.209295  0.908561    foo    cool

Retrieving unique values in an indexable or data column.

In [11]: import warnings

In [12]: with warnings.catch_warnings():
   ....:     warnings.simplefilter('ignore', category=UserWarning)
   ....:     store.unique('df','index')
   ....:     store.unique('df','string')
   ....: 

You can now store datetime64 in data columns

In [13]: df_mixed               = df.copy()

In [14]: df_mixed['datetime64'] = Timestamp('20010102')

In [15]: df_mixed.ix[3:4,['A','B']] = np.nan

In [16]: store.append('df_mixed', df_mixed)

In [17]: df_mixed1 = store.select('df_mixed')

In [18]: df_mixed1

                   A         B         C string string2          datetime64
2000-01-01 -0.769489  0.424965 -2.399628    foo    cool 2001-01-02 00:00:00
2000-01-02 -2.192836 -0.473283 -1.308975    foo    cool 2001-01-02 00:00:00
2000-01-03 -1.514850  0.078231  0.381254    foo    cool 2001-01-02 00:00:00
2000-01-04       NaN       NaN  0.620463    foo    cool 2001-01-02 00:00:00
2000-01-05  0.002826  0.472304 -2.245639    NaN    cool 2001-01-02 00:00:00
2000-01-06 -0.849584 -1.002201 -0.303299    NaN    cool 2001-01-02 00:00:00
2000-01-07 -0.982759  0.209295  0.908561    foo    cool 2001-01-02 00:00:00
2000-01-08 -1.089538  0.054213 -0.264808    bar    cool 2001-01-02 00:00:00

In [19]: df_mixed1.get_dtype_counts()

datetime64[ns]    1
float64           3
object            2
dtype: int64

You can pass columns keyword to select to filter a list of the return columns, this is equivalent to passing a Term('columns',list_of_columns_to_filter)

In [20]: store.select('df',columns = ['A','B'])

                   A         B
2000-01-01 -0.769489  0.424965
2000-01-02 -2.192836 -0.473283
2000-01-03 -1.514850  0.078231
2000-01-04 -2.146455 -0.371330
2000-01-05  0.002826  0.472304
2000-01-06 -0.849584 -1.002201
2000-01-07 -0.982759  0.209295
2000-01-08 -1.089538  0.054213

HDFStore now serializes multi-index dataframes when appending tables.

In [21]: index = MultiIndex(levels=[['foo', 'bar', 'baz', 'qux'],
   ....:                            ['one', 'two', 'three']],
   ....:                    labels=[[0, 0, 0, 1, 1, 2, 2, 3, 3, 3],
   ....:                            [0, 1, 2, 0, 1, 1, 2, 0, 1, 2]],
   ....:                    names=['foo', 'bar'])
   ....: 

In [22]: df = DataFrame(np.random.randn(10, 3), index=index,
   ....:                columns=['A', 'B', 'C'])
   ....: 

In [23]: df

                  A         B         C
foo bar                                
foo one    0.294470  0.135678 -0.022752
    two   -0.200022  0.256220  0.140280
    three  0.357724  0.170160 -1.358587
bar one    0.895622  0.802917  0.188661
    two    1.149702  0.696241 -1.026172
baz two   -2.450084 -0.640607 -1.654442
    three -0.415947  0.429696 -1.049600
qux one    0.689080  1.265060  1.956265
    two    0.362942 -0.465987  0.684614
    three  1.240014  1.022146 -1.242964

In [24]: store.append('mi',df)

In [25]: store.select('mi')

                  A         B         C
foo bar                                
foo one    0.294470  0.135678 -0.022752
    two   -0.200022  0.256220  0.140280
    three  0.357724  0.170160 -1.358587
bar one    0.895622  0.802917  0.188661
    two    1.149702  0.696241 -1.026172
baz two   -2.450084 -0.640607 -1.654442
    three -0.415947  0.429696 -1.049600
qux one    0.689080  1.265060  1.956265
    two    0.362942 -0.465987  0.684614
    three  1.240014  1.022146 -1.242964

# the levels are automatically included as data columns
In [26]: store.select('mi', Term('foo=bar'))

                A         B         C
foo bar                              
bar one  0.895622  0.802917  0.188661
    two  1.149702  0.696241 -1.026172

Multi-table creation via append_to_multiple and selection via select_as_multiple can create/select from multiple tables and return a combined result, by using where on a selector table.

In [27]: df_mt = DataFrame(randn(8, 6), index=date_range('1/1/2000', periods=8),
   ....:                                columns=['A', 'B', 'C', 'D', 'E', 'F'])
   ....: 

In [28]: df_mt['foo'] = 'bar'

# you can also create the tables individually
In [29]: store.append_to_multiple({ 'df1_mt' : ['A','B'], 'df2_mt' : None }, df_mt, selector = 'df1_mt')

In [30]: store

<class 'pandas.io.pytables.HDFStore'>
File path: store.h5
/df                  frame_table  (typ->appendable,nrows->8,ncols->5,indexers->[index],dc->[B,C,string,string2])
/df1_mt              frame_table  (typ->appendable,nrows->8,ncols->2,indexers->[index],dc->[A,B])               
/df2_mt              frame_table  (typ->appendable,nrows->8,ncols->5,indexers->[index])                         
/df_mixed            frame_table  (typ->appendable,nrows->8,ncols->6,indexers->[index])                         
/mi                  frame_table  (typ->appendable_multi,nrows->10,ncols->5,indexers->[index],dc->[bar,foo])    

# indiviual tables were created
In [31]: store.select('df1_mt')

                   A         B
2000-01-01  0.768460 -0.057566
2000-01-02  0.350837  0.875039
2000-01-03 -0.057137 -0.688849
2000-01-04  1.555574 -0.248194
2000-01-05  0.995767  0.606351
2000-01-06  1.728000  1.734583
2000-01-07 -0.574095  0.216992
2000-01-08  0.093835 -0.311742

In [32]: store.select('df2_mt')

                   C         D         E         F  foo
2000-01-01  0.465511 -1.234034  0.593461  0.833259  bar
2000-01-02 -0.165315  1.134751  0.839545  0.516851  bar
2000-01-03 -1.725258 -2.526898  0.391201  1.539931  bar
2000-01-04 -0.395961  0.543736  0.077688  0.354689  bar
2000-01-05  0.845677  0.542023  0.402085 -0.525700  bar
2000-01-06 -0.747668  2.500444  0.590482  0.138810  bar
2000-01-07 -0.113490 -0.085532 -0.672853  0.208339  bar
2000-01-08 -1.406835 -0.671815 -0.299850 -1.630263  bar

# as a multiple
In [33]: store.select_as_multiple(['df1_mt','df2_mt'], where = [ 'A>0','B>0' ], selector = 'df1_mt')

                   A         B         C         D         E        F  foo
2000-01-03       NaN       NaN       NaN       NaN       NaN      NaN  NaN
2000-01-04       NaN       NaN       NaN       NaN       NaN      NaN  NaN
2000-01-05  0.995767  0.606351  0.845677  0.542023  0.402085 -0.52570  bar
2000-01-06  1.728000  1.734583 -0.747668  2.500444  0.590482  0.13881  bar

Enhancements

  • HDFStore now can read native PyTables table format tables
  • You can pass nan_rep = 'my_nan_rep' to append, to change the default nan representation on disk (which converts to/from np.nan), this defaults to nan.
  • You can pass index to append. This defaults to True. This will automagically create indicies on the indexables and data columns of the table
  • You can pass chunksize=an integer to append, to change the writing chunksize (default is 50000). This will signficantly lower your memory usage on writing.
  • You can pass expectedrows=an integer to the first append, to set the TOTAL number of expectedrows that PyTables will expected. This will optimize read/write performance.
  • Select now supports passing start and stop to provide selection space limiting in selection.
  • Greatly improved ISO8601 (e.g., yyyy-mm-dd) date parsing for file parsers (GH2698)
  • Allow DataFrame.merge to handle combinatorial sizes too large for 64-bit integer (GH2690)
  • Series now has unary negation (-series) and inversion (~series) operators (GH2686)
  • DataFrame.plot now includes a logx parameter to change the x-axis to log scale (GH2327)
  • Series arithmetic operators can now handle constant and ndarray input (GH2574)
  • ExcelFile now takes a kind argument to specify the file type (GH2613)
  • A faster implementation for Series.str methods (GH2602)

Bug Fixes

  • HDFStore tables can now store float32 types correctly (cannot be mixed with float64 however)
  • Fixed Google Analytics prefix when specifying request segment (GH2713).
  • Function to reset Google Analytics token store so users can recover from improperly setup client secrets (GH2687).
  • Fixed groupby bug resulting in segfault when passing in MultiIndex (GH2706)
  • Fixed bug where passing a Series with datetime64 values into to_datetime results in bogus output values (GH2699)
  • Fixed bug in pattern in HDFStore expressions when pattern is not a valid regex (GH2694)
  • Fixed performance issues while aggregating boolean data (GH2692)
  • When given a boolean mask key and a Series of new values, Series __setitem__ will now align the incoming values with the original Series (GH2686)
  • Fixed MemoryError caused by performing counting sort on sorting MultiIndex levels with a very large number of combinatorial values (GH2684)
  • Fixed bug that causes plotting to fail when the index is a DatetimeIndex with a fixed-offset timezone (GH2683)
  • Corrected businessday subtraction logic when the offset is more than 5 bdays and the starting date is on a weekend (GH2680)
  • Fixed C file parser behavior when the file has more columns than data (GH2668)
  • Fixed file reader bug that misaligned columns with data in the presence of an implicit column and a specified usecols value
  • DataFrames with numerical or datetime indices are now sorted prior to plotting (GH2609)
  • Fixed DataFrame.from_records error when passed columns, index, but empty records (GH2633)
  • Several bug fixed for Series operations when dtype is datetime64 (GH2689, GH2629, GH2626)

See the full release notes or issue tracker on GitHub for a complete list.

v0.10.0 (December 17, 2012)

This is a major release from 0.9.1 and includes many new features and enhancements along with a large number of bug fixes. There are also a number of important API changes that long-time pandas users should pay close attention to.

File parsing new features

The delimited file parsing engine (the guts of read_csv and read_table) has been rewritten from the ground up and now uses a fraction the amount of memory while parsing, while being 40% or more faster in most use cases (in some cases much faster).

There are also many new features:

  • Much-improved Unicode handling via the encoding option.
  • Column filtering (usecols)
  • Dtype specification (dtype argument)
  • Ability to specify strings to be recognized as True/False
  • Ability to yield NumPy record arrays (as_recarray)
  • High performance delim_whitespace option
  • Decimal format (e.g. European format) specification
  • Easier CSV dialect options: escapechar, lineterminator, quotechar, etc.
  • More robust handling of many exceptional kinds of files observed in the wild

API changes

Deprecated DataFrame BINOP TimeSeries special case behavior

The default behavior of binary operations between a DataFrame and a Series has always been to align on the DataFrame’s columns and broadcast down the rows, except in the special case that the DataFrame contains time series. Since there are now method for each binary operator enabling you to specify how you want to broadcast, we are phasing out this special case (Zen of Python: Special cases aren’t special enough to break the rules). Here’s what I’m talking about:

In [1]: import pandas as pd

In [2]: df = pd.DataFrame(np.random.randn(6, 4),
   ...:                   index=pd.date_range('1/1/2000', periods=6))
   ...: 

In [3]: df

                   0         1         2         3
2000-01-01 -0.413827  0.629132  0.298770 -0.237729
2000-01-02 -0.669590 -0.496145 -0.241407  0.015766
2000-01-03  0.926027  1.167866 -2.064089  0.372602
2000-01-04 -0.214600  0.037143  0.423940  1.351143
2000-01-05 -0.562857 -0.496996 -0.050571 -1.174954
2000-01-06  0.034020  0.475296 -0.277230 -0.933706

# deprecated now
In [4]: df - df[0]

            0         1         2         3
2000-01-01  0  1.042958  0.712597  0.176098
2000-01-02  0  0.173445  0.428183  0.685357
2000-01-03  0  0.241840 -2.990116 -0.553425
2000-01-04  0  0.251743  0.638539  1.565743
2000-01-05  0  0.065861  0.512286 -0.612097
2000-01-06  0  0.441276 -0.311250 -0.967725

# Change your code to
In [5]: df.sub(df[0], axis=0) # align on axis 0 (rows)

            0         1         2         3
2000-01-01  0  1.042958  0.712597  0.176098
2000-01-02  0  0.173445  0.428183  0.685357
2000-01-03  0  0.241840 -2.990116 -0.553425
2000-01-04  0  0.251743  0.638539  1.565743
2000-01-05  0  0.065861  0.512286 -0.612097
2000-01-06  0  0.441276 -0.311250 -0.967725

You will get a deprecation warning in the 0.10.x series, and the deprecated functionality will be removed in 0.11 or later.

Altered resample default behavior

The default time series resample binning behavior of daily D and higher frequencies has been changed to closed='left', label='left'. Lower nfrequencies are unaffected. The prior defaults were causing a great deal of confusion for users, especially resampling data to daily frequency (which labeled the aggregated group with the end of the interval: the next day).

Note:

In [6]: dates = pd.date_range('1/1/2000', '1/5/2000', freq='4h')

In [7]: series = Series(np.arange(len(dates)), index=dates)

In [8]: series

2000-01-01 00:00:00     0
2000-01-01 04:00:00     1
2000-01-01 08:00:00     2
2000-01-01 12:00:00     3
2000-01-01 16:00:00     4
2000-01-01 20:00:00     5
2000-01-02 00:00:00     6
2000-01-02 04:00:00     7
2000-01-02 08:00:00     8
2000-01-02 12:00:00     9
2000-01-02 16:00:00    10
2000-01-02 20:00:00    11
2000-01-03 00:00:00    12
2000-01-03 04:00:00    13
2000-01-03 08:00:00    14
2000-01-03 12:00:00    15
2000-01-03 16:00:00    16
2000-01-03 20:00:00    17
2000-01-04 00:00:00    18
2000-01-04 04:00:00    19
2000-01-04 08:00:00    20
2000-01-04 12:00:00    21
2000-01-04 16:00:00    22
2000-01-04 20:00:00    23
2000-01-05 00:00:00    24
Freq: 4H, dtype: int64

In [9]: series.resample('D', how='sum')

2000-01-01     15
2000-01-02     51
2000-01-03     87
2000-01-04    123
2000-01-05     24
Freq: D, dtype: int64

# old behavior
In [10]: series.resample('D', how='sum', closed='right', label='right')

2000-01-01      0
2000-01-02     21
2000-01-03     57
2000-01-04     93
2000-01-05    129
Freq: D, dtype: int64
  • Infinity and negative infinity are no longer treated as NA by isnull and notnull. That they every were was a relic of early pandas. This behavior can be re-enabled globally by the mode.use_inf_as_null option:
In [11]: s = pd.Series([1.5, np.inf, 3.4, -np.inf])

In [12]: pd.isnull(s)

0    False
1    False
2    False
3    False
dtype: bool

In [13]: s.fillna(0)

0    1.500000
1         inf
2    3.400000
3        -inf
dtype: float64

In [14]: pd.set_option('use_inf_as_null', True)

In [15]: pd.isnull(s)

0    False
1     True
2    False
3     True
dtype: bool

In [16]: s.fillna(0)

0    1.5
1    0.0
2    3.4
3    0.0
dtype: float64

In [17]: pd.reset_option('use_inf_as_null')
  • Methods with the inplace option now all return None instead of the calling object. E.g. code written like df = df.fillna(0, inplace=True) may stop working. To fix, simply delete the unnecessary variable assignment.
  • pandas.merge no longer sorts the group keys (sort=False) by default. This was done for performance reasons: the group-key sorting is often one of the more expensive parts of the computation and is often unnecessary.
  • The default column names for a file with no header have been changed to the integers 0 through N - 1. This is to create consistency with the DataFrame constructor with no columns specified. The v0.9.0 behavior (names X0, X1, ...) can be reproduced by specifying prefix='X':
In [18]: data= 'a,b,c\n1,Yes,2\n3,No,4'

In [19]: print data
a,b,c
1,Yes,2
3,No,4

In [20]: pd.read_csv(StringIO(data), header=None)

   0    1  2
0  a    b  c
1  1  Yes  2
2  3   No  4

In [21]: pd.read_csv(StringIO(data), header=None, prefix='X')

  X0   X1 X2
0  a    b  c
1  1  Yes  2
2  3   No  4
  • Values like 'Yes' and 'No' are not interpreted as boolean by default, though this can be controlled by new true_values and false_values arguments:
In [22]: print data
a,b,c
1,Yes,2
3,No,4

In [23]: pd.read_csv(StringIO(data))

   a    b  c
0  1  Yes  2
1  3   No  4

In [24]: pd.read_csv(StringIO(data), true_values=['Yes'], false_values=['No'])

   a      b  c
0  1   True  2
1  3  False  4
  • The file parsers will not recognize non-string values arising from a converter function as NA if passed in the na_values argument. It’s better to do post-processing using the replace function instead.
  • Calling fillna on Series or DataFrame with no arguments is no longer valid code. You must either specify a fill value or an interpolation method:
In [25]: s = Series([np.nan, 1., 2., np.nan, 4])

In [26]: s

0   NaN
1     1
2     2
3   NaN
4     4
dtype: float64

In [27]: s.fillna(0)

0    0
1    1
2    2
3    0
4    4
dtype: float64

In [28]: s.fillna(method='pad')

0   NaN
1     1
2     2
3     2
4     4
dtype: float64

Convenience methods ffill and bfill have been added:

In [29]: s.ffill()

0   NaN
1     1
2     2
3     2
4     4
dtype: float64
  • Series.apply will now operate on a returned value from the applied function, that is itself a series, and possibly upcast the result to a DataFrame

    In [30]: def f(x):
       ....:     return Series([ x, x**2 ], index = ['x', 'x^2'])
       ....: 
    
    In [31]: s = Series(np.random.rand(5))
    
    In [32]: s
    
    0    0.613592
    1    0.769406
    2    0.468244
    3    0.836326
    4    0.128879
    dtype: float64
    
    In [33]: s.apply(f)
    
              x       x^2
    0  0.613592  0.376496
    1  0.769406  0.591985
    2  0.468244  0.219253
    3  0.836326  0.699442
    4  0.128879  0.016610
    
  • New API functions for working with pandas options (GH2097):

    • get_option / set_option - get/set the value of an option. Partial names are accepted. - reset_option - reset one or more options to their default value. Partial names are accepted. - describe_option - print a description of one or more options. When called with no arguments. print all registered options.

    Note: set_printoptions/ reset_printoptions are now deprecated (but functioning), the print options now live under “display.XYZ”. For example:

    In [34]: get_option("display.max_rows")
    60
    
  • to_string() methods now always return unicode strings (GH2224).

New features

Wide DataFrame Printing

Instead of printing the summary information, pandas now splits the string representation across multiple rows by default:

In [35]: wide_frame = DataFrame(randn(5, 16))

In [36]: wide_frame

         0         1         2         3         4         5         6   \
0 -0.827639 -0.816706  0.603429 -1.931547  1.779999  0.024273 -2.239311   
1 -0.715313 -0.153854  0.698947 -1.233408  1.251011  0.123857 -0.990684   
2  1.519298  1.233602  0.830518  0.330667 -0.007652  1.623959  0.200346   
3 -1.306721  0.034066 -0.929118 -2.245334  0.131842 -0.184247  0.497157   
4 -0.045029 -0.102145 -1.081173 -0.336105  0.124110 -0.325763  0.505789   
         7         8         9         10        11        12        13  \
0 -1.186057 -0.924978  0.407929 -1.022817 -0.575870 -0.082379 -0.696202   
1 -0.203066  0.335089 -0.093407  0.533182  0.418369 -0.151378 -0.491670   
2  0.020121  0.814141  0.422690  0.425065  0.457886 -0.781064  0.018526   
3  0.367061  0.531170  1.017521 -0.071251  0.100287  0.688424 -1.408056   
4  0.331683  0.749208  1.657286  0.621129  1.076158  0.107174  1.703447   
         14        15  
0 -1.581168  0.056498  
1 -2.083875  1.046906  
2 -0.805903 -0.547564  
3 -0.258734 -0.632736  
4  0.804157 -2.014735  

The old behavior of printing out summary information can be achieved via the ‘expand_frame_repr’ print option:

In [37]: pd.set_option('expand_frame_repr', False)

In [38]: wide_frame

<class 'pandas.core.frame.DataFrame'>
Int64Index: 5 entries, 0 to 4
Data columns (total 16 columns):
0     5  non-null values
1     5  non-null values
2     5  non-null values
3     5  non-null values
4     5  non-null values
5     5  non-null values
6     5  non-null values
7     5  non-null values
8     5  non-null values
9     5  non-null values
10    5  non-null values
11    5  non-null values
12    5  non-null values
13    5  non-null values
14    5  non-null values
15    5  non-null values
dtypes: float64(16)

The width of each line can be changed via ‘line_width’ (80 by default):

In [39]: pd.set_option('line_width', 40)

In [40]: wide_frame

         0         1         2   \
0 -0.827639 -0.816706  0.603429   
1 -0.715313 -0.153854  0.698947   
2  1.519298  1.233602  0.830518   
3 -1.306721  0.034066 -0.929118   
4 -0.045029 -0.102145 -1.081173   
         3         4         5   \
0 -1.931547  1.779999  0.024273   
1 -1.233408  1.251011  0.123857   
2  0.330667 -0.007652  1.623959   
3 -2.245334  0.131842 -0.184247   
4 -0.336105  0.124110 -0.325763   
         6         7         8   \
0 -2.239311 -1.186057 -0.924978   
1 -0.990684 -0.203066  0.335089   
2  0.200346  0.020121  0.814141   
3  0.497157  0.367061  0.531170   
4  0.505789  0.331683  0.749208   
         9         10        11  \
0  0.407929 -1.022817 -0.575870   
1 -0.093407  0.533182  0.418369   
2  0.422690  0.425065  0.457886   
3  1.017521 -0.071251  0.100287   
4  1.657286  0.621129  1.076158   
         12        13        14  \
0 -0.082379 -0.696202 -1.581168   
1 -0.151378 -0.491670 -2.083875   
2 -0.781064  0.018526 -0.805903   
3  0.688424 -1.408056 -0.258734   
4  0.107174  1.703447  0.804157   
         15  
0  0.056498  
1  1.046906  
2 -0.547564  
3 -0.632736  
4 -2.014735  

Updated PyTables Support

Docs for PyTables Table format & several enhancements to the api. Here is a taste of what to expect.

In [41]: store = HDFStore('store.h5')

In [42]: df = DataFrame(randn(8, 3), index=date_range('1/1/2000', periods=8),
   ....:            columns=['A', 'B', 'C'])
   ....: 

In [43]: df

                   A         B         C
2000-01-01  0.472926 -1.615450  0.123502
2000-01-02 -0.253527  1.354506  0.870047
2000-01-03 -0.896321 -0.356776 -0.868625
2000-01-04  0.489542 -3.282162  0.525669
2000-01-05 -1.071854  0.498022 -1.902799
2000-01-06  2.177016  0.108157  0.625921
2000-01-07 -1.013489 -0.340575 -1.955101
2000-01-08  0.840414 -0.310110 -0.024645

# appending data frames
In [44]: df1 = df[0:4]

In [45]: df2 = df[4:]

In [46]: store.append('df', df1)

In [47]: store.append('df', df2)

In [48]: store

<class 'pandas.io.pytables.HDFStore'>
File path: store.h5
/df            frame_table  (typ->appendable,nrows->8,ncols->3,indexers->[index])

# selecting the entire store
In [49]: store.select('df')

                   A         B         C
2000-01-01  0.472926 -1.615450  0.123502
2000-01-02 -0.253527  1.354506  0.870047
2000-01-03 -0.896321 -0.356776 -0.868625
2000-01-04  0.489542 -3.282162  0.525669
2000-01-05 -1.071854  0.498022 -1.902799
2000-01-06  2.177016  0.108157  0.625921
2000-01-07 -1.013489 -0.340575 -1.955101
2000-01-08  0.840414 -0.310110 -0.024645
In [50]: wp = Panel(randn(2, 5, 4), items=['Item1', 'Item2'],
   ....:        major_axis=date_range('1/1/2000', periods=5),
   ....:        minor_axis=['A', 'B', 'C', 'D'])
   ....: 

In [51]: wp

<class 'pandas.core.panel.Panel'>
Dimensions: 2 (items) x 5 (major_axis) x 4 (minor_axis)
Items axis: Item1 to Item2
Major_axis axis: 2000-01-01 00:00:00 to 2000-01-05 00:00:00
Minor_axis axis: A to D

# storing a panel
In [52]: store.append('wp',wp)

# selecting via A QUERY
In [53]: store.select('wp',
   ....:   [ Term('major_axis>20000102'), Term('minor_axis', '=', ['A','B']) ])
   ....: 

<class 'pandas.core.panel.Panel'>
Dimensions: 2 (items) x 3 (major_axis) x 2 (minor_axis)
Items axis: Item1 to Item2
Major_axis axis: 2000-01-03 00:00:00 to 2000-01-05 00:00:00
Minor_axis axis: A to B

# removing data from tables
In [54]: store.remove('wp', [ 'major_axis', '>', wp.major_axis[3] ])
4

In [55]: store.select('wp')

<class 'pandas.core.panel.Panel'>
Dimensions: 2 (items) x 4 (major_axis) x 4 (minor_axis)
Items axis: Item1 to Item2
Major_axis axis: 2000-01-01 00:00:00 to 2000-01-04 00:00:00
Minor_axis axis: A to D

# deleting a store
In [56]: del store['df']

In [57]: store

<class 'pandas.io.pytables.HDFStore'>
File path: store.h5
/wp            wide_table   (typ->appendable,nrows->16,ncols->2,indexers->[major_axis,minor_axis])

Enhancements

  • added ability to hierarchical keys

    In [58]: store.put('foo/bar/bah', df)
    
    In [59]: store.append('food/orange', df)
    
    In [60]: store.append('food/apple',  df)
    
    In [61]: store
    
    <class 'pandas.io.pytables.HDFStore'>
    File path: store.h5
    /wp                     wide_table   (typ->appendable,nrows->16,ncols->2,indexers->[major_axis,minor_axis])
    /food/apple             frame_table  (typ->appendable,nrows->8,ncols->3,indexers->[index])                 
    /food/orange            frame_table  (typ->appendable,nrows->8,ncols->3,indexers->[index])                 
    /foo/bar/bah            frame        (shape->[8,3])                                                        
    
    # remove all nodes under this level
    In [62]: store.remove('food')
    
    In [63]: store
    
    <class 'pandas.io.pytables.HDFStore'>
    File path: store.h5
    /wp                     wide_table   (typ->appendable,nrows->16,ncols->2,indexers->[major_axis,minor_axis])
    /foo/bar/bah            frame        (shape->[8,3])                                                        
    
  • added mixed-dtype support!

    In [64]: df['string'] = 'string'
    
    In [65]: df['int']    = 1
    
    In [66]: store.append('df',df)
    
    In [67]: df1 = store.select('df')
    
    In [68]: df1
    
                       A         B         C  string  int
    2000-01-01  0.472926 -1.615450  0.123502  string    1
    2000-01-02 -0.253527  1.354506  0.870047  string    1
    2000-01-03 -0.896321 -0.356776 -0.868625  string    1
    2000-01-04  0.489542 -3.282162  0.525669  string    1
    2000-01-05 -1.071854  0.498022 -1.902799  string    1
    2000-01-06  2.177016  0.108157  0.625921  string    1
    2000-01-07 -1.013489 -0.340575 -1.955101  string    1
    2000-01-08  0.840414 -0.310110 -0.024645  string    1
    
    In [69]: df1.get_dtype_counts()
    
    float64    3
    int64      1
    object     1
    dtype: int64
    
  • performance improvments on table writing

  • support for arbitrarily indexed dimensions

  • SparseSeries now has a density property (GH2384)

  • enable Series.str.strip/lstrip/rstrip methods to take an input argument to strip arbitrary characters (GH2411)

  • implement value_vars in melt to limit values to certain columns and add melt to pandas namespace (GH2412)

Bug Fixes

  • added Term method of specifying where conditions (GH1996).
  • del store['df'] now call store.remove('df') for store deletion
  • deleting of consecutive rows is much faster than before
  • min_itemsize parameter can be specified in table creation to force a minimum size for indexing columns (the previous implementation would set the column size based on the first append)
  • indexing support via create_table_index (requires PyTables >= 2.3) (GH698).
  • appending on a store would fail if the table was not first created via put
  • fixed issue with missing attributes after loading a pickled dataframe (GH2431)
  • minor change to select and remove: require a table ONLY if where is also provided (and not None)

Compatibility

0.10 of HDFStore is backwards compatible for reading tables created in a prior version of pandas, however, query terms using the prior (undocumented) methodology are unsupported. You must read in the entire file and write it out using the new format to take advantage of the updates.

N Dimensional Panels (Experimental)

Adding experimental support for Panel4D and factory functions to create n-dimensional named panels. Docs for NDim. Here is a taste of what to expect.

In [70]: p4d = Panel4D(randn(2, 2, 5, 4),
   ....:       labels=['Label1','Label2'],
   ....:       items=['Item1', 'Item2'],
   ....:       major_axis=date_range('1/1/2000', periods=5),
   ....:       minor_axis=['A', 'B', 'C', 'D'])
   ....: 

In [71]: p4d

<class 'pandas.core.panelnd.Panel4D'>
Dimensions: 2 (labels) x 2 (items) x 5 (major_axis) x 4 (minor_axis)
Labels axis: Label1 to Label2
Items axis: Item1 to Item2
Major_axis axis: 2000-01-01 00:00:00 to 2000-01-05 00:00:00
Minor_axis axis: A to D

See the full release notes or issue tracker on GitHub for a complete list.

v0.9.1 (November 14, 2012)

This is a bugfix release from 0.9.0 and includes several new features and enhancements along with a large number of bug fixes. The new features include by-column sort order for DataFrame and Series, improved NA handling for the rank method, masking functions for DataFrame, and intraday time-series filtering for DataFrame.

New features

  • Series.sort, DataFrame.sort, and DataFrame.sort_index can now be specified in a per-column manner to support multiple sort orders (GH928)

    In [1]: df = DataFrame(np.random.randint(0, 2, (6, 3)), columns=['A', 'B', 'C'])
    
    In [2]: df.sort(['A', 'B'], ascending=[1, 0])
    
       A  B  C
    0  0  1  0
    5  0  1  0
    1  0  0  0
    4  0  0  1
    2  1  0  1
    3  1  0  1
    
  • DataFrame.rank now supports additional argument values for the na_option parameter so missing values can be assigned either the largest or the smallest rank (GH1508, GH2159)

    In [3]: df = DataFrame(np.random.randn(6, 3), columns=['A', 'B', 'C'])
    
    In [4]: df.ix[2:4] = np.nan
    
    In [5]: df.rank()
    
        A   B   C
    0   2   2   3
    1   3   3   1
    2 NaN NaN NaN
    3 NaN NaN NaN
    4 NaN NaN NaN
    5   1   1   2
    
    In [6]: df.rank(na_option='top')
    
       A  B  C
    0  5  5  6
    1  6  6  4
    2  2  2  2
    3  2  2  2
    4  2  2  2
    5  4  4  5
    
    In [7]: df.rank(na_option='bottom')
    
       A  B  C
    0  2  2  3
    1  3  3  1
    2  5  5  5
    3  5  5  5
    4  5  5  5
    5  1  1  2
    
  • DataFrame has new where and mask methods to select values according to a given boolean mask (GH2109, GH2151)

    DataFrame currently supports slicing via a boolean vector the same length as the DataFrame (inside the []). The returned DataFrame has the same number of columns as the original, but is sliced on its index.

    In [8]: df = DataFrame(np.random.randn(5, 3), columns = ['A','B','C'])
    
    In [9]: df
    
              A         B         C
    0 -1.630026  1.555465 -1.872323
    1 -0.732144  1.098388 -0.653544
    2  1.507659  0.886892  0.235305
    3  0.732701 -0.813539 -1.700478
    4  0.736007 -0.666061 -1.796996
    
    In [10]: df[df['A'] > 0]
    
              A         B         C
    2  1.507659  0.886892  0.235305
    3  0.732701 -0.813539 -1.700478
    4  0.736007 -0.666061 -1.796996
    

    If a DataFrame is sliced with a DataFrame based boolean condition (with the same size as the original DataFrame), then a DataFrame the same size (index and columns) as the original is returned, with elements that do not meet the boolean condition as NaN. This is accomplished via the new method DataFrame.where. In addition, where takes an optional other argument for replacement.

    In [11]: df[df>0]
    
              A         B         C
    0       NaN  1.555465       NaN
    1       NaN  1.098388       NaN
    2  1.507659  0.886892  0.235305
    3  0.732701       NaN       NaN
    4  0.736007       NaN       NaN
    
    In [12]: df.where(df>0)
    
              A         B         C
    0       NaN  1.555465       NaN
    1       NaN  1.098388       NaN
    2  1.507659  0.886892  0.235305
    3  0.732701       NaN       NaN
    4  0.736007       NaN       NaN
    
    In [13]: df.where(df>0,-df)
    
              A         B         C
    0  1.630026  1.555465  1.872323
    1  0.732144  1.098388  0.653544
    2  1.507659  0.886892  0.235305
    3  0.732701  0.813539  1.700478
    4  0.736007  0.666061  1.796996
    

    Furthermore, where now aligns the input boolean condition (ndarray or DataFrame), such that partial selection with setting is possible. This is analagous to partial setting via .ix (but on the contents rather than the axis labels)

    In [14]: df2 = df.copy()
    
    In [15]: df2[ df2[1:4] > 0 ] = 3
    
    In [16]: df2
    
              A         B         C
    0 -1.630026  1.555465 -1.872323
    1 -0.732144  3.000000 -0.653544
    2  3.000000  3.000000  3.000000
    3  3.000000 -0.813539 -1.700478
    4  0.736007 -0.666061 -1.796996
    

    DataFrame.mask is the inverse boolean operation of where.

    In [17]: df.mask(df<=0)
    
              A         B         C
    0       NaN  1.555465       NaN
    1       NaN  1.098388       NaN
    2  1.507659  0.886892  0.235305
    3  0.732701       NaN       NaN
    4  0.736007       NaN       NaN
    
  • Enable referencing of Excel columns by their column names (GH1936)

    In [18]: xl = ExcelFile('data/test.xls')
    
    In [19]: xl.parse('Sheet1', index_col=0, parse_dates=True,
       ....:          parse_cols='A:D')
       ....: 
    
                       A         B         C
    2000-01-03  0.980269  3.685731 -0.364217
    2000-01-04  1.047916 -0.041232 -0.161812
    2000-01-05  0.498581  0.731168 -0.537677
    2000-01-06  1.120202  1.567621  0.003641
    2000-01-07 -0.487094  0.571455 -1.611639
    2000-01-10  0.836649  0.246462  0.588543
    2000-01-11 -0.157161  1.340307  1.195778
    
  • Added option to disable pandas-style tick locators and formatters using series.plot(x_compat=True) or pandas.plot_params[‘x_compat’] = True (GH2205)

  • Existing TimeSeries methods at_time and between_time were added to DataFrame (GH2149)

  • DataFrame.dot can now accept ndarrays (GH2042)

  • DataFrame.drop now supports non-unique indexes (GH2101)

  • Panel.shift now supports negative periods (GH2164)

  • DataFrame now support unary ~ operator (GH2110)

API changes

  • Upsampling data with a PeriodIndex will result in a higher frequency TimeSeries that spans the original time window

    In [20]: prng = period_range('2012Q1', periods=2, freq='Q')
    
    In [21]: s = Series(np.random.randn(len(prng)), prng)
    
    In [22]: s.resample('M')
    
    2012-01   -0.376759
    2012-02         NaN
    2012-03         NaN
    2012-04   -0.927935
    2012-05         NaN
    2012-06         NaN
    Freq: M, dtype: float64
    
  • Period.end_time now returns the last nanosecond in the time interval (GH2124, GH2125, GH1764)

    In [23]: p = Period('2012')
    
    In [24]: p.end_time
    Timestamp('2012-12-31 23:59:59.999999999', tz=None)
    
  • File parsers no longer coerce to float or bool for columns that have custom converters specified (GH2184)

    In [25]: data = 'A,B,C\n00001,001,5\n00002,002,6'
    
    In [26]: from cStringIO import StringIO
    
    In [27]: read_csv(StringIO(data), converters={'A' : lambda x: x.strip()})
    
           A  B  C
    0  00001  1  5
    1  00002  2  6
    

See the full release notes or issue tracker on GitHub for a complete list.

v0.9.0 (October 7, 2012)

This is a major release from 0.8.1 and includes several new features and enhancements along with a large number of bug fixes. New features include vectorized unicode encoding/decoding for Series.str, to_latex method to DataFrame, more flexible parsing of boolean values, and enabling the download of options data from Yahoo! Finance.

New features

  • Add encode and decode for unicode handling to vectorized string processing methods in Series.str (GH1706)
  • Add DataFrame.to_latex method (GH1735)
  • Add convenient expanding window equivalents of all rolling_* ops (GH1785)
  • Add Options class to pandas.io.data for fetching options data from Yahoo! Finance (GH1748, GH1739)
  • More flexible parsing of boolean values (Yes, No, TRUE, FALSE, etc) (GH1691, GH1295)
  • Add level parameter to Series.reset_index
  • TimeSeries.between_time can now select times across midnight (GH1871)
  • Series constructor can now handle generator as input (GH1679)
  • DataFrame.dropna can now take multiple axes (tuple/list) as input (GH924)
  • Enable skip_footer parameter in ExcelFile.parse (GH1843)

API changes

  • The default column names when header=None and no columns names passed to functions like read_csv has changed to be more Pythonic and amenable to attribute access:
In [1]: from StringIO import StringIO

In [2]: data = '0,0,1\n1,1,0\n0,1,0'

In [3]: df = read_csv(StringIO(data), header=None)

In [4]: df

   0  1  2
0  0  0  1
1  1  1  0
2  0  1  0
  • Creating a Series from another Series, passing an index, will cause reindexing to happen inside rather than treating the Series like an ndarray. Technically improper usages like Series(df[col1], index=df[col2]) that worked before “by accident” (this was never intended) will lead to all NA Series in some cases. To be perfectly clear:
In [5]: s1 = Series([1, 2, 3])

In [6]: s1

0    1
1    2
2    3
dtype: int64

In [7]: s2 = Series(s1, index=['foo', 'bar', 'baz'])

In [8]: s2

foo   NaN
bar   NaN
baz   NaN
dtype: float64
  • Deprecated day_of_year API removed from PeriodIndex, use dayofyear (GH1723)
  • Don’t modify NumPy suppress printoption to True at import time
  • The internal HDF5 data arrangement for DataFrames has been transposed. Legacy files will still be readable by HDFStore (GH1834, GH1824)
  • Legacy cruft removed: pandas.stats.misc.quantileTS
  • Use ISO8601 format for Period repr: monthly, daily, and on down (GH1776)
  • Empty DataFrame columns are now created as object dtype. This will prevent a class of TypeErrors that was occurring in code where the dtype of a column would depend on the presence of data or not (e.g. a SQL query having results) (GH1783)
  • Setting parts of DataFrame/Panel using ix now aligns input Series/DataFrame (GH1630)
  • first and last methods in GroupBy no longer drop non-numeric columns (GH1809)
  • Resolved inconsistencies in specifying custom NA values in text parser. na_values of type dict no longer override default NAs unless keep_default_na is set to false explicitly (GH1657)
  • DataFrame.dot will not do data alignment, and also work with Series (GH1915)

See the full release notes or issue tracker on GitHub for a complete list.

v0.8.1 (July 22, 2012)

This release includes a few new features, performance enhancements, and over 30 bug fixes from 0.8.0. New features include notably NA friendly string processing functionality and a series of new plot types and options.

New features

Performance improvements

  • Improved implementation of rolling min and max (thanks to Bottleneck !)
  • Add accelerated 'median' GroupBy option (GH1358)
  • Significantly improve the performance of parsing ISO8601-format date strings with DatetimeIndex or to_datetime (GH1571)
  • Improve the performance of GroupBy on single-key aggregations and use with Categorical types
  • Significant datetime parsing performance improvments

v0.8.0 (June 29, 2012)

This is a major release from 0.7.3 and includes extensive work on the time series handling and processing infrastructure as well as a great deal of new functionality throughout the library. It includes over 700 commits from more than 20 distinct authors. Most pandas 0.7.3 and earlier users should not experience any issues upgrading, but due to the migration to the NumPy datetime64 dtype, there may be a number of bugs and incompatibilities lurking. Lingering incompatibilities will be fixed ASAP in a 0.8.1 release if necessary. See the full release notes or issue tracker on GitHub for a complete list.

Support for non-unique indexes

All objects can now work with non-unique indexes. Data alignment / join operations work according to SQL join semantics (including, if application, index duplication in many-to-many joins)

NumPy datetime64 dtype and 1.6 dependency

Time series data are now represented using NumPy’s datetime64 dtype; thus, pandas 0.8.0 now requires at least NumPy 1.6. It has been tested and verified to work with the development version (1.7+) of NumPy as well which includes some significant user-facing API changes. NumPy 1.6 also has a number of bugs having to do with nanosecond resolution data, so I recommend that you steer clear of NumPy 1.6’s datetime64 API functions (though limited as they are) and only interact with this data using the interface that pandas provides.

See the end of the 0.8.0 section for a “porting” guide listing potential issues for users migrating legacy codebases from pandas 0.7 or earlier to 0.8.0.

Bug fixes to the 0.7.x series for legacy NumPy < 1.6 users will be provided as they arise. There will be no more further development in 0.7.x beyond bug fixes.

Time series changes and improvements

Note

With this release, legacy scikits.timeseries users should be able to port their code to use pandas.

Note

See documentation for overview of pandas timeseries API.

  • New datetime64 representation speeds up join operations and data alignment, reduces memory usage, and improve serialization / deserialization performance significantly over datetime.datetime
  • High performance and flexible resample method for converting from high-to-low and low-to-high frequency. Supports interpolation, user-defined aggregation functions, and control over how the intervals and result labeling are defined. A suite of high performance Cython/C-based resampling functions (including Open-High-Low-Close) have also been implemented.
  • Revamp of frequency aliases and support for frequency shortcuts like ‘15min’, or ‘1h30min’
  • New DatetimeIndex class supports both fixed frequency and irregular time series. Replaces now deprecated DateRange class
  • New PeriodIndex and Period classes for representing time spans and performing calendar logic, including the 12 fiscal quarterly frequencies <timeseries.quarterly>. This is a partial port of, and a substantial enhancement to, elements of the scikits.timeseries codebase. Support for conversion between PeriodIndex and DatetimeIndex
  • New Timestamp data type subclasses datetime.datetime, providing the same interface while enabling working with nanosecond-resolution data. Also provides easy time zone conversions.
  • Enhanced support for time zones. Add tz_convert and tz_lcoalize methods to TimeSeries and DataFrame. All timestamps are stored as UTC; Timestamps from DatetimeIndex objects with time zone set will be localized to localtime. Time zone conversions are therefore essentially free. User needs to know very little about pytz library now; only time zone names as as strings are required. Time zone-aware timestamps are equal if and only if their UTC timestamps match. Operations between time zone-aware time series with different time zones will result in a UTC-indexed time series.
  • Time series string indexing conveniences / shortcuts: slice years, year and month, and index values with strings
  • Enhanced time series plotting; adaptation of scikits.timeseries matplotlib-based plotting code
  • New date_range, bdate_range, and period_range factory functions
  • Robust frequency inference function infer_freq and inferred_freq property of DatetimeIndex, with option to infer frequency on construction of DatetimeIndex
  • to_datetime function efficiently parses array of strings to DatetimeIndex. DatetimeIndex will parse array or list of strings to datetime64
  • Optimized support for datetime64-dtype data in Series and DataFrame columns
  • New NaT (Not-a-Time) type to represent NA in timestamp arrays
  • Optimize Series.asof for looking up “as of” values for arrays of timestamps
  • Milli, Micro, Nano date offset objects
  • Can index time series with datetime.time objects to select all data at particular time of day (TimeSeries.at_time) or between two times (TimeSeries.between_time)
  • Add tshift method for leading/lagging using the frequency (if any) of the index, as opposed to a naive lead/lag using shift

Other new features

  • New cut and qcut functions (like R’s cut function) for computing a categorical variable from a continuous variable by binning values either into value-based (cut) or quantile-based (qcut) bins
  • Rename Factor to Categorical and add a number of usability features
  • Add limit argument to fillna/reindex
  • More flexible multiple function application in GroupBy, and can pass list (name, function) tuples to get result in particular order with given names
  • Add flexible replace method for efficiently substituting values
  • Enhanced read_csv/read_table for reading time series data and converting multiple columns to dates
  • Add comments option to parser functions: read_csv, etc.
  • Add :ref`dayfirst <io.dayfirst>` option to parser functions for parsing international DD/MM/YYYY dates
  • Allow the user to specify the CSV reader dialect to control quoting etc.
  • Handling thousands separators in read_csv to improve integer parsing.
  • Enable unstacking of multiple levels in one shot. Alleviate pivot_table bugs (empty columns being introduced)
  • Move to klib-based hash tables for indexing; better performance and less memory usage than Python’s dict
  • Add first, last, min, max, and prod optimized GroupBy functions
  • New ordered_merge function
  • Add flexible comparison instance methods eq, ne, lt, gt, etc. to DataFrame, Series
  • Improve scatter_matrix plotting function and add histogram or kernel density estimates to diagonal
  • Add ‘kde’ plot option for density plots
  • Support for converting DataFrame to R data.frame through rpy2
  • Improved support for complex numbers in Series and DataFrame
  • Add pct_change method to all data structures
  • Add max_colwidth configuration option for DataFrame console output
  • Interpolate Series values using index values
  • Can select multiple columns from GroupBy
  • Add update methods to Series/DataFrame for updating values in place
  • Add any and all method to DataFrame

New plotting methods

Series.plot now supports a secondary_y option:

In [1]: plt.figure()
<matplotlib.figure.Figure at 0x1d487250>

In [2]: fx['FR'].plot(style='g')
<matplotlib.axes.AxesSubplot at 0x1d4876d0>

In [3]: fx['IT'].plot(style='k--', secondary_y=True)
<matplotlib.axes.AxesSubplot at 0x1cfc1b50>
_images/whatsnew_secondary_y.png

Vytautas Jancauskas, the 2012 GSOC participant, has added many new plot types. For example, 'kde' is a new option:

In [4]: s = Series(np.concatenate((np.random.randn(1000),
   ...:                            np.random.randn(1000) * 0.5 + 3)))
   ...: 

In [5]: plt.figure()
<matplotlib.figure.Figure at 0x1bd92b10>

In [6]: s.hist(normed=True, alpha=0.2)
<matplotlib.axes.AxesSubplot at 0x1d258d90>

In [7]: s.plot(kind='kde')
<matplotlib.axes.AxesSubplot at 0x1d258d90>
_images/whatsnew_kde.png

See the plotting page for much more.

Other API changes

  • Deprecation of offset, time_rule, and timeRule arguments names in time series functions. Warnings will be printed until pandas 0.9 or 1.0.

Potential porting issues for pandas <= 0.7.3 users

The major change that may affect you in pandas 0.8.0 is that time series indexes use NumPy’s datetime64 data type instead of dtype=object arrays of Python’s built-in datetime.datetime objects. DateRange has been replaced by DatetimeIndex but otherwise behaved identically. But, if you have code that converts DateRange or Index objects that used to contain datetime.datetime values to plain NumPy arrays, you may have bugs lurking with code using scalar values because you are handing control over to NumPy:

In [8]: import datetime

In [9]: rng = date_range('1/1/2000', periods=10)

In [10]: rng[5]
Timestamp('2000-01-06 00:00:00', tz=None)

In [11]: isinstance(rng[5], datetime.datetime)
True

In [12]: rng_asarray = np.asarray(rng)

In [13]: scalar_val = rng_asarray[5]

In [14]: type(scalar_val)
numpy.datetime64

pandas’s Timestamp object is a subclass of datetime.datetime that has nanosecond support (the nanosecond field store the nanosecond value between 0 and 999). It should substitute directly into any code that used datetime.datetime values before. Thus, I recommend not casting DatetimeIndex to regular NumPy arrays.

If you have code that requires an array of datetime.datetime objects, you have a couple of options. First, the asobject property of DatetimeIndex produces an array of Timestamp objects:

In [15]: stamp_array = rng.asobject

In [16]: stamp_array
Index([2000-01-01 00:00:00, 2000-01-02 00:00:00, 2000-01-03 00:00:00, 2000-01-04 00:00:00, 2000-01-05 00:00:00, 2000-01-06 00:00:00, 2000-01-07 00:00:00, 2000-01-08 00:00:00, 2000-01-09 00:00:00, 2000-01-10 00:00:00], dtype=object)

In [17]: stamp_array[5]
Timestamp('2000-01-06 00:00:00', tz=None)

To get an array of proper datetime.datetime objects, use the to_pydatetime method:

In [18]: dt_array = rng.to_pydatetime()

In [19]: dt_array

array([datetime.datetime(2000, 1, 1, 0, 0),
       datetime.datetime(2000, 1, 2, 0, 0),
       datetime.datetime(2000, 1, 3, 0, 0),
       datetime.datetime(2000, 1, 4, 0, 0),
       datetime.datetime(2000, 1, 5, 0, 0),
       datetime.datetime(2000, 1, 6, 0, 0),
       datetime.datetime(2000, 1, 7, 0, 0),
       datetime.datetime(2000, 1, 8, 0, 0),
       datetime.datetime(2000, 1, 9, 0, 0),
       datetime.datetime(2000, 1, 10, 0, 0)], dtype=object)

In [20]: dt_array[5]
datetime.datetime(2000, 1, 6, 0, 0)

matplotlib knows how to handle datetime.datetime but not Timestamp objects. While I recommend that you plot time series using TimeSeries.plot, you can either use to_pydatetime or register a converter for the Timestamp type. See matplotlib documentation for more on this.

Warning

There are bugs in the user-facing API with the nanosecond datetime64 unit in NumPy 1.6. In particular, the string version of the array shows garbage values, and conversion to dtype=object is similarly broken.

In [21]: rng = date_range('1/1/2000', periods=10)

In [22]: rng

<class 'pandas.tseries.index.DatetimeIndex'>
[2000-01-01 00:00:00, ..., 2000-01-10 00:00:00]
Length: 10, Freq: D, Timezone: None

In [23]: np.asarray(rng)

array(['2000-01-01T02:00:00.000000000+0200',
       '2000-01-02T02:00:00.000000000+0200',
       '2000-01-03T02:00:00.000000000+0200',
       '2000-01-04T02:00:00.000000000+0200',
       '2000-01-05T02:00:00.000000000+0200',
       '2000-01-06T02:00:00.000000000+0200',
       '2000-01-07T02:00:00.000000000+0200',
       '2000-01-08T02:00:00.000000000+0200',
       '2000-01-09T02:00:00.000000000+0200',
       '2000-01-10T02:00:00.000000000+0200'], dtype='datetime64[ns]')

In [24]: converted = np.asarray(rng, dtype=object)

In [25]: converted[5]
947116800000000000L

Trust me: don’t panic. If you are using NumPy 1.6 and restrict your interaction with datetime64 values to pandas’s API you will be just fine. There is nothing wrong with the data-type (a 64-bit integer internally); all of the important data processing happens in pandas and is heavily tested. I strongly recommend that you do not work directly with datetime64 arrays in NumPy 1.6 and only use the pandas API.

Support for non-unique indexes: In the latter case, you may have code inside a try:... catch: block that failed due to the index not being unique. In many cases it will no longer fail (some method like append still check for uniqueness unless disabled). However, all is not lost: you can inspect index.is_unique and raise an exception explicitly if it is False or go to a different code branch.

v.0.7.3 (April 12, 2012)

This is a minor release from 0.7.2 and fixes many minor bugs and adds a number of nice new features. There are also a couple of API changes to note; these should not affect very many users, and we are inclined to call them “bug fixes” even though they do constitute a change in behavior. See the full release notes or issue tracker on GitHub for a complete list.

New features

from pandas.tools.plotting import scatter_matrix
scatter_matrix(df, alpha=0.2)
_images/scatter_matrix_kde.png
  • Add stacked argument to Series and DataFrame’s plot method for stacked bar plots.
df.plot(kind='bar', stacked=True)
_images/bar_plot_stacked_ex.png
df.plot(kind='barh', stacked=True)
_images/barh_plot_stacked_ex.png
  • Add log x and y scaling options to DataFrame.plot and Series.plot
  • Add kurt methods to Series and DataFrame for computing kurtosis

NA Boolean Comparison API Change

Reverted some changes to how NA values (represented typically as NaN or None) are handled in non-numeric Series:

In [1]: series = Series(['Steve', np.nan, 'Joe'])

In [2]: series == 'Steve'

0     True
1    False
2    False
dtype: bool

In [3]: series != 'Steve'

0    False
1     True
2     True
dtype: bool

In comparisons, NA / NaN will always come through as False except with != which is True. Be very careful with boolean arithmetic, especially negation, in the presence of NA data. You may wish to add an explicit NA filter into boolean array operations if you are worried about this:

In [4]: mask = series == 'Steve'

In [5]: series[mask & series.notnull()]

0    Steve
dtype: object

While propagating NA in comparisons may seem like the right behavior to some users (and you could argue on purely technical grounds that this is the right thing to do), the evaluation was made that propagating NA everywhere, including in numerical arrays, would cause a large amount of problems for users. Thus, a “practicality beats purity” approach was taken. This issue may be revisited at some point in the future.

Other API Changes

When calling apply on a grouped Series, the return value will also be a Series, to be more consistent with the groupby behavior with DataFrame:

In [1]: df = DataFrame({'A' : ['foo', 'bar', 'foo', 'bar',
   ...:                     'foo', 'bar', 'foo', 'foo'],
   ...:                 'B' : ['one', 'one', 'two', 'three',
   ...:                        'two', 'two', 'one', 'three'],
   ...:                 'C' : np.random.randn(8), 'D' : np.random.randn(8)})
   ...: 

In [2]: df

     A      B         C         D
0  foo    one -0.528334 -0.230122
1  bar    one  0.382692 -0.431350
2  foo    two  0.169641 -0.810551
3  bar  three -0.607006 -0.325147
4  foo    two  1.616027  0.567872
5  bar    two  0.084365 -0.326051
6  foo    one -0.291657 -1.637628
7  foo  three  0.414315  0.398467

In [3]: grouped = df.groupby('A')['C']

In [4]: grouped.describe()

A         
bar  count    3.000000
     mean    -0.046650
     std      0.507690
     min     -0.607006
     25%     -0.261320
     50%      0.084365
     75%      0.233528
     max      0.382692
foo  count    5.000000
     mean     0.275998
     std      0.835958
     min     -0.528334
     25%     -0.291657
     50%      0.169641
     75%      0.414315
     max      1.616027
dtype: float64

In [5]: grouped.apply(lambda x: x.order()[-2:]) # top 2 values

A     
bar  5    0.084365
     1    0.382692
foo  7    0.414315
     4    1.616027
dtype: float64

v.0.7.2 (March 16, 2012)

This release targets bugs in 0.7.1, and adds a few minor features.

New features

  • Add additional tie-breaking methods in DataFrame.rank (GH874)
  • Add ascending parameter to rank in Series, DataFrame (GH875)
  • Add coerce_float option to DataFrame.from_records (GH893)
  • Add sort_columns parameter to allow unsorted plots (GH918)
  • Enable column access via attributes on GroupBy (GH882)
  • Can pass dict of values to DataFrame.fillna (GH661)
  • Can select multiple hierarchical groups by passing list of values in .ix (GH134)
  • Add axis option to DataFrame.fillna (GH174)
  • Add level keyword to drop for dropping values from a level (GH159)

Performance improvements

  • Use khash for Series.value_counts, add raw function to algorithms.py (GH861)
  • Intercept __builtin__.sum in groupby (GH885)

v.0.7.1 (February 29, 2012)

This release includes a few new features and addresses over a dozen bugs in 0.7.0.

New features

  • Add to_clipboard function to pandas namespace for writing objects to the system clipboard (GH774)
  • Add itertuples method to DataFrame for iterating through the rows of a dataframe as tuples (GH818)
  • Add ability to pass fill_value and method to DataFrame and Series align method (GH806, GH807)
  • Add fill_value option to reindex, align methods (GH784)
  • Enable concat to produce DataFrame from Series (GH787)
  • Add between method to Series (GH802)
  • Add HTML representation hook to DataFrame for the IPython HTML notebook (GH773)
  • Support for reading Excel 2007 XML documents using openpyxl

Performance improvements

  • Improve performance and memory usage of fillna on DataFrame
  • Can concatenate a list of Series along axis=1 to obtain a DataFrame (GH787)

v.0.7.0 (February 9, 2012)

New features

  • New unified merge function for efficiently performing full gamut of database / relational-algebra operations. Refactored existing join methods to use the new infrastructure, resulting in substantial performance gains (GH220, GH249, GH267)
  • New unified concatenation function for concatenating Series, DataFrame or Panel objects along an axis. Can form union or intersection of the other axes. Improves performance of Series.append and DataFrame.append (GH468, GH479, GH273)
  • Can pass multiple DataFrames to DataFrame.append to concatenate (stack) and multiple Series to Series.append too
  • Can pass list of dicts (e.g., a list of JSON objects) to DataFrame constructor (GH526)
  • You can now set multiple columns in a DataFrame via __getitem__, useful for transformation (GH342)
  • Handle differently-indexed output values in DataFrame.apply (GH498)
In [1]: df = DataFrame(randn(10, 4))

In [2]: df.apply(lambda x: x.describe())

               0          1          2          3
count  10.000000  10.000000  10.000000  10.000000
mean   -0.116419   0.299055  -0.079231   0.019777
std     0.813849   1.136189   1.241842   1.034550
min    -1.835734  -0.941538  -2.529494  -1.264087
25%    -0.413921  -0.466724  -0.720181  -0.673730
50%    -0.044290  -0.012975  -0.019968  -0.227942
75%     0.438453   0.967377   0.794089   0.724189
max     0.997926   2.766371   1.735816   2.085903
  • Add reorder_levels method to Series and DataFrame (GH534)
  • Add dict-like get function to DataFrame and Panel (GH521)
  • Add DataFrame.iterrows method for efficiently iterating through the rows of a DataFrame
  • Add DataFrame.to_panel with code adapted from LongPanel.to_long
  • Add reindex_axis method added to DataFrame
  • Add level option to binary arithmetic functions on DataFrame and Series
  • Add level option to the reindex and align methods on Series and DataFrame for broadcasting values across a level (GH542, GH552, others)
  • Add attribute-based item access to Panel and add IPython completion (GH563)
  • Add logy option to Series.plot for log-scaling on the Y axis
  • Add index and header options to DataFrame.to_string
  • Can pass multiple DataFrames to DataFrame.join to join on index (GH115)
  • Can pass multiple Panels to Panel.join (GH115)
  • Added justify argument to DataFrame.to_string to allow different alignment of column headers
  • Add sort option to GroupBy to allow disabling sorting of the group keys for potential speedups (GH595)
  • Can pass MaskedArray to Series constructor (GH563)
  • Add Panel item access via attributes and IPython completion (GH554)
  • Implement DataFrame.lookup, fancy-indexing analogue for retrieving values given a sequence of row and column labels (GH338)
  • Can pass a list of functions to aggregate with groupby on a DataFrame, yielding an aggregated result with hierarchical columns (GH166)
  • Can call cummin and cummax on Series and DataFrame to get cumulative minimum and maximum, respectively (GH647)
  • value_range added as utility function to get min and max of a dataframe (GH288)
  • Added encoding argument to read_csv, read_table, to_csv and from_csv for non-ascii text (GH717)
  • Added abs method to pandas objects
  • Added crosstab function for easily computing frequency tables
  • Added isin method to index objects
  • Added level argument to xs method of DataFrame.

API Changes to integer indexing

One of the potentially riskiest API changes in 0.7.0, but also one of the most important, was a complete review of how integer indexes are handled with regard to label-based indexing. Here is an example:

In [3]: s = Series(randn(10), index=range(0, 20, 2))

In [4]: s

0    -0.269317
2     1.147837
4     0.513990
6     1.016381
8     1.245311
10   -0.658915
12    0.191295
14   -1.334680
16    1.311125
18   -0.370756
dtype: float64

In [5]: s[0]
-0.26931724190559875

In [6]: s[2]
1.1478369253800751

In [7]: s[4]
0.51399026411689186

This is all exactly identical to the behavior before. However, if you ask for a key not contained in the Series, in versions 0.6.1 and prior, Series would fall back on a location-based lookup. This now raises a KeyError:

In [2]: s[1]
KeyError: 1

This change also has the same impact on DataFrame:

In [3]: df = DataFrame(randn(8, 4), index=range(0, 16, 2))

In [4]: df
    0        1       2       3
0   0.88427  0.3363 -0.1787  0.03162
2   0.14451 -0.1415  0.2504  0.58374
4  -1.44779 -0.9186 -1.4996  0.27163
6  -0.26598 -2.4184 -0.2658  0.11503
8  -0.58776  0.3144 -0.8566  0.61941
10  0.10940 -0.7175 -1.0108  0.47990
12 -1.16919 -0.3087 -0.6049 -0.43544
14 -0.07337  0.3410  0.0424 -0.16037

In [5]: df.ix[3]
KeyError: 3

In order to support purely integer-based indexing, the following methods have been added:

Method Description
Series.iget_value(i) Retrieve value stored at location i
Series.iget(i) Alias for iget_value
DataFrame.irow(i) Retrieve the i-th row
DataFrame.icol(j) Retrieve the j-th column
DataFrame.iget_value(i, j) Retrieve the value at row i and column j

API tweaks regarding label-based slicing

Label-based slicing using ix now requires that the index be sorted (monotonic) unless both the start and endpoint are contained in the index:

In [8]: s = Series(randn(6), index=list('gmkaec'))

In [9]: s

g    1.654410
m   -1.814873
k    0.110765
a    0.129211
e    0.639126
c    0.190511
dtype: float64

Then this is OK:

In [10]: s.ix['k':'e']

k    0.110765
a    0.129211
e    0.639126
dtype: float64

But this is not:

In [12]: s.ix['b':'h']
KeyError 'b'

If the index had been sorted, the “range selection” would have been possible:

In [11]: s2 = s.sort_index()

In [12]: s2

a    0.129211
c    0.190511
e    0.639126
g    1.654410
k    0.110765
m   -1.814873
dtype: float64

In [13]: s2.ix['b':'h']

c    0.190511
e    0.639126
g    1.654410
dtype: float64

Changes to Series [] operator

As as notational convenience, you can pass a sequence of labels or a label slice to a Series when getting and setting values via [] (i.e. the __getitem__ and __setitem__ methods). The behavior will be the same as passing similar input to ix except in the case of integer indexing:

In [14]: s = Series(randn(6), index=list('acegkm'))

In [15]: s

a   -0.788637
c    1.407538
e    1.151946
g    0.780799
k   -0.477058
m    2.171053
dtype: float64

In [16]: s[['m', 'a', 'c', 'e']]

m    2.171053
a   -0.788637
c    1.407538
e    1.151946
dtype: float64

In [17]: s['b':'l']

c    1.407538
e    1.151946
g    0.780799
k   -0.477058
dtype: float64

In [18]: s['c':'k']

c    1.407538
e    1.151946
g    0.780799
k   -0.477058
dtype: float64

In the case of integer indexes, the behavior will be exactly as before (shadowing ndarray):

In [19]: s = Series(randn(6), index=range(0, 12, 2))

In [20]: s[[4, 0, 2]]

4   -0.166226
0    1.529302
2    2.004196
dtype: float64

In [21]: s[1:5]

2    2.004196
4   -0.166226
6    1.163491
8   -0.170568
dtype: float64

If you wish to do indexing with sequences and slicing on an integer index with label semantics, use ix.

Other API Changes

  • The deprecated LongPanel class has been completely removed
  • If Series.sort is called on a column of a DataFrame, an exception will now be raised. Before it was possible to accidentally mutate a DataFrame’s column by doing df[col].sort() instead of the side-effect free method df[col].order() (GH316)
  • Miscellaneous renames and deprecations which will (harmlessly) raise FutureWarning
  • drop added as an optional parameter to DataFrame.reset_index (GH699)

Performance improvements

  • Cythonized GroupBy aggregations no longer presort the data, thus achieving a significant speedup (GH93). GroupBy aggregations with Python functions significantly sped up by clever manipulation of the ndarray data type in Cython (GH496).
  • Better error message in DataFrame constructor when passed column labels don’t match data (GH497)
  • Substantially improve performance of multi-GroupBy aggregation when a Python function is passed, reuse ndarray object in Cython (GH496)
  • Can store objects indexed by tuples and floats in HDFStore (GH492)
  • Don’t print length by default in Series.to_string, add length option (GH489)
  • Improve Cython code for multi-groupby to aggregate without having to sort the data (GH93)
  • Improve MultiIndex reindexing speed by storing tuples in the MultiIndex, test for backwards unpickling compatibility
  • Improve column reindexing performance by using specialized Cython take function
  • Further performance tweaking of Series.__getitem__ for standard use cases
  • Avoid Index dict creation in some cases (i.e. when getting slices, etc.), regression from prior versions
  • Friendlier error message in setup.py if NumPy not installed
  • Use common set of NA-handling operations (sum, mean, etc.) in Panel class also (GH536)
  • Default name assignment when calling reset_index on DataFrame with a regular (non-hierarchical) index (GH476)
  • Use Cythonized groupers when possible in Series/DataFrame stat ops with level parameter passed (GH545)
  • Ported skiplist data structure to C to speed up rolling_median by about 5-10x in most typical use cases (GH374)

v.0.6.1 (December 13, 2011)

New features

Performance improvements

  • Improve memory usage of DataFrame.describe (do not copy data unnecessarily) (PR #425)
  • Optimize scalar value lookups in the general case by 25% or more in Series and DataFrame
  • Fix performance regression in cross-sectional count in DataFrame, affecting DataFrame.dropna speed
  • Column deletion in DataFrame copies no data (computes views on blocks) (GH #158)

v.0.6.0 (November 25, 2011)

New Features

  • Added melt function to pandas.core.reshape
  • Added level parameter to group by level in Series and DataFrame descriptive statistics (GH313)
  • Added head and tail methods to Series, analogous to to DataFrame (GH296)
  • Added Series.isin function which checks if each value is contained in a passed sequence (GH289)
  • Added float_format option to Series.to_string
  • Added skip_footer (GH291) and converters (GH343) options to read_csv and read_table
  • Added drop_duplicates and duplicated functions for removing duplicate DataFrame rows and checking for duplicate rows, respectively (GH319)
  • Implemented operators ‘&’, ‘|’, ‘^’, ‘-‘ on DataFrame (GH347)
  • Added Series.mad, mean absolute deviation
  • Added QuarterEnd DateOffset (GH321)
  • Added dot to DataFrame (GH65)
  • Added orient option to Panel.from_dict (GH359, GH301)
  • Added orient option to DataFrame.from_dict
  • Added passing list of tuples or list of lists to DataFrame.from_records (GH357)
  • Added multiple levels to groupby (GH103)
  • Allow multiple columns in by argument of DataFrame.sort_index (GH92, GH362)
  • Added fast get_value and put_value methods to DataFrame (GH360)
  • Added cov instance methods to Series and DataFrame (GH194, GH362)
  • Added kind='bar' option to DataFrame.plot (GH348)
  • Added idxmin and idxmax to Series and DataFrame (GH286)
  • Added read_clipboard function to parse DataFrame from clipboard (GH300)
  • Added nunique function to Series for counting unique elements (GH297)
  • Made DataFrame constructor use Series name if no columns passed (GH373)
  • Support regular expressions in read_table/read_csv (GH364)
  • Added DataFrame.to_html for writing DataFrame to HTML (GH387)
  • Added support for MaskedArray data in DataFrame, masked values converted to NaN (GH396)
  • Added DataFrame.boxplot function (GH368)
  • Can pass extra args, kwds to DataFrame.apply (GH376)
  • Implement DataFrame.join with vector on argument (GH312)
  • Added legend boolean flag to DataFrame.plot (GH324)
  • Can pass multiple levels to stack and unstack (GH370)
  • Can pass multiple values columns to pivot_table (GH381)
  • Use Series name in GroupBy for result index (GH363)
  • Added raw option to DataFrame.apply for performance if only need ndarray (GH309)
  • Added proper, tested weighted least squares to standard and panel OLS (GH303)

Performance Enhancements

  • VBENCH Cythonized cache_readonly, resulting in substantial micro-performance enhancements throughout the codebase (GH361)
  • VBENCH Special Cython matrix iterator for applying arbitrary reduction operations with 3-5x better performance than np.apply_along_axis (GH309)
  • VBENCH Improved performance of MultiIndex.from_tuples
  • VBENCH Special Cython matrix iterator for applying arbitrary reduction operations
  • VBENCH + DOCUMENT Add raw option to DataFrame.apply for getting better performance when
  • VBENCH Faster cythonized count by level in Series and DataFrame (GH341)
  • VBENCH? Significant GroupBy performance enhancement with multiple keys with many “empty” combinations
  • VBENCH New Cython vectorized function map_infer speeds up Series.apply and Series.map significantly when passed elementwise Python function, motivated by (GH355)
  • VBENCH Significantly improved performance of Series.order, which also makes np.unique called on a Series faster (GH327)
  • VBENCH Vastly improved performance of GroupBy on axes with a MultiIndex (GH299)

v.0.5.0 (October 24, 2011)

New Features

  • Added DataFrame.align method with standard join options
  • Added parse_dates option to read_csv and read_table methods to optionally try to parse dates in the index columns
  • Added nrows, chunksize, and iterator arguments to read_csv and read_table. The last two return a new TextParser class capable of lazily iterating through chunks of a flat file (GH242)
  • Added ability to join on multiple columns in DataFrame.join (GH214)
  • Added private _get_duplicates function to Index for identifying duplicate values more easily (ENH5c)
  • Added column attribute access to DataFrame.
  • Added Python tab completion hook for DataFrame columns. (GH233, GH230)
  • Implemented Series.describe for Series containing objects (GH241)
  • Added inner join option to DataFrame.join when joining on key(s) (GH248)
  • Implemented selecting DataFrame columns by passing a list to __getitem__ (GH253)
  • Implemented & and | to intersect / union Index objects, respectively (GH261)
  • Added pivot_table convenience function to pandas namespace (GH234)
  • Implemented Panel.rename_axis function (GH243)
  • DataFrame will show index level names in console output (GH334)
  • Implemented Panel.take
  • Added set_eng_float_format for alternate DataFrame floating point string formatting (ENH61)
  • Added convenience set_index function for creating a DataFrame index from its existing columns
  • Implemented groupby hierarchical index level name (GH223)
  • Added support for different delimiters in DataFrame.to_csv (GH244)
  • TODO: DOCS ABOUT TAKE METHODS

Performance Enhancements

  • VBENCH Major performance improvements in file parsing functions read_csv and read_table
  • VBENCH Added Cython function for converting tuples to ndarray very fast. Speeds up many MultiIndex-related operations
  • VBENCH Refactored merging / joining code into a tidy class and disabled unnecessary computations in the float/object case, thus getting about 10% better performance (GH211)
  • VBENCH Improved speed of DataFrame.xs on mixed-type DataFrame objects by about 5x, regression from 0.3.0 (GH215)
  • VBENCH With new DataFrame.align method, speeding up binary operations between differently-indexed DataFrame objects by 10-25%.
  • VBENCH Significantly sped up conversion of nested dict into DataFrame (GH212)
  • VBENCH Significantly speed up DataFrame __repr__ and count on large mixed-type DataFrame objects

v.0.4.3 through v0.4.1 (September 25 - October 9, 2011)

New Features

  • Added Python 3 support using 2to3 (GH200)
  • Added name attribute to Series, now prints as part of Series.__repr__
  • Added instance methods isnull and notnull to Series (GH209, GH203)
  • Added Series.align method for aligning two series with choice of join method (ENH56)
  • Added method get_level_values to MultiIndex (GH188)
  • Set values in mixed-type DataFrame objects via .ix indexing attribute (GH135)
  • Added new DataFrame methods get_dtype_counts and property dtypes (ENHdc)
  • Added ignore_index option to DataFrame.append to stack DataFrames (ENH1b)
  • read_csv tries to sniff delimiters using csv.Sniffer (GH146)
  • read_csv can read multiple columns into a MultiIndex; DataFrame’s to_csv method writes out a corresponding MultiIndex (GH151)
  • DataFrame.rename has a new copy parameter to rename a DataFrame in place (ENHed)
  • Enable unstacking by name (GH142)
  • Enable sortlevel to work by level (GH141)

Performance Enhancements

  • Altered binary operations on differently-indexed SparseSeries objects to use the integer-based (dense) alignment logic which is faster with a larger number of blocks (GH205)
  • Wrote faster Cython data alignment / merging routines resulting in substantial speed increases
  • Improved performance of isnull and notnull, a regression from v0.3.0 (GH187)
  • Refactored code related to DataFrame.join so that intermediate aligned copies of the data in each DataFrame argument do not need to be created. Substantial performance increases result (GH176)
  • Substantially improved performance of generic Index.intersection and Index.union
  • Implemented BlockManager.take resulting in significantly faster take performance on mixed-type DataFrame objects (GH104)
  • Improved performance of Series.sort_index
  • Significant groupby performance enhancement: removed unnecessary integrity checks in DataFrame internals that were slowing down slicing operations to retrieve groups
  • Optimized _ensure_index function resulting in performance savings in type-checking Index objects
  • Wrote fast time series merging / joining methods in Cython. Will be integrated later into DataFrame.join and related functions