pandas 0.10.0 documentation

IO Tools (Text, CSV, HDF5, ...)

CSV & Text files

The two workhorse functions for reading text files (a.k.a. flat files) are read_csv() and read_table(). They both use the same parsing code to intelligently convert tabular data into a DataFrame object. They can take a number of arguments:

  • filepath_or_buffer: Either a string path to a file, or any object with a read method (such as an open file or StringIO).
  • sep or delimiter: A delimiter / separator to split fields on. read_csv is capable of inferring the delimiter automatically in some cases by “sniffing.” The separator may be specified as a regular expression; for instance you may use ‘|s*’ to indicate a pipe plus arbitrary whitespace.
  • delim_whitespace: Parse whitespace-delimited (spaces or tabs) file (much faster than using a regular expression)
  • compression: decompress 'gzip' and 'bz2' formats on the fly.
  • dialect: string or csv.Dialect instance to expose more ways to specify the file format
  • dtype: A data type name or a dict of column name to data type. If not specified, data types will be inferred.
  • header: row number to use as the column names, and the start of the data. Defaults to 0 if no names passed, otherwise None. Explicitly pass header=0 to be able to replace existing names.
  • skiprows: A collection of numbers for rows in the file to skip. Can also be an integer to skip the first n rows
  • index_col: column number, column name, or list of column numbers/names, to use as the index (row labels) of the resulting DataFrame. By default, it will number the rows without using any column, unless there is one more data column than there are headers, in which case the first column is taken as the index.
  • names: List of column names to use as column names. To replace header existing in file, explicitly pass header=0.
  • na_values: optional list of strings to recognize as NaN (missing values), either in addition to or in lieu of the default set.
  • true_values: list of strings to recognize as True
  • false_values: list of strings to recognize as False
  • keep_default_na: whether to include the default set of missing values in addition to the ones specified in na_values
  • parse_dates: if True then index will be parsed as dates (False by default). You can specify more complicated options to parse a subset of columns or a combination of columns into a single date column (list of ints or names, list of lists, or dict) [1, 2, 3] -> try parsing columns 1, 2, 3 each as a separate date column [[1, 3]] -> combine columns 1 and 3 and parse as a single date column {‘foo’ : [1, 3]} -> parse columns 1, 3 as date and call result ‘foo’
  • keep_date_col: if True, then date component columns passed into parse_dates will be retained in the output (False by default).
  • date_parser: function to use to parse strings into datetime objects. If parse_dates is True, it defaults to the very robust dateutil.parser. Specifying this implicitly sets parse_dates as True. You can also use functions from community supported date converters from date_converters.py
  • dayfirst: if True then uses the DD/MM international/European date format (This is False by default)
  • thousands: sepcifies the thousands separator. If not None, then parser will try to look for it in the output and parse relevant data to integers. Because it has to essentially scan through the data again, this causes a significant performance hit so only use if necessary.
  • comment: denotes the start of a comment and ignores the rest of the line. Currently line commenting is not supported.
  • nrows: Number of rows to read out of the file. Useful to only read a small portion of a large file
  • iterator: If True, return a TextParser to enable reading a file into memory piece by piece
  • chunksize: An number of rows to be used to “chunk” a file into pieces. Will cause an TextParser object to be returned. More on this below in the section on iterating and chunking
  • skip_footer: number of lines to skip at bottom of file (default 0)
  • converters: a dictionary of functions for converting values in certain columns, where keys are either integers or column labels
  • encoding: a string representing the encoding to use for decoding unicode data, e.g. 'utf-8` or 'latin-1'.
  • verbose: show number of NA values inserted in non-numeric columns
  • squeeze: if True then output with only one column is turned into Series

Consider a typical CSV file containing, in this case, some time series data:

In [830]: print open('foo.csv').read()
date,A,B,C
20090101,a,1,2
20090102,b,3,4
20090103,c,4,5

The default for read_csv is to create a DataFrame with simple numbered rows:

In [831]: pd.read_csv('foo.csv')
Out[831]: 
       date  A  B  C
0  20090101  a  1  2
1  20090102  b  3  4
2  20090103  c  4  5

In the case of indexed data, you can pass the column number or column name you wish to use as the index:

In [832]: pd.read_csv('foo.csv', index_col=0)
Out[832]: 
          A  B  C
date             
20090101  a  1  2
20090102  b  3  4
20090103  c  4  5
In [833]: pd.read_csv('foo.csv', index_col='date')
Out[833]: 
          A  B  C
date             
20090101  a  1  2
20090102  b  3  4
20090103  c  4  5

You can also use a list of columns to create a hierarchical index:

In [834]: pd.read_csv('foo.csv', index_col=[0, 'A'])
Out[834]: 
            B  C
date     A      
20090101 a  1  2
20090102 b  3  4
20090103 c  4  5

The dialect keyword gives greater flexibility in specifying the file format. By default it uses the Excel dialect but you can specify either the dialect name or a csv.Dialect instance.

Suppose you had data with unenclosed quotes:

In [835]: print data
label1,label2,label3
index1,"a,c,e
index2,b,d,f

By default, read_csv uses the Excel dialect and treats the double quote as the quote character, which causes it to fail when it finds a newline before it finds the closing double quote.

We can get around this using dialect

In [836]: dia = csv.excel()

In [837]: dia.quoting = csv.QUOTE_NONE

In [838]: pd.read_csv(StringIO(data), dialect=dia)
Out[838]: 
       label1 label2 label3
index1     "a      c      e
index2      b      d      f

All of the dialect options can be specified separately by keyword arguments:

In [839]: data = 'a,b,c~1,2,3~4,5,6'

In [840]: pd.read_csv(StringIO(data), lineterminator='~')
Out[840]: 
   a  b  c
0  1  2  3
1  4  5  6

Another common dialect option is skipinitialspace, to skip any whitespace after a delimiter:

In [841]: data = 'a, b, c\n1, 2, 3\n4, 5, 6'

In [842]: print data
a, b, c
1, 2, 3
4, 5, 6

In [843]: pd.read_csv(StringIO(data), skipinitialspace=True)
Out[843]: 
   a  b  c
0  1  2  3
1  4  5  6

The parsers make every attempt to “do the right thing” and not be very fragile. Type inference is a pretty big deal. So if a column can be coerced to integer dtype without altering the contents, it will do so. Any non-numeric columns will come through as object dtype as with the rest of pandas objects.

Specifying column data types

Starting with v0.10, you can indicate the data type for the whole DataFrame or individual columns:

In [844]: data = 'a,b,c\n1,2,3\n4,5,6\n7,8,9'

In [845]: print data
a,b,c
1,2,3
4,5,6
7,8,9

In [846]: df = pd.read_csv(StringIO(data), dtype=object)

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

In [848]: df['a'][0]
Out[848]: '1'

In [849]: df = pd.read_csv(StringIO(data), dtype={'b': object, 'c': np.float64})

In [850]: df.dtypes
Out[850]: 
a      int64
b     object
c    float64

Handling column names

A file may or may not have a header row. pandas assumes the first row should be used as the column names:

In [851]: from StringIO import StringIO

In [852]: data = 'a,b,c\n1,2,3\n4,5,6\n7,8,9'

In [853]: print data
a,b,c
1,2,3
4,5,6
7,8,9

In [854]: pd.read_csv(StringIO(data))
Out[854]: 
   a  b  c
0  1  2  3
1  4  5  6
2  7  8  9

By specifying the names argument in conjunction with header you can indicate other names to use and whether or not to throw away the header row (if any):

In [855]: print data
a,b,c
1,2,3
4,5,6
7,8,9

In [856]: pd.read_csv(StringIO(data), names=['foo', 'bar', 'baz'], header=0)
Out[856]: 
   foo  bar  baz
0    1    2    3
1    4    5    6
2    7    8    9

In [857]: pd.read_csv(StringIO(data), names=['foo', 'bar', 'baz'], header=None)
Out[857]: 
  foo bar baz
0   a   b   c
1   1   2   3
2   4   5   6
3   7   8   9

If the header is in a row other than the first, pass the row number to header. This will skip the preceding rows:

In [858]: data = 'skip this skip it\na,b,c\n1,2,3\n4,5,6\n7,8,9'

In [859]: pd.read_csv(StringIO(data), header=1)
Out[859]: 
   a  b  c
0  1  2  3
1  4  5  6
2  7  8  9

Filtering columns (usecols)

The usecols argument allows you to select any subset of the columns in a file, either using the column names or position numbers:

In [860]: data = 'a,b,c,d\n1,2,3,foo\n4,5,6,bar\n7,8,9,baz'

In [861]: pd.read_csv(StringIO(data))
Out[861]: 
   a  b  c    d
0  1  2  3  foo
1  4  5  6  bar
2  7  8  9  baz

In [862]: pd.read_csv(StringIO(data), usecols=['b', 'd'])
Out[862]: 
   b    d
0  2  foo
1  5  bar
2  8  baz

In [863]: pd.read_csv(StringIO(data), usecols=[0, 2, 3])
Out[863]: 
   a  c    d
0  1  3  foo
1  4  6  bar
2  7  9  baz

Dealing with Unicode Data

The encoding argument should be used for encoded unicode data, which will result in byte strings being decoded to unicode in the result:

In [864]: data = 'word,length\nTr\xe4umen,7\nGr\xfc\xdfe,5'

In [865]: df = pd.read_csv(StringIO(data), encoding='latin-1')

In [866]: df
Out[866]: 
      word  length
0  Träumen       7
1    Grüße       5

In [867]: df['word'][1]
Out[867]: u'Gr\xfc\xdfe'

Some formats which encode all characters as multiple bytes, like UTF-16, won’t parse correctly at all without specifying the encoding.

Index columns and trailing delimiters

If a file has one more column of data than the number of column names, the first column will be used as the DataFrame’s row names:

In [868]: data = 'a,b,c\n4,apple,bat,5.7\n8,orange,cow,10'

In [869]: pd.read_csv(StringIO(data))
Out[869]: 
        a    b     c
4   apple  bat   5.7
8  orange  cow  10.0
In [870]: data = 'index,a,b,c\n4,apple,bat,5.7\n8,orange,cow,10'

In [871]: pd.read_csv(StringIO(data), index_col=0)
Out[871]: 
            a    b     c
index                   
4       apple  bat   5.7
8      orange  cow  10.0

Ordinarily, you can achieve this behavior using the index_col option.

There are some exception cases when a file has been prepared with delimiters at the end of each data line, confusing the parser. To explicitly disable the index column inference and discard the last column, pass index_col=False:

In [872]: data = 'a,b,c\n4,apple,bat,\n8,orange,cow,'

In [873]: print data
a,b,c
4,apple,bat,
8,orange,cow,

In [874]: pd.read_csv(StringIO(data))
Out[874]: 
        a    b   c
4   apple  bat NaN
8  orange  cow NaN

In [875]: pd.read_csv(StringIO(data), index_col=False)
Out[875]: 
   a       b    c
0  4   apple  bat
1  8  orange  cow

Specifying Date Columns

To better facilitate working with datetime data, read_csv() and read_table() uses the keyword arguments parse_dates and date_parser to allow users to specify a variety of columns and date/time formats to turn the input text data into datetime objects.

The simplest case is to just pass in parse_dates=True:

# Use a column as an index, and parse it as dates.
In [876]: df = pd.read_csv('foo.csv', index_col=0, parse_dates=True)

In [877]: df
Out[877]: 
            A  B  C
date               
2009-01-01  a  1  2
2009-01-02  b  3  4
2009-01-03  c  4  5

# These are python datetime objects
In [878]: df.index
Out[878]: 
<class 'pandas.tseries.index.DatetimeIndex'>
[2009-01-01 00:00:00, ..., 2009-01-03 00:00:00]
Length: 3, Freq: None, Timezone: None

It is often the case that we may want to store date and time data separately, or store various date fields separately. the parse_dates keyword can be used to specify a combination of columns to parse the dates and/or times from.

You can specify a list of column lists to parse_dates, the resulting date columns will be prepended to the output (so as to not affect the existing column order) and the new column names will be the concatenation of the component column names:

In [879]: print open('tmp.csv').read()
KORD,19990127, 19:00:00, 18:56:00, 0.8100
KORD,19990127, 20:00:00, 19:56:00, 0.0100
KORD,19990127, 21:00:00, 20:56:00, -0.5900
KORD,19990127, 21:00:00, 21:18:00, -0.9900
KORD,19990127, 22:00:00, 21:56:00, -0.5900
KORD,19990127, 23:00:00, 22:56:00, -0.5900

In [880]: df = pd.read_csv('tmp.csv', header=None, parse_dates=[[1, 2], [1, 3]])

In [881]: df
Out[881]: 
                   1_2                  1_3     0     4
0  1999-01-27 19:00:00  1999-01-27 18:56:00  KORD  0.81
1  1999-01-27 20:00:00  1999-01-27 19:56:00  KORD  0.01
2  1999-01-27 21:00:00  1999-01-27 20:56:00  KORD -0.59
3  1999-01-27 21:00:00  1999-01-27 21:18:00  KORD -0.99
4  1999-01-27 22:00:00  1999-01-27 21:56:00  KORD -0.59
5  1999-01-27 23:00:00  1999-01-27 22:56:00  KORD -0.59

By default the parser removes the component date columns, but you can choose to retain them via the keep_date_col keyword:

In [882]: df = pd.read_csv('tmp.csv', header=None, parse_dates=[[1, 2], [1, 3]],
   .....:                  keep_date_col=True)
   .....:

In [883]: df
Out[883]: 
                   1_2                  1_3     0         1          2          3  \
0  1999-01-27 19:00:00  1999-01-27 18:56:00  KORD  19990127   19:00:00   18:56:00   
1  1999-01-27 20:00:00  1999-01-27 19:56:00  KORD  19990127   20:00:00   19:56:00   
2  1999-01-27 21:00:00  1999-01-27 20:56:00  KORD  19990127   21:00:00   20:56:00   
3  1999-01-27 21:00:00  1999-01-27 21:18:00  KORD  19990127   21:00:00   21:18:00   
4  1999-01-27 22:00:00  1999-01-27 21:56:00  KORD  19990127   22:00:00   21:56:00   
5  1999-01-27 23:00:00  1999-01-27 22:56:00  KORD  19990127   23:00:00   22:56:00   
      4  
0  0.81  
1  0.01  
2 -0.59  
3 -0.99  
4 -0.59  
5 -0.59  

Note that if you wish to combine multiple columns into a single date column, a nested list must be used. In other words, parse_dates=[1, 2] indicates that the second and third columns should each be parsed as separate date columns while parse_dates=[[1, 2]] means the two columns should be parsed into a single column.

You can also use a dict to specify custom name columns:

In [884]: date_spec = {'nominal': [1, 2], 'actual': [1, 3]}

In [885]: df = pd.read_csv('tmp.csv', header=None, parse_dates=date_spec)

In [886]: df
Out[886]: 
               nominal               actual     0     4
0  1999-01-27 19:00:00  1999-01-27 18:56:00  KORD  0.81
1  1999-01-27 20:00:00  1999-01-27 19:56:00  KORD  0.01
2  1999-01-27 21:00:00  1999-01-27 20:56:00  KORD -0.59
3  1999-01-27 21:00:00  1999-01-27 21:18:00  KORD -0.99
4  1999-01-27 22:00:00  1999-01-27 21:56:00  KORD -0.59
5  1999-01-27 23:00:00  1999-01-27 22:56:00  KORD -0.59

It is important to remember that if multiple text columns are to be parsed into a single date column, then a new column is prepended to the data. The index_col specification is based off of this new set of columns rather than the original data columns:

In [887]: date_spec = {'nominal': [1, 2], 'actual': [1, 3]}

In [888]: df = pd.read_csv('tmp.csv', header=None, parse_dates=date_spec,
   .....:                  index_col=0) #index is the nominal column
   .....:

In [889]: df
Out[889]: 
                                  actual     0     4
nominal                                             
1999-01-27 19:00:00  1999-01-27 18:56:00  KORD  0.81
1999-01-27 20:00:00  1999-01-27 19:56:00  KORD  0.01
1999-01-27 21:00:00  1999-01-27 20:56:00  KORD -0.59
1999-01-27 21:00:00  1999-01-27 21:18:00  KORD -0.99
1999-01-27 22:00:00  1999-01-27 21:56:00  KORD -0.59
1999-01-27 23:00:00  1999-01-27 22:56:00  KORD -0.59

Note: When passing a dict as the parse_dates argument, the order of the columns prepended is not guaranteed, because dict objects do not impose an ordering on their keys. On Python 2.7+ you may use collections.OrderedDict instead of a regular dict if this matters to you. Because of this, when using a dict for ‘parse_dates’ in conjunction with the index_col argument, it’s best to specify index_col as a column label rather then as an index on the resulting frame.

Date Parsing Functions

Finally, the parser allows you can specify a custom date_parser function to take full advantage of the flexiblity of the date parsing API:

In [890]: import pandas.io.date_converters as conv

In [891]: df = pd.read_csv('tmp.csv', header=None, parse_dates=date_spec,
   .....:                  date_parser=conv.parse_date_time)
   .....:

In [892]: df
Out[892]: 
               nominal               actual     0     4
0  1999-01-27 19:00:00  1999-01-27 18:56:00  KORD  0.81
1  1999-01-27 20:00:00  1999-01-27 19:56:00  KORD  0.01
2  1999-01-27 21:00:00  1999-01-27 20:56:00  KORD -0.59
3  1999-01-27 21:00:00  1999-01-27 21:18:00  KORD -0.99
4  1999-01-27 22:00:00  1999-01-27 21:56:00  KORD -0.59
5  1999-01-27 23:00:00  1999-01-27 22:56:00  KORD -0.59

You can explore the date parsing functionality in date_converters.py and add your own. We would love to turn this module into a community supported set of date/time parsers. To get you started, date_converters.py contains functions to parse dual date and time columns, year/month/day columns, and year/month/day/hour/minute/second columns. It also contains a generic_parser function so you can curry it with a function that deals with a single date rather than the entire array.

International Date Formats

While US date formats tend to be MM/DD/YYYY, many international formats use DD/MM/YYYY instead. For convenience, a dayfirst keyword is provided:

In [893]: print open('tmp.csv').read()
date,value,cat
1/6/2000,5,a
2/6/2000,10,b
3/6/2000,15,c

In [894]: pd.read_csv('tmp.csv', parse_dates=[0])
Out[894]: 
                  date  value cat
0  2000-01-06 00:00:00      5   a
1  2000-02-06 00:00:00     10   b
2  2000-03-06 00:00:00     15   c

In [895]: pd.read_csv('tmp.csv', dayfirst=True, parse_dates=[0])
Out[895]: 
                  date  value cat
0  2000-06-01 00:00:00      5   a
1  2000-06-02 00:00:00     10   b
2  2000-06-03 00:00:00     15   c

Thousand Separators

For large integers that have been written with a thousands separator, you can set the thousands keyword to True so that integers will be parsed correctly:

By default, integers with a thousands separator will be parsed as strings

In [896]: print open('tmp.csv').read()
ID|level|category
Patient1|123,000|x
Patient2|23,000|y
Patient3|1,234,018|z

In [897]: df = pd.read_csv('tmp.csv', sep='|')

In [898]: df
Out[898]: 
         ID      level category
0  Patient1    123,000        x
1  Patient2     23,000        y
2  Patient3  1,234,018        z

In [899]: df.level.dtype
Out[899]: dtype('object')

The thousands keyword allows integers to be parsed correctly

In [900]: print open('tmp.csv').read()
ID|level|category
Patient1|123,000|x
Patient2|23,000|y
Patient3|1,234,018|z

In [901]: df = pd.read_csv('tmp.csv', sep='|', thousands=',')

In [902]: df
Out[902]: 
         ID    level category
0  Patient1   123000        x
1  Patient2    23000        y
2  Patient3  1234018        z

In [903]: df.level.dtype
Out[903]: dtype('int64')

Comments

Sometimes comments or meta data may be included in a file:

In [904]: print open('tmp.csv').read()
ID,level,category
Patient1,123000,x # really unpleasant
Patient2,23000,y # wouldn't take his medicine
Patient3,1234018,z # awesome

By default, the parse includes the comments in the output:

In [905]: df = pd.read_csv('tmp.csv')

In [906]: df
Out[906]: 
         ID    level                        category
0  Patient1   123000           x # really unpleasant
1  Patient2    23000  y # wouldn't take his medicine
2  Patient3  1234018                     z # awesome

We can suppress the comments using the comment keyword:

In [907]: df = pd.read_csv('tmp.csv', comment='#')

In [908]: df
Out[908]: 
         ID    level category
0  Patient1   123000       x 
1  Patient2    23000       y 
2  Patient3  1234018       z 

Returning Series

Using the squeeze keyword, the parser will return output with a single column as a Series:

In [909]: print open('tmp.csv').read()
level
Patient1,123000
Patient2,23000
Patient3,1234018

In [910]: output =  pd.read_csv('tmp.csv', squeeze=True)

In [911]: output
Out[911]: 
Patient1     123000
Patient2      23000
Patient3    1234018
Name: level

In [912]: type(output)
Out[912]: pandas.core.series.Series

Boolean values

The common values True, False, TRUE, and FALSE are all recognized as boolean. Sometime you would want to recognize some other values as being boolean. To do this use the true_values and false_values options:

In [913]: data= 'a,b,c\n1,Yes,2\n3,No,4'

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

In [915]: pd.read_csv(StringIO(data))
Out[915]: 
   a    b  c
0  1  Yes  2
1  3   No  4

In [916]: pd.read_csv(StringIO(data), true_values=['Yes'], false_values=['No'])
Out[916]: 
   a      b  c
0  1   True  2
1  3  False  4

Handling “bad” lines

Some files may have malformed lines with too few fields or too many. Lines with too few fields will have NA values filled in the trailing fields. Lines with too many will cause an error by default:

In [27]: data = 'a,b,c\n1,2,3\n4,5,6,7\n8,9,10'

In [28]: pd.read_csv(StringIO(data))
---------------------------------------------------------------------------
CParserError                              Traceback (most recent call last)
CParserError: Error tokenizing data. C error: Expected 3 fields in line 3, saw 4

You can elect to skip bad lines:

In [29]: pd.read_csv(StringIO(data), error_bad_lines=False)
Skipping line 3: expected 3 fields, saw 4

Out[29]:
   a  b   c
0  1  2   3
1  8  9  10

Quoting and Escape Characters

Quotes (and other escape characters) in embedded fields can be handled in any number of ways. One way is to use backslashes; to properly parse this data, you should pass the escapechar option:

In [917]: data = 'a,b\n"hello, \\"Bob\\", nice to see you",5'

In [918]: print data
a,b
"hello, \"Bob\", nice to see you",5

In [919]: pd.read_csv(StringIO(data), escapechar='\\')
Out[919]: 
                               a  b
0  hello, "Bob", nice to see you  5

Files with Fixed Width Columns

While read_csv reads delimited data, the read_fwf() function works with data files that have known and fixed column widths. The function parameters to read_fwf are largely the same as read_csv with two extra parameters:

  • colspecs: a list of pairs (tuples), giving the extents of the fixed-width fields of each line as half-open intervals [from, to[
  • widths: a list of field widths, which can be used instead of colspecs if the intervals are contiguous

Consider a typical fixed-width data file:

In [920]: print open('bar.csv').read()
id8141    360.242940   149.910199   11950.7
id1594    444.953632   166.985655   11788.4
id1849    364.136849   183.628767   11806.2
id1230    413.836124   184.375703   11916.8
id1948    502.953953   173.237159   12468.3

In order to parse this file into a DataFrame, we simply need to supply the column specifications to the read_fwf function along with the file name:

#Column specifications are a list of half-intervals
In [921]: colspecs = [(0, 6), (8, 20), (21, 33), (34, 43)]

In [922]: df = pd.read_fwf('bar.csv', colspecs=colspecs, header=None, index_col=0)

In [923]: df
Out[923]: 
                 1           2        3
0                                      
id8141  360.242940  149.910199  11950.7
id1594  444.953632  166.985655  11788.4
id1849  364.136849  183.628767  11806.2
id1230  413.836124  184.375703  11916.8
id1948  502.953953  173.237159  12468.3

Note how the parser automatically picks column names X.<column number> when header=None argument is specified. Alternatively, you can supply just the column widths for contiguous columns:

#Widths are a list of integers
In [924]: widths = [6, 14, 13, 10]

In [925]: df = pd.read_fwf('bar.csv', widths=widths, header=None)

In [926]: df
Out[926]: 
        0           1           2        3
0  id8141  360.242940  149.910199  11950.7
1  id1594  444.953632  166.985655  11788.4
2  id1849  364.136849  183.628767  11806.2
3  id1230  413.836124  184.375703  11916.8
4  id1948  502.953953  173.237159  12468.3

The parser will take care of extra white spaces around the columns so it’s ok to have extra separation between the columns in the file.

Files with an “implicit” index column

Consider a file with one less entry in the header than the number of data column:

In [927]: print open('foo.csv').read()
A,B,C
20090101,a,1,2
20090102,b,3,4
20090103,c,4,5

In this special case, read_csv assumes that the first column is to be used as the index of the DataFrame:

In [928]: pd.read_csv('foo.csv')
Out[928]: 
          A  B  C
20090101  a  1  2
20090102  b  3  4
20090103  c  4  5

Note that the dates weren’t automatically parsed. In that case you would need to do as before:

In [929]: df = pd.read_csv('foo.csv', parse_dates=True)

In [930]: df.index
Out[930]: 
<class 'pandas.tseries.index.DatetimeIndex'>
[2009-01-01 00:00:00, ..., 2009-01-03 00:00:00]
Length: 3, Freq: None, Timezone: None

Reading DataFrame objects with MultiIndex

Suppose you have data indexed by two columns:

In [931]: print open('data/mindex_ex.csv').read()
year,indiv,zit,xit
1977,"A",1.2,.6
1977,"B",1.5,.5
1977,"C",1.7,.8
1978,"A",.2,.06
1978,"B",.7,.2
1978,"C",.8,.3
1978,"D",.9,.5
1978,"E",1.4,.9
1979,"C",.2,.15
1979,"D",.14,.05
1979,"E",.5,.15
1979,"F",1.2,.5
1979,"G",3.4,1.9
1979,"H",5.4,2.7
1979,"I",6.4,1.2

The index_col argument to read_csv and read_table can take a list of column numbers to turn multiple columns into a MultiIndex:

In [932]: df = pd.read_csv("data/mindex_ex.csv", index_col=[0,1])

In [933]: df
Out[933]: 
             zit   xit
year indiv            
1977 A      1.20  0.60
     B      1.50  0.50
     C      1.70  0.80
1978 A      0.20  0.06
     B      0.70  0.20
     C      0.80  0.30
     D      0.90  0.50
     E      1.40  0.90
1979 C      0.20  0.15
     D      0.14  0.05
     E      0.50  0.15
     F      1.20  0.50
     G      3.40  1.90
     H      5.40  2.70
     I      6.40  1.20

In [934]: df.ix[1978]
Out[934]: 
       zit   xit
indiv           
A      0.2  0.06
B      0.7  0.20
C      0.8  0.30
D      0.9  0.50
E      1.4  0.90

Automatically “sniffing” the delimiter

read_csv is capable of inferring delimited (not necessarily comma-separated) files. YMMV, as pandas uses the csv.Sniffer class of the csv module.

In [935]: print open('tmp2.sv').read()
:0:1:2:3
0:0.469112299907:-0.282863344329:-1.50905850317:-1.13563237102
1:1.21211202502:-0.173214649053:0.119208711297:-1.04423596628
2:-0.861848963348:-2.10456921889:-0.494929274069:1.07180380704
3:0.721555162244:-0.70677113363:-1.03957498511:0.271859885543
4:-0.424972329789:0.567020349794:0.276232019278:-1.08740069129
5:-0.673689708088:0.113648409689:-1.47842655244:0.524987667115
6:0.40470521868:0.57704598592:-1.71500201611:-1.03926848351
7:-0.370646858236:-1.15789225064:-1.34431181273:0.844885141425
8:1.07576978372:-0.10904997528:1.64356307036:-1.46938795954
9:0.357020564133:-0.67460010373:-1.77690371697:-0.968913812447

In [936]: pd.read_csv('tmp2.sv')
Out[936]: 
                                            :0:1:2:3
0  0:0.469112299907:-0.282863344329:-1.5090585031...
1  1:1.21211202502:-0.173214649053:0.119208711297...
2  2:-0.861848963348:-2.10456921889:-0.4949292740...
3  3:0.721555162244:-0.70677113363:-1.03957498511...
4  4:-0.424972329789:0.567020349794:0.27623201927...
5  5:-0.673689708088:0.113648409689:-1.4784265524...
6  6:0.40470521868:0.57704598592:-1.71500201611:-...
7  7:-0.370646858236:-1.15789225064:-1.3443118127...
8  8:1.07576978372:-0.10904997528:1.64356307036:-...
9  9:0.357020564133:-0.67460010373:-1.77690371697...

Iterating through files chunk by chunk

Suppose you wish to iterate through a (potentially very large) file lazily rather than reading the entire file into memory, such as the following:

In [937]: print open('tmp.sv').read()
|0|1|2|3
0|0.469112299907|-0.282863344329|-1.50905850317|-1.13563237102
1|1.21211202502|-0.173214649053|0.119208711297|-1.04423596628
2|-0.861848963348|-2.10456921889|-0.494929274069|1.07180380704
3|0.721555162244|-0.70677113363|-1.03957498511|0.271859885543
4|-0.424972329789|0.567020349794|0.276232019278|-1.08740069129
5|-0.673689708088|0.113648409689|-1.47842655244|0.524987667115
6|0.40470521868|0.57704598592|-1.71500201611|-1.03926848351
7|-0.370646858236|-1.15789225064|-1.34431181273|0.844885141425
8|1.07576978372|-0.10904997528|1.64356307036|-1.46938795954
9|0.357020564133|-0.67460010373|-1.77690371697|-0.968913812447

In [938]: table = pd.read_table('tmp.sv', sep='|')

In [939]: table
Out[939]: 
   Unnamed: 0         0         1         2         3
0           0  0.469112 -0.282863 -1.509059 -1.135632
1           1  1.212112 -0.173215  0.119209 -1.044236
2           2 -0.861849 -2.104569 -0.494929  1.071804
3           3  0.721555 -0.706771 -1.039575  0.271860
4           4 -0.424972  0.567020  0.276232 -1.087401
5           5 -0.673690  0.113648 -1.478427  0.524988
6           6  0.404705  0.577046 -1.715002 -1.039268
7           7 -0.370647 -1.157892 -1.344312  0.844885
8           8  1.075770 -0.109050  1.643563 -1.469388
9           9  0.357021 -0.674600 -1.776904 -0.968914

By specifiying a chunksize to read_csv or read_table, the return value will be an iterable object of type TextParser:

In [940]: reader = pd.read_table('tmp.sv', sep='|', chunksize=4)

In [941]: reader
Out[941]: <pandas.io.parsers.TextFileReader at 0xb06f190>

In [942]: for chunk in reader:
   .....:     print chunk
   .....:
   Unnamed: 0         0         1         2         3
0           0  0.469112 -0.282863 -1.509059 -1.135632
1           1  1.212112 -0.173215  0.119209 -1.044236
2           2 -0.861849 -2.104569 -0.494929  1.071804
3           3  0.721555 -0.706771 -1.039575  0.271860
   Unnamed: 0         0         1         2         3
0           4 -0.424972  0.567020  0.276232 -1.087401
1           5 -0.673690  0.113648 -1.478427  0.524988
2           6  0.404705  0.577046 -1.715002 -1.039268
3           7 -0.370647 -1.157892 -1.344312  0.844885
   Unnamed: 0         0        1         2         3
0           8  1.075770 -0.10905  1.643563 -1.469388
1           9  0.357021 -0.67460 -1.776904 -0.968914

Specifying iterator=True will also return the TextParser object:

In [943]: reader = pd.read_table('tmp.sv', sep='|', iterator=True)

In [944]: reader.get_chunk(5)
Out[944]: 
   Unnamed: 0         0         1         2         3
0           0  0.469112 -0.282863 -1.509059 -1.135632
1           1  1.212112 -0.173215  0.119209 -1.044236
2           2 -0.861849 -2.104569 -0.494929  1.071804
3           3  0.721555 -0.706771 -1.039575  0.271860
4           4 -0.424972  0.567020  0.276232 -1.087401

Writing to CSV format

The Series and DataFrame objects have an instance method to_csv which allows storing the contents of the object as a comma-separated-values file. The function takes a number of arguments. Only the first is required.

  • path: A string path to the file to write nanRep: A string representation of a missing value (default ‘’)
  • cols: Columns to write (default None)
  • header: Whether to write out the column names (default True)
  • index: whether to write row (index) names (default True)
  • index_label: Column label(s) for index column(s) if desired. If None (default), and header and index are True, then the index names are used. (A sequence should be given if the DataFrame uses MultiIndex).
  • mode : Python write mode, default ‘w’
  • sep : Field delimiter for the output file (default ”,”)
  • encoding: a string representing the encoding to use if the contents are non-ascii, for python versions prior to 3

Writing a formatted string

The DataFrame object has an instance method to_string which allows control over the string representation of the object. All arguments are optional:

  • buf default None, for example a StringIO object
  • columns default None, which columns to write
  • col_space default None, minimum width of each column.
  • na_rep default NaN, representation of NA value
  • formatters default None, a dictionary (by column) of functions each of which takes a single argument and returns a formatted string
  • float_format default None, a function which takes a single (float) argument and returns a formatted string; to be applied to floats in the DataFrame.
  • sparsify default True, set to False for a DataFrame with a hierarchical index to print every multiindex key at each row.
  • index_names default True, will print the names of the indices
  • index default True, will print the index (ie, row labels)
  • header default True, will print the column labels
  • justify default left, will print column headers left- or right-justified

The Series object also has a to_string method, but with only the buf, na_rep, float_format arguments. There is also a length argument which, if set to True, will additionally output the length of the Series.

Writing to HTML format

DataFrame object has an instance method to_html which renders the contents of the DataFrame as an html table. The function arguments are as in the method to_string described above.

Clipboard

A handy way to grab data is to use the read_clipboard method, which takes the contents of the clipboard buffer and passes them to the read_table method described in the next section. For instance, you can copy the following text to the clipboard (CTRL-C on many operating systems):

  A B C
x 1 4 p
y 2 5 q
z 3 6 r

And then import the data directly to a DataFrame by calling:

clipdf = pd.read_clipboard(delim_whitespace=True)
In [945]: clipdf
Out[945]: 
   A  B  C
x  1  4  p
y  2  5  q
z  3  6  r

Excel files

The ExcelFile class can read an Excel 2003 file using the xlrd Python module and use the same parsing code as the above to convert tabular data into a DataFrame. To use it, create the ExcelFile object:

xls = ExcelFile('path_to_file.xls')

Then use the parse instance method with a sheetname, then use the same additional arguments as the parsers above:

xls.parse('Sheet1', index_col=None, na_values=['NA'])

To read sheets from an Excel 2007 file, you can pass a filename with a .xlsx extension, in which case the openpyxl module will be used to read the file.

It is often the case that users will insert columns to do temporary computations in Excel and you may not want to read in those columns. ExcelFile.parse takes a parse_cols keyword to allow you to specify a subset of columns to parse.

If parse_cols is an integer, then it is assumed to indicate the last column to be parsed.

xls.parse('Sheet1', parse_cols=2, index_col=None, na_values=['NA'])

If parse_cols is a list of integers, then it is assumed to be the file column indices to be parsed.

xls.parse('Sheet1', parse_cols=[0, 2, 3], index_col=None, na_values=['NA'])

To write a DataFrame object to a sheet of an Excel file, you can use the to_excel instance method. The arguments are largely the same as to_csv described above, the first argument being the name of the excel file, and the optional second argument the name of the sheet to which the DataFrame should be written. For example:

df.to_excel('path_to_file.xlsx', sheet_name='sheet1')

Files with a .xls extension will be written using xlwt and those with a .xlsx extension will be written using openpyxl. The Panel class also has a to_excel instance method, which writes each DataFrame in the Panel to a separate sheet.

In order to write separate DataFrames to separate sheets in a single Excel file, one can use the ExcelWriter class, as in the following example:

writer = ExcelWriter('path_to_file.xlsx')
df1.to_excel(writer, sheet_name='sheet1')
df2.to_excel(writer, sheet_name='sheet2')
writer.save()

HDF5 (PyTables)

HDFStore is a dict-like object which reads and writes pandas to the high performance HDF5 format using the excellent PyTables library.

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

In [947]: print store
<class 'pandas.io.pytables.HDFStore'>
File path: store.h5
Empty

Objects can be written to the file just like adding key-value pairs to a dict:

In [948]: index = date_range('1/1/2000', periods=8)

In [949]: s = Series(randn(5), index=['a', 'b', 'c', 'd', 'e'])

In [950]: df = DataFrame(randn(8, 3), index=index,
   .....:                columns=['A', 'B', 'C'])
   .....:

In [951]: wp = Panel(randn(2, 5, 4), items=['Item1', 'Item2'],
   .....:            major_axis=date_range('1/1/2000', periods=5),
   .....:            minor_axis=['A', 'B', 'C', 'D'])
   .....:

# store.put('s', s) is an equivalent method
In [952]: store['s'] = s

In [953]: store['df'] = df

In [954]: store['wp'] = wp

# the type of stored data
In [955]: store.root.wp._v_attrs.pandas_type
Out[955]: 'wide'

In [956]: store
Out[956]: 
<class 'pandas.io.pytables.HDFStore'>
File path: store.h5
/df     DataFrame
/s      Series   
/wp     Panel    

In a current or later Python session, you can retrieve stored objects:

# store.get('df') is an equivalent method
In [957]: store['df']
Out[957]: 
                   A         B         C
2000-01-01 -0.362543 -0.006154 -0.923061
2000-01-02  0.895717  0.805244 -1.206412
2000-01-03  2.565646  1.431256  1.340309
2000-01-04 -1.170299 -0.226169  0.410835
2000-01-05  0.813850  0.132003 -0.827317
2000-01-06 -0.076467 -1.187678  1.130127
2000-01-07 -1.436737 -1.413681  1.607920
2000-01-08  1.024180  0.569605  0.875906

Deletion of the object specified by the key

# store.remove('wp') is an equivalent method
In [958]: del store['wp']

In [959]: store
Out[959]: 
<class 'pandas.io.pytables.HDFStore'>
File path: store.h5
/df     DataFrame
/s      Series   

These stores are not appendable once written (though you can simply remove them and rewrite). Nor are they queryable; they must be retrieved in their entirety.

Storing in Table format

HDFStore supports another PyTables format on disk, the table format. Conceptually a table is shaped very much like a DataFrame, with rows and columns. A table may be appended to in the same or other sessions. In addition, delete & query type operations are supported.

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

In [961]: df1 = df[0:4]

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

# append data (creates a table automatically)
In [963]: store.append('df', df1)

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

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

# select the entire object
In [966]: store.select('df')
Out[966]: 
                   A         B         C
2000-01-01 -0.362543 -0.006154 -0.923061
2000-01-02  0.895717  0.805244 -1.206412
2000-01-03  2.565646  1.431256  1.340309
2000-01-04 -1.170299 -0.226169  0.410835
2000-01-05  0.813850  0.132003 -0.827317
2000-01-06 -0.076467 -1.187678  1.130127
2000-01-07 -1.436737 -1.413681  1.607920
2000-01-08  1.024180  0.569605  0.875906

# the type of stored data
In [967]: store.root.df._v_attrs.pandas_type
Out[967]: 'frame_table'

Hierarchical Keys

Keys to a store can be specified as a string. These can be in a hierarchical path-name like format (e.g. foo/bar/bah), which will generate a hierarchy of sub-stores (or Groups in PyTables parlance). Keys can be specified with out the leading ‘/’ and are ALWAYS absolute (e.g. ‘foo’ refers to ‘/foo’). Removal operations can remove everying in the sub-store and BELOW, so be careful.

In [968]: store.put('foo/bar/bah', df)

In [969]: store.append('food/orange', df)

In [970]: store.append('food/apple',  df)

In [971]: store
Out[971]: 
<class 'pandas.io.pytables.HDFStore'>
File path: store.h5
/food/apple      frame_table (typ->appendable,nrows->8,indexers->[index])
/foo/bar/bah     DataFrame                                               
/df              frame_table (typ->appendable,nrows->8,indexers->[index])
/food/orange     frame_table (typ->appendable,nrows->8,indexers->[index])

# a list of keys are returned
In [972]: store.keys()
Out[972]: ['/df', '/food/apple', '/food/orange', '/foo/bar/bah']

# remove all nodes under this level
In [973]: store.remove('food')

In [974]: store
Out[974]: 
<class 'pandas.io.pytables.HDFStore'>
File path: store.h5
/foo/bar/bah     DataFrame                                               
/df              frame_table (typ->appendable,nrows->8,indexers->[index])

Storing Mixed Types in a Table

Storing mixed-dtype data is supported. Strings are store as a fixed-width using the maximum size of the appended column. Subsequent appends will truncate strings at this length. Passing min_itemsize = { `values` : size } as a parameter to append will set a larger minimum for the string columns. Storing floats, strings, ints, bools are currently supported.

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

In [976]: df_mixed['string']   = 'string'

In [977]: df_mixed['int']      = 1

In [978]: df_mixed['bool']     = True

In [979]: store.append('df_mixed', df_mixed, min_itemsize = { 'values' : 50 })

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

In [981]: df_mixed1
Out[981]: 
                   A         B         C  string  int  bool
2000-01-01 -0.362543 -0.006154 -0.923061  string    1  True
2000-01-02  0.895717  0.805244 -1.206412  string    1  True
2000-01-03  2.565646  1.431256  1.340309  string    1  True
2000-01-04 -1.170299 -0.226169  0.410835  string    1  True
2000-01-05  0.813850  0.132003 -0.827317  string    1  True
2000-01-06 -0.076467 -1.187678  1.130127  string    1  True
2000-01-07 -1.436737 -1.413681  1.607920  string    1  True
2000-01-08  1.024180  0.569605  0.875906  string    1  True

In [982]: df_mixed1.get_dtype_counts()
Out[982]: 
bool       1
float64    3
int64      1
object     1

# we have provided a minimum string column size
In [983]: store.root.df_mixed.table
Out[983]: 
/df_mixed/table (Table(8,)) ''
  description := {
  "index": Int64Col(shape=(), dflt=0, pos=0),
  "values_block_0": Float64Col(shape=(3,), dflt=0.0, pos=1),
  "values_block_1": StringCol(itemsize=50, shape=(1,), dflt='', pos=2),
  "values_block_2": Int64Col(shape=(1,), dflt=0, pos=3),
  "values_block_3": BoolCol(shape=(1,), dflt=False, pos=4)}
  byteorder := 'little'
  chunkshape := (720,)

Querying a Table

select and delete operations have an optional criteria that can be specified to select/delete only a subset of the data. This allows one to have a very large on-disk table and retrieve only a portion of the data.

A query is specified using the Term class under the hood.

  • ‘index’ and ‘columns’ are supported indexers of a DataFrame
  • ‘major_axis’, ‘minor_axis’, and ‘items’ are supported indexers of the Panel

Valid terms can be created from dict, list, tuple, or string. Objects can be embeded as values. Allowed operations are: <, <=, >, >=, =. = will be inferred as an implicit set operation (e.g. if 2 or more values are provided). The following are all valid terms.

  • dict(field = 'index', op = '>', value = '20121114')
  • ('index', '>', '20121114')
  • 'index>20121114'
  • ('index', '>', datetime(2012,11,14))
  • ('index', ['20121114','20121115'])
  • ('major_axis', '=', Timestamp('2012/11/14'))
  • ('minor_axis', ['A','B'])

Queries are built up using a list of Terms (currently only anding of terms is supported). An example query for a panel might be specified as follows. ['major_axis>20000102', ('minor_axis', '=', ['A','B']) ]. This is roughly translated to: major_axis must be greater than the date 20000102 and the minor_axis must be A or B

In [984]: store.append('wp',wp)

In [985]: store
Out[985]: 
<class 'pandas.io.pytables.HDFStore'>
File path: store.h5
/foo/bar/bah     DataFrame                                                               
/df              frame_table (typ->appendable,nrows->8,indexers->[index])                
/df_mixed        frame_table (typ->appendable,nrows->8,indexers->[index])                
/wp              wide_table (typ->appendable,nrows->20,indexers->[major_axis,minor_axis])

In [986]: store.select('wp',[ Term('major_axis>20000102'), Term('minor_axis', '=', ['A','B']) ])
Out[986]: 
<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

Indexing

You can create an index for a table with create_table_index after data is already in the table (after and append/put operation). Creating a table index is highly encouraged. This will speed your queries a great deal when you use a select with the indexed dimension as the where. It is not automagically done now because you may want to index different axes than the default (except in the case of a DataFrame, where it almost always makes sense to index the index.

# create an index
In [987]: store.create_table_index('df')

In [988]: i = store.root.df.table.cols.index.index

In [989]: i.optlevel, i.kind
Out[989]: (6, 'medium')

# change an index by passing new parameters
In [990]: store.create_table_index('df', optlevel = 9, kind = 'full')

In [991]: i = store.root.df.table.cols.index.index

In [992]: i.optlevel, i.kind
Out[992]: (9, 'full')

Delete from a Table

You can delete from a table selectively by specifying a where. In deleting rows, it is important to understand the PyTables deletes rows by erasing the rows, then moving the following data. Thus deleting can potentially be a very expensive operation depending on the orientation of your data. This is especially true in higher dimensional objects (Panel and Panel4D). To get optimal deletion speed, it pays to have the dimension you are deleting be the first of the indexables.

Data is ordered (on the disk) in terms of the indexables. Here’s a simple use case. You store panel type data, with dates in the major_axis and ids in the minor_axis. The data is then interleaved like this:

  • date_1
    • id_1
    • id_2
    • .
    • id_n
  • date_2
    • id_1
    • .
    • id_n

It should be clear that a delete operation on the major_axis will be fairly quick, as one chunk is removed, then the following data moved. On the other hand a delete operation on the minor_axis will be very expensive. In this case it would almost certainly be faster to rewrite the table using a where that selects all but the missing data.

# returns the number of rows deleted
In [993]: store.remove('wp', 'major_axis>20000102' )
Out[993]: 12

In [994]: store.select('wp')
Out[994]: 
<class 'pandas.core.panel.Panel'>
Dimensions: 2 (items) x 2 (major_axis) x 4 (minor_axis)
Items axis: Item1 to Item2
Major_axis axis: 2000-01-01 00:00:00 to 2000-01-02 00:00:00
Minor_axis axis: A to D

Notes & Caveats

  • Once a table is created its items (Panel) / columns (DataFrame) are fixed; only exactly the same columns can be appended

  • You can not append/select/delete to a non-table (table creation is determined on the first append, or by passing table=True in a put operation)

  • HDFStore is not-threadsafe for writing. The underlying PyTables only supports concurrent reads (via threading or processes). If you need reading and writing at the same time, you need to serialize these operations in a single thread in a single process. You will corrupt your data otherwise. See the issue <https://github.com/pydata/pandas/issues/2397> for more information.

  • PyTables only supports fixed-width string columns in tables. The sizes of a string based indexing column (e.g. columns or minor_axis) are determined as the maximum size of the elements in that axis or by passing the parameter min_itemsize on the first table creation (min_itemsize can be an integer or a dict of column name to an integer). If subsequent appends introduce elements in the indexing axis that are larger than the supported indexer, an Exception will be raised (otherwise you could have a silent truncation of these indexers, leading to loss of information). Just to be clear, this fixed-width restriction applies to indexables (the indexing columns) and string values in a mixed_type table.

    In [995]: store.append('wp_big_strings', wp, min_itemsize = { 'minor_axis' : 30 })
    
    In [996]: wp = wp.rename_axis(lambda x: x + '_big_strings', axis=2)
    
    In [997]: store.append('wp_big_strings', wp)
    
    In [998]: store.select('wp_big_strings')
    Out[998]: 
    <class 'pandas.core.panel.Panel'>
    Dimensions: 2 (items) x 5 (major_axis) x 8 (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_big_strings
    
    # we have provided a minimum minor_axis indexable size
    In [999]: store.root.wp_big_strings.table
    Out[999]: 
    /wp_big_strings/table (Table(40,)) ''
      description := {
      "major_axis": Int64Col(shape=(), dflt=0, pos=0),
      "minor_axis": StringCol(itemsize=30, shape=(), dflt='', pos=1),
      "values_block_0": Float64Col(shape=(2,), dflt=0.0, pos=2)}
      byteorder := 'little'
      chunkshape := (1213,)
    

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. HDFStore will issue a warning if you try to use a prior-version format file. You must read in the entire file and write it out using the new format to take advantage of the updates. The group attribute pandas_version contains the version information.

Performance

  • Tables come with a writing performance penalty as compared to regular stores. The benefit is the ability to append/delete and query (potentially very large amounts of data). Write times are generally longer as compared with regular stores. Query times can be quite fast, especially on an indexed axis.
  • Tables can (as of 0.10.0) be expressed as different types.
    • AppendableTable which is a similiar table to past versions (this is the default).
    • WORMTable (pending implementation) - is available to faciliate very fast writing of tables that are also queryable (but CANNOT support appends)
  • Tables offer better performance when compressed after writing them (as opposed to turning on compression at the very beginning) use the pytables utilities ptrepack to rewrite the file (and also can change compression methods)
  • Duplicate rows can be written, but are filtered out in selection (with the last items being selected; thus a table is unique on major, minor pairs)

Experimental

HDFStore supports Panel4D storage.

In [1000]: p4d = Panel4D({ 'l1' : wp })

In [1001]: p4d
Out[1001]: 
<class 'pandas.core.panelnd.Panel4D'>
Dimensions: 1 (labels) x 2 (items) x 5 (major_axis) x 4 (minor_axis)
Labels axis: l1 to l1
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_big_strings to D_big_strings

In [1002]: store.append('p4d', p4d)

In [1003]: store
Out[1003]: 
<class 'pandas.io.pytables.HDFStore'>
File path: store.h5
/foo/bar/bah        DataFrame                                                                     
/df                 frame_table (typ->appendable,nrows->8,indexers->[index])                      
/df_mixed           frame_table (typ->appendable,nrows->8,indexers->[index])                      
/p4d                ndim_table (typ->appendable,nrows->40,indexers->[items,major_axis,minor_axis])
/wp                 wide_table (typ->appendable,nrows->8,indexers->[major_axis,minor_axis])       
/wp_big_strings     wide_table (typ->appendable,nrows->40,indexers->[major_axis,minor_axis])      

These, by default, index the three axes items, major_axis, minor_axis. On an AppendableTable it is possible to setup with the first append a different indexing scheme, depending on how you want to store your data. Pass the axes keyword with a list of dimension (currently must by exactly 1 less than the total dimensions of the object). This cannot be changed after table creation.

In [1004]: store.append('p4d2', p4d, axes = ['labels','major_axis','minor_axis'])

In [1005]: store
Out[1005]: 
<class 'pandas.io.pytables.HDFStore'>
File path: store.h5
/foo/bar/bah        DataFrame                                                                      
/df                 frame_table (typ->appendable,nrows->8,indexers->[index])                       
/df_mixed           frame_table (typ->appendable,nrows->8,indexers->[index])                       
/p4d                ndim_table (typ->appendable,nrows->40,indexers->[items,major_axis,minor_axis]) 
/p4d2               ndim_table (typ->appendable,nrows->20,indexers->[labels,major_axis,minor_axis])
/wp                 wide_table (typ->appendable,nrows->8,indexers->[major_axis,minor_axis])        
/wp_big_strings     wide_table (typ->appendable,nrows->40,indexers->[major_axis,minor_axis])       

In [1006]: store.select('p4d2', [ Term('labels=l1'), Term('items=Item1'), Term('minor_axis=A_big_strings') ])
Out[1006]: 
<class 'pandas.core.panelnd.Panel4D'>
Dimensions: 1 (labels) x 1 (items) x 5 (major_axis) x 1 (minor_axis)
Labels axis: l1 to l1
Items axis: Item1 to Item1
Major_axis axis: 2000-01-01 00:00:00 to 2000-01-05 00:00:00
Minor_axis axis: A_big_strings to A_big_strings