IO Tools (Text, CSV, HDF5, ...)¶
The Pandas I/O api is 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
- read_pickle
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
- to_pickle
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. See the cookbook for some advanced strategies
They can take a number of arguments:
- filepath_or_buffer: Either a string path to a file, url (including http, ftp, and s3 locations), 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. The header can be a list of integers that specify row locations for a multi-index on the columns E.g. [0,1,3]. Interveaning rows that are not specified will be skipped. (E.g. 2 in this example are skipped)
- 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.
- lineterminator : string (length 1), default None, Character to break file into lines. Only valid with C parser
- quotechar : string, The character to used to denote the start and end of a quoted item. Quoted items can include the delimiter and it will be ignored.
- quoting : int, Controls whether quotes should be recognized. Values are taken from csv.QUOTE_* values. Acceptable values are 0, 1, 2, and 3 for QUOTE_MINIMAL, QUOTE_ALL, QUOTE_NONE, and QUOTE_NONNUMERIC, respectively.
- skipinitialspace : boolean, default False, Skip spaces after delimiter
- escapechar : string, to specify how to escape quoted data
- 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 TextFileReader 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 TextFileReader 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
- error_bad_lines: if False then any lines causing an error will be skipped bad lines
- usecols: a subset of columns to return, results in much faster parsing time and lower memory usage.
- mangle_dupe_cols: boolean, default True, then duplicate columns will be specified as ‘X.0’...’X.N’, rather than ‘X’...’X’
- tupleize_cols: boolean, default True, if False, convert a list of tuples to a multi-index of columns, otherwise, leave the column index as a list of tuples
Consider a typical CSV file containing, in this case, some time series data:
In [1]: 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 [2]: pd.read_csv('foo.csv')
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 [3]: pd.read_csv('foo.csv', index_col=0)
A B C
date
20090101 a 1 2
20090102 b 3 4
20090103 c 4 5
In [4]: pd.read_csv('foo.csv', index_col='date')
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 [5]: pd.read_csv('foo.csv', index_col=[0, 'A'])
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 [6]: 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 [7]: dia = csv.excel()
In [8]: dia.quoting = csv.QUOTE_NONE
In [9]: pd.read_csv(StringIO(data), dialect=dia)
label1 label2 label3
index1 "a c e
index2 b d f
All of the dialect options can be specified separately by keyword arguments:
In [10]: data = 'a,b,c~1,2,3~4,5,6'
In [11]: pd.read_csv(StringIO(data), lineterminator='~')
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 [12]: data = 'a, b, c\n1, 2, 3\n4, 5, 6'
In [13]: print data
a, b, c
1, 2, 3
4, 5, 6
In [14]: pd.read_csv(StringIO(data), skipinitialspace=True)
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 [15]: data = 'a,b,c\n1,2,3\n4,5,6\n7,8,9'
In [16]: print data
a,b,c
1,2,3
4,5,6
7,8,9
In [17]: df = pd.read_csv(StringIO(data), dtype=object)
In [18]: df
a b c
0 1 2 3
1 4 5 6
2 7 8 9
In [19]: df['a'][0]
'1'
In [20]: df = pd.read_csv(StringIO(data), dtype={'b': object, 'c': np.float64})
In [21]: df.dtypes
a int64
b object
c float64
dtype: object
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 [22]: from StringIO import StringIO
In [23]: data = 'a,b,c\n1,2,3\n4,5,6\n7,8,9'
In [24]: print data
a,b,c
1,2,3
4,5,6
7,8,9
In [25]: pd.read_csv(StringIO(data))
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 [26]: print data
a,b,c
1,2,3
4,5,6
7,8,9
In [27]: pd.read_csv(StringIO(data), names=['foo', 'bar', 'baz'], header=0)
foo bar baz
0 1 2 3
1 4 5 6
2 7 8 9
In [28]: pd.read_csv(StringIO(data), names=['foo', 'bar', 'baz'], header=None)
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 [29]: data = 'skip this skip it\na,b,c\n1,2,3\n4,5,6\n7,8,9'
In [30]: pd.read_csv(StringIO(data), header=1)
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 [31]: data = 'a,b,c,d\n1,2,3,foo\n4,5,6,bar\n7,8,9,baz'
In [32]: pd.read_csv(StringIO(data))
a b c d
0 1 2 3 foo
1 4 5 6 bar
2 7 8 9 baz
In [33]: pd.read_csv(StringIO(data), usecols=['b', 'd'])
b d
0 2 foo
1 5 bar
2 8 baz
In [34]: pd.read_csv(StringIO(data), usecols=[0, 2, 3])
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 [35]: data = 'word,length\nTr\xe4umen,7\nGr\xfc\xdfe,5'
In [36]: df = pd.read_csv(StringIO(data), encoding='latin-1')
In [37]: df
word length
0 Träumen 7
1 Grüße 5
In [38]: df['word'][1]
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 [39]: data = 'a,b,c\n4,apple,bat,5.7\n8,orange,cow,10'
In [40]: pd.read_csv(StringIO(data))
a b c
4 apple bat 5.7
8 orange cow 10.0
In [41]: data = 'index,a,b,c\n4,apple,bat,5.7\n8,orange,cow,10'
In [42]: pd.read_csv(StringIO(data), index_col=0)
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 [43]: data = 'a,b,c\n4,apple,bat,\n8,orange,cow,'
In [44]: print data
a,b,c
4,apple,bat,
8,orange,cow,
In [45]: pd.read_csv(StringIO(data))
a b c
4 apple bat NaN
8 orange cow NaN
In [46]: pd.read_csv(StringIO(data), index_col=False)
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 [47]: df = pd.read_csv('foo.csv', index_col=0, parse_dates=True)
In [48]: df
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 [49]: df.index
<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 [50]: 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 [51]: df = pd.read_csv('tmp.csv', header=None, parse_dates=[[1, 2], [1, 3]])
In [52]: df
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 [53]: df = pd.read_csv('tmp.csv', header=None, parse_dates=[[1, 2], [1, 3]],
....: keep_date_col=True)
....:
In [54]: df
1_2 1_3 0 1 2 \
0 1999-01-27 19:00:00 1999-01-27 18:56:00 KORD 19990127 19:00:00
1 1999-01-27 20:00:00 1999-01-27 19:56:00 KORD 19990127 20:00:00
2 1999-01-27 21:00:00 1999-01-27 20:56:00 KORD 19990127 21:00:00
3 1999-01-27 21:00:00 1999-01-27 21:18:00 KORD 19990127 21:00:00
4 1999-01-27 22:00:00 1999-01-27 21:56:00 KORD 19990127 22:00:00
5 1999-01-27 23:00:00 1999-01-27 22:56:00 KORD 19990127 23:00:00
3 4
0 18:56:00 0.81
1 19:56:00 0.01
2 20:56:00 -0.59
3 21:18:00 -0.99
4 21:56:00 -0.59
5 22:56:00 -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 [55]: date_spec = {'nominal': [1, 2], 'actual': [1, 3]}
In [56]: df = pd.read_csv('tmp.csv', header=None, parse_dates=date_spec)
In [57]: df
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 [58]: date_spec = {'nominal': [1, 2], 'actual': [1, 3]}
In [59]: df = pd.read_csv('tmp.csv', header=None, parse_dates=date_spec,
....: index_col=0) #index is the nominal column
....:
In [60]: df
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 [61]: import pandas.io.date_converters as conv
In [62]: df = pd.read_csv('tmp.csv', header=None, parse_dates=date_spec,
....: date_parser=conv.parse_date_time)
....:
In [63]: df
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 [64]: print open('tmp.csv').read()
date,value,cat
1/6/2000,5,a
2/6/2000,10,b
3/6/2000,15,c
In [65]: pd.read_csv('tmp.csv', parse_dates=[0])
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 [66]: pd.read_csv('tmp.csv', dayfirst=True, parse_dates=[0])
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 [67]: print open('tmp.csv').read()
ID|level|category
Patient1|123,000|x
Patient2|23,000|y
Patient3|1,234,018|z
In [68]: df = pd.read_csv('tmp.csv', sep='|')
In [69]: df
ID level category
0 Patient1 123,000 x
1 Patient2 23,000 y
2 Patient3 1,234,018 z
In [70]: df.level.dtype
dtype('O')
The thousands keyword allows integers to be parsed correctly
In [71]: print open('tmp.csv').read()
ID|level|category
Patient1|123,000|x
Patient2|23,000|y
Patient3|1,234,018|z
In [72]: df = pd.read_csv('tmp.csv', sep='|', thousands=',')
In [73]: df
ID level category
0 Patient1 123000 x
1 Patient2 23000 y
2 Patient3 1234018 z
In [74]: df.level.dtype
dtype('int64')
Comments¶
Sometimes comments or meta data may be included in a file:
In [75]: 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 [76]: df = pd.read_csv('tmp.csv')
In [77]: df
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 [78]: df = pd.read_csv('tmp.csv', comment='#')
In [79]: df
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 [80]: print open('tmp.csv').read()
level
Patient1,123000
Patient2,23000
Patient3,1234018
In [81]: output = pd.read_csv('tmp.csv', squeeze=True)
In [82]: output
Patient1 123000
Patient2 23000
Patient3 1234018
Name: level, dtype: int64
In [83]: type(output)
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 [84]: data= 'a,b,c\n1,Yes,2\n3,No,4'
In [85]: print data
a,b,c
1,Yes,2
3,No,4
In [86]: pd.read_csv(StringIO(data))
a b c
0 1 Yes 2
1 3 No 4
In [87]: pd.read_csv(StringIO(data), true_values=['Yes'], false_values=['No'])
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 [88]: data = 'a,b\n"hello, \\"Bob\\", nice to see you",5'
In [89]: print data
a,b
"hello, \"Bob\", nice to see you",5
In [90]: pd.read_csv(StringIO(data), escapechar='\\')
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 [91]: 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 [92]: colspecs = [(0, 6), (8, 20), (21, 33), (34, 43)]
In [93]: df = pd.read_fwf('bar.csv', colspecs=colspecs, header=None, index_col=0)
In [94]: df
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 [95]: widths = [6, 14, 13, 10]
In [96]: df = pd.read_fwf('bar.csv', widths=widths, header=None)
In [97]: df
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 [98]: 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 [99]: pd.read_csv('foo.csv')
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 [100]: df = pd.read_csv('foo.csv', parse_dates=True)
In [101]: df.index
<class 'pandas.tseries.index.DatetimeIndex'>
[2009-01-01 00:00:00, ..., 2009-01-03 00:00:00]
Length: 3, Freq: None, Timezone: None
Reading an index with a MultiIndex¶
Suppose you have data indexed by two columns:
In [102]: 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 for the index of the returned object:
In [103]: df = pd.read_csv("data/mindex_ex.csv", index_col=[0,1])
In [104]: df
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 [105]: df.ix[1978]
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
Reading columns with a MultiIndex¶
By specifying list of row locations for the header argument, you can read in a MultiIndex for the columns. Specifying non-consecutive rows will skip the interveaning rows.
In [106]: from pandas.util.testing import makeCustomDataframe as mkdf
In [107]: df = mkdf(5,3,r_idx_nlevels=2,c_idx_nlevels=4)
In [108]: df.to_csv('mi.csv',tupleize_cols=False)
In [109]: 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 [110]: 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
Note: The default behavior in 0.12 remains unchanged (tupleize_cols=True) from prior versions, but starting with 0.13, the default to write and read multi-index columns will be in the new format (tupleize_cols=False)
Note: 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.
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 [111]: print open('tmp2.sv').read()
:0:1:2:3
0:0.4691122999071863:-0.2828633443286633:-1.5090585031735124:-1.1356323710171934
1:1.2121120250208506:-0.17321464905330858:0.11920871129693428:-1.0442359662799567
2:-0.8618489633477999:-2.1045692188948086:-0.4949292740687813:1.071803807037338
3:0.7215551622443669:-0.7067711336300845:-1.0395749851146963:0.27185988554282986
4:-0.42497232978883753:0.567020349793672:0.27623201927771873:-1.0874006912859915
5:-0.6736897080883706:0.1136484096888855:-1.4784265524372235:0.5249876671147047
6:0.4047052186802365:0.5770459859204836:-1.7150020161146375:-1.0392684835147725
7:-0.3706468582364464:-1.1578922506419993:-1.344311812731667:0.8448851414248841
8:1.0757697837155533:-0.10904997528022223:1.6435630703622064:-1.4693879595399115
9:0.35702056413309086:-0.6746001037299882:-1.776903716971867:-0.9689138124473498
In [112]: pd.read_csv('tmp2.sv')
:0:1:2:3
0 0:0.4691122999071863:-0.2828633443286633:-1.50...
1 1:1.2121120250208506:-0.17321464905330858:0.11...
2 2:-0.8618489633477999:-2.1045692188948086:-0.4...
3 3:0.7215551622443669:-0.7067711336300845:-1.03...
4 4:-0.42497232978883753:0.567020349793672:0.276...
5 5:-0.6736897080883706:0.1136484096888855:-1.47...
6 6:0.4047052186802365:0.5770459859204836:-1.715...
7 7:-0.3706468582364464:-1.1578922506419993:-1.3...
8 8:1.0757697837155533:-0.10904997528022223:1.64...
9 9:0.35702056413309086:-0.6746001037299882:-1.7...
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 [113]: print open('tmp.sv').read()
|0|1|2|3
0|0.4691122999071863|-0.2828633443286633|-1.5090585031735124|-1.1356323710171934
1|1.2121120250208506|-0.17321464905330858|0.11920871129693428|-1.0442359662799567
2|-0.8618489633477999|-2.1045692188948086|-0.4949292740687813|1.071803807037338
3|0.7215551622443669|-0.7067711336300845|-1.0395749851146963|0.27185988554282986
4|-0.42497232978883753|0.567020349793672|0.27623201927771873|-1.0874006912859915
5|-0.6736897080883706|0.1136484096888855|-1.4784265524372235|0.5249876671147047
6|0.4047052186802365|0.5770459859204836|-1.7150020161146375|-1.0392684835147725
7|-0.3706468582364464|-1.1578922506419993|-1.344311812731667|0.8448851414248841
8|1.0757697837155533|-0.10904997528022223|1.6435630703622064|-1.4693879595399115
9|0.35702056413309086|-0.6746001037299882|-1.776903716971867|-0.9689138124473498
In [114]: table = pd.read_table('tmp.sv', sep='|')
In [115]: table
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 TextFileReader:
In [116]: reader = pd.read_table('tmp.sv', sep='|', chunksize=4)
In [117]: reader
<pandas.io.parsers.TextFileReader at 0xbd77950>
In [118]: 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 TextFileReader object:
In [119]: reader = pd.read_table('tmp.sv', sep='|', iterator=True)
In [120]: reader.get_chunk(5)
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
- na_rep: 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
- tupleize_cols: boolean, default True, if False, write as a list of tuples, otherwise write in an expanded line format suitable for read_csv
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.
JSON¶
Read and write JSON format files.
Writing JSON¶
A Series or DataFrame can be converted to a valid JSON string. Use to_json with optional parameters:
path_or_buf : the pathname or buffer to write the output This can be None in which case a JSON string is returned
orient :
- Series :
- default is index
- allowed values are {split, records, index}
- DataFrame
- default is columns
- allowed values are {split, records, index, columns, values}
The format of the JSON string
split dict like {index -> [index], columns -> [columns], data -> [values]} records list like [{column -> value}, ... , {column -> value}] index dict like {index -> {column -> value}} columns dict like {column -> {index -> value}} values just the values array date_format : type of date conversion (epoch = epoch milliseconds, iso = ISO8601), default is epoch
double_precision : The number of decimal places to use when encoding floating point values, default 10.
force_ascii : force encoded string to be ASCII, default True.
Note NaN’s and None will be converted to null and datetime objects will be converted based on the date_format parameter
In [121]: dfj = DataFrame(randn(5, 2), columns=list('AB'))
In [122]: json = dfj.to_json()
In [123]: json
'{"A":{"0":-1.2945235903,"1":0.2766617129,"2":-0.0139597524,"3":-0.0061535699,"4":0.8957173022},"B":{"0":0.4137381054,"1":-0.472034511,"2":-0.3625429925,"3":-0.923060654,"4":0.8052440254}}'
Writing in iso date format
In [124]: dfd = DataFrame(randn(5, 2), columns=list('AB'))
In [125]: dfd['date'] = Timestamp('20130101')
In [126]: json = dfd.to_json(date_format='iso')
In [127]: json
'{"A":{"0":-1.2064117817,"1":1.4312559863,"2":-1.1702987971,"3":0.4108345112,"4":0.1320031703},"B":{"0":2.5656459463,"1":1.3403088498,"2":-0.2261692849,"3":0.8138502857,"4":-0.8273169356},"date":{"0":"2013-01-01T00:00:00","1":"2013-01-01T00:00:00","2":"2013-01-01T00:00:00","3":"2013-01-01T00:00:00","4":"2013-01-01T00:00:00"}}'
Writing to a file, with a date index and a date column
In [128]: dfj2 = dfj.copy()
In [129]: dfj2['date'] = Timestamp('20130101')
In [130]: dfj2['ints'] = range(5)
In [131]: dfj2['bools'] = True
In [132]: dfj2.index = date_range('20130101',periods=5)
In [133]: dfj2.to_json('test.json')
In [134]: open('test.json').read()
'{"A":{"1356998400000000000":-1.2945235903,"1357084800000000000":0.2766617129,"1357171200000000000":-0.0139597524,"1357257600000000000":-0.0061535699,"1357344000000000000":0.8957173022},"B":{"1356998400000000000":0.4137381054,"1357084800000000000":-0.472034511,"1357171200000000000":-0.3625429925,"1357257600000000000":-0.923060654,"1357344000000000000":0.8052440254},"date":{"1356998400000000000":1356998400000000000,"1357084800000000000":1356998400000000000,"1357171200000000000":1356998400000000000,"1357257600000000000":1356998400000000000,"1357344000000000000":1356998400000000000},"ints":{"1356998400000000000":0,"1357084800000000000":1,"1357171200000000000":2,"1357257600000000000":3,"1357344000000000000":4},"bools":{"1356998400000000000":true,"1357084800000000000":true,"1357171200000000000":true,"1357257600000000000":true,"1357344000000000000":true}}'
Reading JSON¶
Reading a JSON string to pandas object can take a number of parameters. The parser will try to parse a DataFrame if typ is not supplied or is None. To explicity force Series parsing, pass typ=series
filepath_or_buffer : a VALID JSON string or file handle / StringIO. The string could be a URL. Valid URL schemes include http, ftp, s3, and file. For file URLs, a host is expected. For instance, a local file could be file ://localhost/path/to/table.json
typ : type of object to recover (series or frame), default ‘frame’
orient :
- Series :
- default is index
- allowed values are {split, records, index}
- DataFrame
- default is columns
- allowed values are {split, records, index, columns, values}
The format of the JSON string
split dict like {index -> [index], columns -> [columns], data -> [values]} records list like [{column -> value}, ... , {column -> value}] index dict like {index -> {column -> value}} columns dict like {column -> {index -> value}} values just the values array dtype : if True, infer dtypes, if a dict of column to dtype, then use those, if False, then don’t infer dtypes at all, default is True, apply only to the data
convert_axes : boolean, try to convert the axes to the proper dtypes, default is True
convert_dates : a list of columns to parse for dates; If True, then try to parse datelike columns, default is True
keep_default_dates : boolean, default True. If parsing dates, then parse the default datelike columns
numpy : direct decoding to numpy arrays. default is False; Note that the JSON ordering MUST be the same for each term if numpy=True
precise_float : boolean, default False. Set to enable usage of higher precision (strtod) function when decoding string to double values. Default (False) is to use fast but less precise builtin functionality
The parser will raise one of ValueError/TypeError/AssertionError if the JSON is not parsable.
The default of convert_axes=True, dtype=True, and convert_dates=True will try to parse the axes, and all of the data into appropriate types, including dates. If you need to override specific dtypes, pass a dict to dtype. convert_axes should only be set to False if you need to preserve string-like numbers (e.g. ‘1’, ‘2’) in an axes.
Warning
When reading JSON data, automatic coercing into dtypes has some quirks:
- an index can be reconstructed in a different order from serialization, that is, the returned order is not guaranteed to be the same as before serialization
- a column that was float data will be converted to integer if it can be done safely, e.g. a column of 1.
- bool columns will be converted to integer on reconstruction
Thus there are times where you may want to specify specific dtypes via the dtype keyword argument.
Reading from a JSON string
In [135]: pd.read_json(json)
A B date
0 -1.206412 2.565646 2013-01-01 00:00:00
1 1.431256 1.340309 2013-01-01 00:00:00
2 -1.170299 -0.226169 2013-01-01 00:00:00
3 0.410835 0.813850 2013-01-01 00:00:00
4 0.132003 -0.827317 2013-01-01 00:00:00
Reading from a file
In [136]: pd.read_json('test.json')
A B bools date ints
2013-01-01 -1.294524 0.413738 True 2013-01-01 00:00:00 0
2013-01-02 0.276662 -0.472035 True 2013-01-01 00:00:00 1
2013-01-03 -0.013960 -0.362543 True 2013-01-01 00:00:00 2
2013-01-04 -0.006154 -0.923061 True 2013-01-01 00:00:00 3
2013-01-05 0.895717 0.805244 True 2013-01-01 00:00:00 4
Don’t convert any data (but still convert axes and dates)
In [137]: pd.read_json('test.json',dtype=object).dtypes
A object
B object
bools object
date datetime64[ns]
ints object
dtype: object
Specify how I want to convert data
In [138]: pd.read_json('test.json',dtype={'A' : 'float32', 'bools' : 'int8'}).dtypes
A float32
B float64
bools int8
date datetime64[ns]
ints int64
dtype: object
I like my string indicies
In [139]: si = DataFrame(np.zeros((4, 4)),
.....: columns=range(4),
.....: index=[str(i) for i in range(4)])
.....:
In [140]: si
0 1 2 3
0 0 0 0 0
1 0 0 0 0
2 0 0 0 0
3 0 0 0 0
In [141]: si.index
Index([u'0', u'1', u'2', u'3'], dtype=object)
In [142]: si.columns
Int64Index([0, 1, 2, 3], dtype=int64)
In [143]: json = si.to_json()
In [144]: sij = pd.read_json(json,convert_axes=False)
In [145]: sij
0 1 2 3
0 0 0 0 0
1 0 0 0 0
2 0 0 0 0
3 0 0 0 0
In [146]: sij.index
Index([u'0', u'1', u'2', u'3'], dtype=object)
In [147]: sij.columns
Index([u'0', u'1', u'2', u'3'], dtype=object)
HTML¶
Reading HTML Content¶
Warning
We highly encourage you to read the HTML parsing gotchas regarding the issues surrounding the BeautifulSoup4/html5lib/lxml parsers.
New in version 0.12.
The top-level read_html() function can accept an HTML string/file/url and will parse HTML tables into list of pandas DataFrames. Let’s look at a few examples.
Note
read_html returns a list of DataFrame objects, even if there is only a single table contained in the HTML content
Read a URL with no options
In [148]: url = 'http://www.fdic.gov/bank/individual/failed/banklist.html'
In [149]: dfs = read_html(url)
In [150]: dfs
[<class 'pandas.core.frame.DataFrame'>
Int64Index: 518 entries, 0 to 517
Data columns (total 8 columns):
Bank Name 518 non-null values
City 518 non-null values
ST 518 non-null values
CERT 518 non-null values
Acquiring Institution 518 non-null values
Closing Date 518 non-null values
Updated Date 518 non-null values
Loss Share Type 518 non-null values
dtypes: datetime64[ns](2), int64(1), object(5)]
Note
The data from the above URL changes every Monday so the resulting data above and the data below may be slightly different.
Read in the content of the file from the above URL and pass it to read_html as a string
In [151]: with open(file_path, 'r') as f:
.....: dfs = read_html(f.read())
.....:
In [152]: dfs
[<class 'pandas.core.frame.DataFrame'>
Int64Index: 506 entries, 0 to 505
Data columns (total 7 columns):
Bank Name 506 non-null values
City 506 non-null values
ST 506 non-null values
CERT 506 non-null values
Acquiring Institution 506 non-null values
Closing Date 506 non-null values
Updated Date 506 non-null values
dtypes: datetime64[ns](2), int64(1), object(4)]
You can even pass in an instance of StringIO if you so desire
In [153]: from cStringIO import StringIO
In [154]: with open(file_path, 'r') as f:
.....: sio = StringIO(f.read())
.....:
In [155]: dfs = read_html(sio)
In [156]: dfs
[<class 'pandas.core.frame.DataFrame'>
Int64Index: 506 entries, 0 to 505
Data columns (total 7 columns):
Bank Name 506 non-null values
City 506 non-null values
ST 506 non-null values
CERT 506 non-null values
Acquiring Institution 506 non-null values
Closing Date 506 non-null values
Updated Date 506 non-null values
dtypes: datetime64[ns](2), int64(1), object(4)]
Note
The following examples are not run by the IPython evaluator due to the fact that having so many network-accessing functions slows down the documentation build. If you spot an error or an example that doesn’t run, please do not hesitate to report it over on pandas GitHub issues page.
Read a URL and match a table that contains specific text
match = 'Metcalf Bank'
df_list = read_html(url, match=match)
Specify a header row (by default <th> elements are used to form the column index); if specified, the header row is taken from the data minus the parsed header elements (<th> elements).
dfs = read_html(url, header=0)
Specify an index column
dfs = read_html(url, index_col=0)
Specify a number of rows to skip
dfs = read_html(url, skiprows=0)
Specify a number of rows to skip using a list (xrange (Python 2 only) works as well)
dfs = read_html(url, skiprows=range(2))
Don’t infer numeric and date types
dfs = read_html(url, infer_types=False)
Specify an HTML attribute
dfs1 = read_html(url, attrs={'id': 'table'})
dfs2 = read_html(url, attrs={'class': 'sortable'})
print np.array_equal(dfs1[0], dfs2[0]) # Should be True
Use some combination of the above
dfs = read_html(url, match='Metcalf Bank', index_col=0)
Read in pandas to_html output (with some loss of floating point precision)
df = DataFrame(randn(2, 2))
s = df.to_html(float_format='{0:.40g}'.format)
dfin = read_html(s, index_col=0)
The lxml backend will raise an error on a failed parse if that is the only parser you provide (if you only have a single parser you can provide just a string, but it is considered good practice to pass a list with one string if, for example, the function expects a sequence of strings)
dfs = read_html(url, 'Metcalf Bank', index_col=0, flavor=['lxml'])
or
dfs = read_html(url, 'Metcalf Bank', index_col=0, flavor='lxml')
However, if you have bs4 and html5lib installed and pass None or ['lxml', 'bs4'] then the parse will most likely succeed. Note that as soon as a parse succeeds, the function will return.
dfs = read_html(url, 'Metcalf Bank', index_col=0, flavor=['lxml', 'bs4'])
Writing to HTML files¶
DataFrame objects have 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.
Note
Not all of the possible options for DataFrame.to_html are shown here for brevity’s sake. See to_html() for the full set of options.
In [157]: df = DataFrame(randn(2, 2))
In [158]: df
0 1
0 -0.076467 -1.187678
1 1.130127 -1.436737
In [159]: print df.to_html() # raw html
<table border="1" class="dataframe">
<thead>
<tr style="text-align: right;">
<th></th>
<th>0</th>
<th>1</th>
</tr>
</thead>
<tbody>
<tr>
<th>0</th>
<td>-0.076467</td>
<td>-1.187678</td>
</tr>
<tr>
<th>1</th>
<td> 1.130127</td>
<td>-1.436737</td>
</tr>
</tbody>
</table>
HTML:
0 | 1 | |
---|---|---|
0 | -0.076467 | -1.187678 |
1 | 1.130127 | -1.436737 |
The columns argument will limit the columns shown
In [160]: print df.to_html(columns=[0])
<table border="1" class="dataframe">
<thead>
<tr style="text-align: right;">
<th></th>
<th>0</th>
</tr>
</thead>
<tbody>
<tr>
<th>0</th>
<td>-0.076467</td>
</tr>
<tr>
<th>1</th>
<td> 1.130127</td>
</tr>
</tbody>
</table>
HTML:
0 | |
---|---|
0 | -0.076467 |
1 | 1.130127 |
float_format takes a Python callable to control the precision of floating point values
In [161]: print df.to_html(float_format='{0:.10f}'.format)
<table border="1" class="dataframe">
<thead>
<tr style="text-align: right;">
<th></th>
<th>0</th>
<th>1</th>
</tr>
</thead>
<tbody>
<tr>
<th>0</th>
<td>-0.0764670176</td>
<td>-1.1876775774</td>
</tr>
<tr>
<th>1</th>
<td> 1.1301272978</td>
<td>-1.4367373184</td>
</tr>
</tbody>
</table>
HTML:
0 | 1 | |
---|---|---|
0 | -0.0764670176 | -1.1876775774 |
1 | 1.1301272978 | -1.4367373184 |
bold_rows will make the row labels bold by default, but you can turn that off
In [162]: print df.to_html(bold_rows=False)
<table border="1" class="dataframe">
<thead>
<tr style="text-align: right;">
<th></th>
<th>0</th>
<th>1</th>
</tr>
</thead>
<tbody>
<tr>
<td>0</td>
<td>-0.076467</td>
<td>-1.187678</td>
</tr>
<tr>
<td>1</td>
<td> 1.130127</td>
<td>-1.436737</td>
</tr>
</tbody>
</table>
0 | 1 | |
---|---|---|
0 | -0.076467 | -1.187678 |
1 | 1.130127 | -1.436737 |
The classes argument provides the ability to give the resulting HTML table CSS classes. Note that these classes are appended to the existing 'dataframe' class.
In [163]: print df.to_html(classes=['awesome_table_class', 'even_more_awesome_class'])
<table border="1" class="dataframe awesome_table_class even_more_awesome_class">
<thead>
<tr style="text-align: right;">
<th></th>
<th>0</th>
<th>1</th>
</tr>
</thead>
<tbody>
<tr>
<th>0</th>
<td>-0.076467</td>
<td>-1.187678</td>
</tr>
<tr>
<th>1</th>
<td> 1.130127</td>
<td>-1.436737</td>
</tr>
</tbody>
</table>
Finally, the escape argument allows you to control whether the “<”, “>” and “&” characters escaped in the resulting HTML (by default it is True). So to get the HTML without escaped characters pass escape=False
In [164]: df = DataFrame({'a': list('&<>'), 'b': randn(3)})
Escaped:
In [165]: print df.to_html()
<table border="1" class="dataframe">
<thead>
<tr style="text-align: right;">
<th></th>
<th>a</th>
<th>b</th>
</tr>
</thead>
<tbody>
<tr>
<th>0</th>
<td> &</td>
<td>-1.413681</td>
</tr>
<tr>
<th>1</th>
<td> <</td>
<td> 1.607920</td>
</tr>
<tr>
<th>2</th>
<td> ></td>
<td> 1.024180</td>
</tr>
</tbody>
</table>
a | b | |
---|---|---|
0 | & | -1.413681 |
1 | < | 1.607920 |
2 | > | 1.024180 |
Not escaped:
In [166]: print df.to_html(escape=False)
<table border="1" class="dataframe">
<thead>
<tr style="text-align: right;">
<th></th>
<th>a</th>
<th>b</th>
</tr>
</thead>
<tbody>
<tr>
<th>0</th>
<td> &</td>
<td>-1.413681</td>
</tr>
<tr>
<th>1</th>
<td> <</td>
<td> 1.607920</td>
</tr>
<tr>
<th>2</th>
<td> ></td>
<td> 1.024180</td>
</tr>
</tbody>
</table>
a | b | |
---|---|---|
0 | & | -1.413681 |
1 | < | 1.607920 |
2 | > | 1.024180 |
Note
Some browsers may not show a difference in the rendering of the previous two HTML tables.
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. 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()
In [167]: clipdf
A B C
x 1 4 p
y 2 5 q
z 3 6 r
The to_clipboard method can be used to write the contents of a DataFrame to the clipboard. Following which you can paste the clipboard contents into other applications (CTRL-V on many operating systems). Here we illustrate writing a DataFrame into clipboard and reading it back.
In [168]: df=pd.DataFrame(randn(5,3))
In [169]: df
0 1 2
0 0.569605 0.875906 -2.211372
1 0.974466 -2.006747 -0.410001
2 -0.078638 0.545952 -1.219217
3 -1.226825 0.769804 -1.281247
4 -0.727707 -0.121306 -0.097883
In [170]: df.to_clipboard()
In [171]: pd.read_clipboard()
0 1 2
0 0.569605 0.875906 -2.211372
1 0.974466 -2.006747 -0.410001
2 -0.078638 0.545952 -1.219217
3 -1.226825 0.769804 -1.281247
4 -0.727707 -0.121306 -0.097883
We can see that we got the same content back, which we had earlier written to the clipboard.
Note
You may need to install xclip or xsel (with gtk or PyQt4 modules) on Linux to use these methods.
Pickling and serialization¶
All pandas objects are equipped with to_pickle methods which use Python’s cPickle module to save data structures to disk using the pickle format.
In [172]: df
0 1 2
0 0.569605 0.875906 -2.211372
1 0.974466 -2.006747 -0.410001
2 -0.078638 0.545952 -1.219217
3 -1.226825 0.769804 -1.281247
4 -0.727707 -0.121306 -0.097883
In [173]: df.to_pickle('foo.pkl')
The read_pickle function in the pandas namespace can be used to load any pickled pandas object (or any other pickled object) from file:
In [174]: read_pickle('foo.pkl')
0 1 2
0 0.569605 0.875906 -2.211372
1 0.974466 -2.006747 -0.410001
2 -0.078638 0.545952 -1.219217
3 -1.226825 0.769804 -1.281247
4 -0.727707 -0.121306 -0.097883
Warning
Loading pickled data received from untrusted sources can be unsafe.
Note
These methods were previously save and load, now deprecated.
Excel files¶
The read_excel method can read Excel 2003 (.xls) and Excel 2007 (.xlsx) files using the xlrd Python module and use the same parsing code as the above to convert tabular data into a DataFrame. See the cookbook for some advanced strategies
Note
The prior method of accessing Excel is now deprecated as of 0.12, this will work but 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'])
Replaced by
read_excel('path_to_file.xls', 'Sheet1', index_col=None, na_values=['NA'])
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. read_excel 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.
read_excel('path_to_file.xls', '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.
read_excel('path_to_file.xls', 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 using the high performance HDF5 format using the excellent PyTables library. See the cookbook for some advanced strategies
Note
PyTables 3.0.0 was recently released to enables support for Python 3. Pandas should be fully compatible (and previously written stores should be backwards compatible) with all PyTables >= 2.3
In [175]: store = HDFStore('store.h5')
In [176]: 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 [177]: index = date_range('1/1/2000', periods=8)
In [178]: s = Series(randn(5), index=['a', 'b', 'c', 'd', 'e'])
In [179]: df = DataFrame(randn(8, 3), index=index,
.....: columns=['A', 'B', 'C'])
.....:
In [180]: 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 [181]: store['s'] = s
In [182]: store['df'] = df
In [183]: store['wp'] = wp
# the type of stored data
In [184]: store.root.wp._v_attrs.pandas_type
'wide'
In [185]: store
<class 'pandas.io.pytables.HDFStore'>
File path: store.h5
/df frame (shape->[8,3])
/s series (shape->[5])
/wp wide (shape->[2,5,4])
In a current or later Python session, you can retrieve stored objects:
# store.get('df') is an equivalent method
In [186]: store['df']
A B C
2000-01-01 0.149748 -0.732339 0.687738
2000-01-02 0.176444 0.403310 -0.154951
2000-01-03 0.301624 -2.179861 -1.369849
2000-01-04 -0.954208 1.462696 -1.743161
2000-01-05 -0.826591 -0.345352 1.314232
2000-01-06 0.690579 0.995761 2.396780
2000-01-07 0.014871 3.357427 -0.317441
2000-01-08 -1.236269 0.896171 -0.487602
# dotted (attribute) access provides get as well
In [187]: store.df
A B C
2000-01-01 0.149748 -0.732339 0.687738
2000-01-02 0.176444 0.403310 -0.154951
2000-01-03 0.301624 -2.179861 -1.369849
2000-01-04 -0.954208 1.462696 -1.743161
2000-01-05 -0.826591 -0.345352 1.314232
2000-01-06 0.690579 0.995761 2.396780
2000-01-07 0.014871 3.357427 -0.317441
2000-01-08 -1.236269 0.896171 -0.487602
Deletion of the object specified by the key
# store.remove('wp') is an equivalent method
In [188]: del store['wp']
In [189]: store
<class 'pandas.io.pytables.HDFStore'>
File path: store.h5
/df frame (shape->[8,3])
/s series (shape->[5])
Closing a Store, Context Manager
# closing a store
In [190]: store.close()
# Working with, and automatically closing the store with the context
# manager
In [191]: with get_store('store.h5') as store:
.....: store.keys()
.....:
Read/Write API¶
HDFStore supports an top-level API using read_hdf for reading and to_hdf for writing, similar to how read_csv and to_csv work. (new in 0.11.0)
In [192]: df_tl = DataFrame(dict(A=range(5), B=range(5)))
In [193]: df_tl.to_hdf('store_tl.h5','table',append=True)
In [194]: read_hdf('store_tl.h5', 'table', where = ['index>2'])
A B
3 3 3
4 4 4
Storer Format¶
The examples above show storing using put, which write the HDF5 to PyTables in a fixed array format, called the storer format. These types of stores are are not appendable once written (though you can simply remove them and rewrite). Nor are they queryable; they must be retrieved in their entirety. These offer very fast writing and slightly faster reading than table stores.
Warning
A storer format will raise a TypeError if you try to retrieve using a where .
DataFrame(randn(10,2)).to_hdf('test_storer.h5','df')
pd.read_hdf('test_storer.h5','df',where='index>5')
TypeError: cannot pass a where specification when reading a non-table
this store must be selected in its entirety
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 [195]: store = HDFStore('store.h5')
In [196]: df1 = df[0:4]
In [197]: df2 = df[4:]
# append data (creates a table automatically)
In [198]: store.append('df', df1)
In [199]: store.append('df', df2)
In [200]: store
<class 'pandas.io.pytables.HDFStore'>
File path: store.h5
/df frame_table (typ->appendable,nrows->8,ncols->3,indexers->[index])
# select the entire object
In [201]: store.select('df')
A B C
2000-01-01 0.149748 -0.732339 0.687738
2000-01-02 0.176444 0.403310 -0.154951
2000-01-03 0.301624 -2.179861 -1.369849
2000-01-04 -0.954208 1.462696 -1.743161
2000-01-05 -0.826591 -0.345352 1.314232
2000-01-06 0.690579 0.995761 2.396780
2000-01-07 0.014871 3.357427 -0.317441
2000-01-08 -1.236269 0.896171 -0.487602
# the type of stored data
In [202]: store.root.df._v_attrs.pandas_type
'frame_table'
Note
You can also create a table by passing table=True to a put operation.
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 [203]: store.put('foo/bar/bah', df)
In [204]: store.append('food/orange', df)
In [205]: store.append('food/apple', df)
In [206]: store
<class 'pandas.io.pytables.HDFStore'>
File path: store.h5
/df frame_table (typ->appendable,nrows->8,ncols->3,indexers->[index])
/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])
# a list of keys are returned
In [207]: store.keys()
['/df', '/food/apple', '/food/orange', '/foo/bar/bah']
# remove all nodes under this level
In [208]: store.remove('food')
In [209]: store
<class 'pandas.io.pytables.HDFStore'>
File path: store.h5
/df frame_table (typ->appendable,nrows->8,ncols->3,indexers->[index])
/foo/bar/bah frame (shape->[8,3])
Storing Mixed Types in a Table¶
Storing mixed-dtype data is supported. Strings are stored 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, datetime64 are currently supported. For string columns, passing nan_rep = 'nan' to append will change the default nan representation on disk (which converts to/from np.nan), this defaults to nan.
In [210]: df_mixed = DataFrame({ 'A' : randn(8),
.....: 'B' : randn(8),
.....: 'C' : np.array(randn(8),dtype='float32'),
.....: 'string' :'string',
.....: 'int' : 1,
.....: 'bool' : True,
.....: 'datetime64' : Timestamp('20010102')},
.....: index=range(8))
.....:
In [211]: df_mixed.ix[3:5,['A', 'B', 'string', 'datetime64']] = np.nan
In [212]: store.append('df_mixed', df_mixed, min_itemsize = {'values': 50})
In [213]: df_mixed1 = store.select('df_mixed')
In [214]: df_mixed1
A B C bool datetime64 int string
0 -0.064034 -0.744471 1.682706 True 2001-01-02 00:00:00 1 string
1 -1.282782 0.758527 -1.717693 True 2001-01-02 00:00:00 1 string
2 0.781836 1.729689 0.888782 True 2001-01-02 00:00:00 1 string
3 NaN NaN 0.228440 True NaT 1 NaN
4 NaN NaN 0.901805 True NaT 1 NaN
5 NaN NaN 1.171216 True NaT 1 NaN
6 0.583787 1.846883 0.520260 True 2001-01-02 00:00:00 1 string
7 0.221471 -1.328865 -1.197071 True 2001-01-02 00:00:00 1 string
In [215]: df_mixed1.get_dtype_counts()
bool 1
datetime64[ns] 1
float32 1
float64 2
int64 1
object 1
dtype: int64
# we have provided a minimum string column size
In [216]: store.root.df_mixed.table
/df_mixed/table (Table(8,)) ''
description := {
"index": Int64Col(shape=(), dflt=0, pos=0),
"values_block_0": Float64Col(shape=(2,), dflt=0.0, pos=1),
"values_block_1": Float32Col(shape=(1,), dflt=0.0, pos=2),
"values_block_2": Int64Col(shape=(1,), dflt=0, pos=3),
"values_block_3": Int64Col(shape=(1,), dflt=0, pos=4),
"values_block_4": BoolCol(shape=(1,), dflt=False, pos=5),
"values_block_5": StringCol(itemsize=50, shape=(1,), dflt='', pos=6)}
byteorder := 'little'
chunkshape := (689,)
autoindex := True
colindexes := {
"index": Index(6, medium, shuffle, zlib(1)).is_csi=False}
Storing Multi-Index DataFrames¶
Storing multi-index dataframes as tables is very similar to storing/selecting from homogeneous index DataFrames.
In [217]: 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 [218]: df_mi = DataFrame(np.random.randn(10, 3), index=index,
.....: columns=['A', 'B', 'C'])
.....:
In [219]: df_mi
A B C
foo bar
foo one -1.066969 -0.303421 -0.858447
two 0.306996 -0.028665 0.384316
three 1.574159 1.588931 0.476720
bar one 0.473424 -0.242861 -0.014805
two -0.284319 0.650776 -1.461665
baz two -1.137707 -0.891060 -0.693921
three 1.613616 0.464000 0.227371
qux one -0.496922 0.306389 -2.290613
two -1.134623 -1.561819 -0.260838
three 0.281957 1.523962 -0.902937
In [220]: store.append('df_mi',df_mi)
In [221]: store.select('df_mi')
A B C
foo bar
foo one -1.066969 -0.303421 -0.858447
two 0.306996 -0.028665 0.384316
three 1.574159 1.588931 0.476720
bar one 0.473424 -0.242861 -0.014805
two -0.284319 0.650776 -1.461665
baz two -1.137707 -0.891060 -0.693921
three 1.613616 0.464000 0.227371
qux one -0.496922 0.306389 -2.290613
two -1.134623 -1.561819 -0.260838
three 0.281957 1.523962 -0.902937
# the levels are automatically included as data columns
In [222]: store.select('df_mi', Term('foo=bar'))
A B C
foo bar
bar one 0.473424 -0.242861 -0.014805
two -0.284319 0.650776 -1.461665
Querying a Table¶
select and delete operations have an optional criterion 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 [223]: store.append('wp',wp)
In [224]: store
<class 'pandas.io.pytables.HDFStore'>
File path: store.h5
/df frame_table (typ->appendable,nrows->8,ncols->3,indexers->[index])
/df_mi frame_table (typ->appendable_multi,nrows->10,ncols->5,indexers->[index],dc->[bar,foo])
/df_mixed frame_table (typ->appendable,nrows->8,ncols->7,indexers->[index])
/wp wide_table (typ->appendable,nrows->20,ncols->2,indexers->[major_axis,minor_axis])
/foo/bar/bah frame (shape->[8,3])
In [225]: 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
The columns keyword can be supplied to select a list of columns to be returned, this is equivalent to passing a Term('columns', list_of_columns_to_filter):
In [226]: store.select('df', columns=['A', 'B'])
A B
2000-01-01 0.149748 -0.732339
2000-01-02 0.176444 0.403310
2000-01-03 0.301624 -2.179861
2000-01-04 -0.954208 1.462696
2000-01-05 -0.826591 -0.345352
2000-01-06 0.690579 0.995761
2000-01-07 0.014871 3.357427
2000-01-08 -1.236269 0.896171
start and stop parameters can be specified to limit the total search space. These are in terms of the total number of rows in a table.
# this is effectively what the storage of a Panel looks like
In [227]: wp.to_frame()
Item1 Item2
major minor
2000-01-01 A -0.082240 0.408204
B -2.182937 -1.048089
C 0.380396 -0.025747
D 0.084844 -0.988387
2000-01-02 A 0.432390 0.094055
B 1.519970 1.262731
C -0.493662 1.289997
D 0.600178 0.082423
2000-01-03 A 0.274230 -0.055758
B 0.132885 0.536580
C -0.023688 -0.489682
D 2.410179 0.369374
2000-01-04 A 1.450520 -0.034571
B 0.206053 -2.484478
C -0.251905 -0.281461
D -2.213588 0.030711
2000-01-05 A 1.063327 0.109121
B 1.266143 1.126203
C 0.299368 -0.977349
D -0.863838 1.474071
# limiting the search
In [228]: store.select('wp',[ Term('major_axis>20000102'),
.....: Term('minor_axis', '=', ['A','B']) ],
.....: start=0, stop=10)
.....:
<class 'pandas.core.panel.Panel'>
Dimensions: 2 (items) x 1 (major_axis) x 2 (minor_axis)
Items axis: Item1 to Item2
Major_axis axis: 2000-01-03 00:00:00 to 2000-01-03 00:00:00
Minor_axis axis: A to B
Indexing¶
You can create/modify 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. Indexes are automagically created (starting 0.10.1) on the indexables and any data columns you specify. This behavior can be turned off by passing index=False to append.
# we have automagically already created an index (in the first section)
In [229]: i = store.root.df.table.cols.index.index
In [230]: i.optlevel, i.kind
(6, 'medium')
# change an index by passing new parameters
In [231]: store.create_table_index('df', optlevel=9, kind='full')
In [232]: i = store.root.df.table.cols.index.index
In [233]: i.optlevel, i.kind
(9, 'full')
Query via Data Columns¶
You can designate (and index) certain columns that you want to be able to perform queries (other than the indexable columns, which you can always query). For instance say you want to perform this common operation, on-disk, and return just the frame that matches this query. You can specify data_columns = True to force all columns to be data_columns
In [234]: df_dc = df.copy()
In [235]: df_dc['string'] = 'foo'
In [236]: df_dc.ix[4:6,'string'] = np.nan
In [237]: df_dc.ix[7:9,'string'] = 'bar'
In [238]: df_dc['string2'] = 'cool'
In [239]: df_dc
A B C string string2
2000-01-01 0.149748 -0.732339 0.687738 foo cool
2000-01-02 0.176444 0.403310 -0.154951 foo cool
2000-01-03 0.301624 -2.179861 -1.369849 foo cool
2000-01-04 -0.954208 1.462696 -1.743161 foo cool
2000-01-05 -0.826591 -0.345352 1.314232 NaN cool
2000-01-06 0.690579 0.995761 2.396780 NaN cool
2000-01-07 0.014871 3.357427 -0.317441 foo cool
2000-01-08 -1.236269 0.896171 -0.487602 bar cool
# on-disk operations
In [240]: store.append('df_dc', df_dc, data_columns = ['B', 'C', 'string', 'string2'])
In [241]: store.select('df_dc', [ Term('B>0') ])
A B C string string2
2000-01-02 0.176444 0.403310 -0.154951 foo cool
2000-01-04 -0.954208 1.462696 -1.743161 foo cool
2000-01-06 0.690579 0.995761 2.396780 NaN cool
2000-01-07 0.014871 3.357427 -0.317441 foo cool
2000-01-08 -1.236269 0.896171 -0.487602 bar cool
# getting creative
In [242]: store.select('df_dc', ['B > 0', 'C > 0', 'string == foo'])
Empty DataFrame
Columns: [A, B, C, string, string2]
Index: []
# this is in-memory version of this type of selection
In [243]: df_dc[(df_dc.B > 0) & (df_dc.C > 0) & (df_dc.string == 'foo')]
Empty DataFrame
Columns: [A, B, C, string, string2]
Index: []
# we have automagically created this index and the B/C/string/string2
# columns are stored separately as ``PyTables`` columns
In [244]: store.root.df_dc.table
/df_dc/table (Table(8,)) ''
description := {
"index": Int64Col(shape=(), dflt=0, pos=0),
"values_block_0": Float64Col(shape=(1,), dflt=0.0, pos=1),
"B": Float64Col(shape=(), dflt=0.0, pos=2),
"C": Float64Col(shape=(), dflt=0.0, pos=3),
"string": StringCol(itemsize=3, shape=(), dflt='', pos=4),
"string2": StringCol(itemsize=4, shape=(), dflt='', pos=5)}
byteorder := 'little'
chunkshape := (1680,)
autoindex := True
colindexes := {
"index": Index(6, medium, shuffle, zlib(1)).is_csi=False,
"C": Index(6, medium, shuffle, zlib(1)).is_csi=False,
"B": Index(6, medium, shuffle, zlib(1)).is_csi=False,
"string2": Index(6, medium, shuffle, zlib(1)).is_csi=False,
"string": Index(6, medium, shuffle, zlib(1)).is_csi=False}
There is some performance degredation by making lots of columns into data columns, so it is up to the user to designate these. In addition, you cannot change data columns (nor indexables) after the first append/put operation (Of course you can simply read in the data and create a new table!)
Iterator¶
Starting in 0.11, you can pass, iterator=True or chunksize=number_in_a_chunk to select and select_as_multiple to return an iterator on the results. The default is 50,000 rows returned in a chunk.
In [245]: for df in store.select('df', chunksize=3):
.....: print df
.....:
A B C
2000-01-01 0.149748 -0.732339 0.687738
2000-01-02 0.176444 0.403310 -0.154951
2000-01-03 0.301624 -2.179861 -1.369849
A B C
2000-01-04 -0.954208 1.462696 -1.743161
2000-01-05 -0.826591 -0.345352 1.314232
2000-01-06 0.690579 0.995761 2.396780
A B C
2000-01-07 0.014871 3.357427 -0.317441
2000-01-08 -1.236269 0.896171 -0.487602
Note
New in version 0.12.
You can also use the iterator with read_hdf which will open, then automatically close the store when finished iterating.
for df in read_hdf('store.h5','df', chunsize=3):
print df
Note, that the chunksize keyword applies to the returned rows. So if you are doing a query, then that set will be subdivided and returned in the iterator. Keep in mind that if you do not pass a where selection criteria then the nrows of the table are considered.
Advanced Queries¶
Select a Single Column
To retrieve a single indexable or data column, use the method select_column. This will, for example, enable you to get the index very quickly. These return a Series of the result, indexed by the row number. These do not currently accept the where selector (coming soon)
In [246]: store.select_column('df_dc', 'index')
0 2000-01-01 00:00:00
1 2000-01-02 00:00:00
2 2000-01-03 00:00:00
3 2000-01-04 00:00:00
4 2000-01-05 00:00:00
5 2000-01-06 00:00:00
6 2000-01-07 00:00:00
7 2000-01-08 00:00:00
dtype: datetime64[ns]
In [247]: store.select_column('df_dc', 'string')
0 foo
1 foo
2 foo
3 foo
4 NaN
5 NaN
6 foo
7 bar
dtype: object
Replicating or
not and or conditions are unsupported at this time; however, or operations are easy to replicate, by repeatedly applying the criteria to the table, and then concat the results.
In [248]: crit1 = [ Term('B>0'), Term('C>0'), Term('string=foo') ]
In [249]: crit2 = [ Term('B<0'), Term('C>0'), Term('string=foo') ]
In [250]: concat([store.select('df_dc',c) for c in [crit1, crit2]])
A B C string string2
2000-01-01 0.149748 -0.732339 0.687738 foo cool
Storer Object
If you want to inspect the stored object, retrieve via get_storer. You could use this programmatically to say get the number of rows in an object.
In [251]: store.get_storer('df_dc').nrows
8
Multiple Table Queries¶
New in 0.10.1 are the methods append_to_multiple and select_as_multiple, that can perform appending/selecting from multiple tables at once. The idea is to have one table (call it the selector table) that you index most/all of the columns, and perform your queries. The other table(s) are data tables with an index matching the selector table’s index. You can then perform a very fast query on the selector table, yet get lots of data back. This method works similar to having a very wide table, but is more efficient in terms of queries.
Note, THE USER IS RESPONSIBLE FOR SYNCHRONIZING THE TABLES. This means, append to the tables in the same order; append_to_multiple splits a single object to multiple tables, given a specification (as a dictionary). This dictionary is a mapping of the table names to the ‘columns’ you want included in that table. Pass a None for a single table (optional) to let it have the remaining columns. The argument selector defines which table is the selector table.
In [252]: df_mt = DataFrame(randn(8, 6), index=date_range('1/1/2000', periods=8),
.....: columns=['A', 'B', 'C', 'D', 'E', 'F'])
.....:
In [253]: df_mt['foo'] = 'bar'
# you can also create the tables individually
In [254]: store.append_to_multiple({'df1_mt': ['A', 'B'], 'df2_mt': None },
.....: df_mt, selector='df1_mt')
.....:
In [255]: store
<class 'pandas.io.pytables.HDFStore'>
File path: store.h5
/df frame_table (typ->appendable,nrows->8,ncols->3,indexers->[index])
/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_dc frame_table (typ->appendable,nrows->8,ncols->5,indexers->[index],dc->[B,C,string,string2])
/df_mi frame_table (typ->appendable_multi,nrows->10,ncols->5,indexers->[index],dc->[bar,foo])
/df_mixed frame_table (typ->appendable,nrows->8,ncols->7,indexers->[index])
/wp wide_table (typ->appendable,nrows->20,ncols->2,indexers->[major_axis,minor_axis])
/foo/bar/bah frame (shape->[8,3])
# indiviual tables were created
In [256]: store.select('df1_mt')
A B
2000-01-01 0.068159 -0.057873
2000-01-02 0.782098 -1.069094
2000-01-03 0.379319 -0.008434
2000-01-04 0.040403 -0.507516
2000-01-05 1.488753 -0.896484
2000-01-06 2.121453 0.597701
2000-01-07 -0.928797 -0.308853
2000-01-08 -1.553902 2.015523
In [257]: store.select('df2_mt')
C D E F foo
2000-01-01 -0.368204 -1.144073 0.861209 0.800193 bar
2000-01-02 -1.099248 0.255269 0.009750 0.661084 bar
2000-01-03 1.952541 -1.056652 0.533946 -1.226970 bar
2000-01-04 -0.230096 0.394500 -1.934370 -1.652499 bar
2000-01-05 0.576897 1.146000 1.487349 0.604603 bar
2000-01-06 0.563700 0.967661 -1.057909 1.375020 bar
2000-01-07 -0.681087 0.377953 0.493672 -2.461467 bar
2000-01-08 -1.833722 1.771740 -0.670027 0.049307 bar
# as a multiple
In [258]: 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-06 2.121453 0.597701 0.5637 0.967661 -1.057909 1.37502 bar
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 performance, it’s worthwhile 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 [259]: store.remove('wp', 'major_axis>20000102' )
12
In [260]: store.select('wp')
<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
Please note that HDF5 DOES NOT RECLAIM SPACE in the h5 files automatically. Thus, repeatedly deleting (or removing nodes) and adding again WILL TEND TO INCREASE THE FILE SIZE. To clean the file, use ptrepack (see below).
Compression¶
PyTables allows the stored data to be compressed. Tthis applies to all kinds of stores, not just tables.
- Pass complevel=int for a compression level (1-9, with 0 being no compression, and the default)
- Pass complib=lib where lib is any of zlib, bzip2, lzo, blosc for whichever compression library you prefer.
HDFStore will use the file based compression scheme if no overriding complib or complevel options are provided. blosc offers very fast compression, and is my most used. Note that lzo and bzip2 may not be installed (by Python) by default.
Compression for all objects within the file
- store_compressed = HDFStore('store_compressed.h5', complevel=9, complib='blosc')
Or on-the-fly compression (this only applies to tables). You can turn off file compression for a specific table by passing complevel=0
- store.append('df', df, complib='zlib', complevel=5)
ptrepack
PyTables offers better write performance when tables are compressed after they are written, as opposed to turning on compression at the very beginning. You can use the supplied PyTables utility ptrepack. In addition, ptrepack can change compression levels after the fact.
- ptrepack --chunkshape=auto --propindexes --complevel=9 --complib=blosc in.h5 out.h5
Furthermore ptrepack in.h5 out.h5 will repack the file to allow you to reuse previously deleted space. Aalternatively, one can simply remove the file and write again, or use the copy method.
Notes & Caveats¶
- Once a table is created its items (Panel) / columns (DataFrame) are fixed; only exactly the same columns can be appended
- If a row has np.nan for EVERY COLUMN (having a nan in a string, or a NaT in a datetime-like column counts as having a value), then those rows WILL BE DROPPED IMPLICITLY. This limitation may be addressed in the future.
- 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
DataTypes¶
HDFStore will map an object dtype to the PyTables underlying dtype. This means the following types are known to work:
- floating : float64, float32, float16 (using np.nan to represent invalid values)
- integer : int64, int32, int8, uint64, uint32, uint8
- bool
- datetime64[ns] (using NaT to represent invalid values)
- object : strings (using np.nan to represent invalid values)
Currently, unicode and datetime columns (represented with a dtype of object), WILL FAIL. In addition, even though a column may look like a datetime64[ns], if it contains np.nan, this WILL FAIL. You can try to convert datetimelike columns to proper datetime64[ns] columns, that possibily contain NaT to represent invalid values. (Some of these issues have been addressed and these conversion may not be necessary in future versions of pandas)
In [261]: import datetime In [262]: df = DataFrame(dict(datelike=Series([datetime.datetime(2001, 1, 1), .....: datetime.datetime(2001, 1, 2), np.nan]))) .....: In [263]: df datelike 0 2001-01-01 00:00:00 1 2001-01-02 00:00:00 2 NaN In [264]: df.dtypes datelike object dtype: object # to convert In [265]: df['datelike'] = Series(df['datelike'].values, dtype='M8[ns]') In [266]: df datelike 0 2001-01-01 00:00:00 1 2001-01-02 00:00:00 2 NaT In [267]: df.dtypes datelike datetime64[ns] dtype: object
String Columns¶
The underlying implementation of HDFStore uses a fixed column width (itemsize) for string columns. A string column itemsize is calculated as the maximum of the length of data (for that column) that is passed to the HDFStore, in the first append. Subsequent appends, may introduce a string for a column larger than the column can hold, an Exception will be raised (otherwise you could have a silent truncation of these columns, leading to loss of information). In the future we may relax this and allow a user-specified truncation to occur.
Pass min_itemsize on the first table creation to a-priori specifiy the minimum length of a particular string column. min_itemsize can be an integer, or a dict mapping a column name to an integer. You can pass values as a key to allow all indexables or data_columns to have this min_itemsize.
Starting in 0.11, passing a min_itemsize dict will cause all passed columns to be created as data_columns automatically.
Note
If you are not passing any data_columns, then the min_itemsize will be the maximum of the length of any string passed
In [268]: dfs = DataFrame(dict(A = 'foo', B = 'bar'),index=range(5))
In [269]: dfs
A B
0 foo bar
1 foo bar
2 foo bar
3 foo bar
4 foo bar
# A and B have a size of 30
In [270]: store.append('dfs', dfs, min_itemsize = 30)
In [271]: store.get_storer('dfs').table
/dfs/table (Table(5,)) ''
description := {
"index": Int64Col(shape=(), dflt=0, pos=0),
"values_block_0": StringCol(itemsize=30, shape=(2,), dflt='', pos=1)}
byteorder := 'little'
chunkshape := (963,)
autoindex := True
colindexes := {
"index": Index(6, medium, shuffle, zlib(1)).is_csi=False}
# A is created as a data_column with a size of 30
# B is size is calculated
In [272]: store.append('dfs2', dfs, min_itemsize = { 'A' : 30 })
In [273]: store.get_storer('dfs2').table
/dfs2/table (Table(5,)) ''
description := {
"index": Int64Col(shape=(), dflt=0, pos=0),
"values_block_0": StringCol(itemsize=3, shape=(1,), dflt='', pos=1),
"A": StringCol(itemsize=30, shape=(), dflt='', pos=2)}
byteorder := 'little'
chunkshape := (1598,)
autoindex := True
colindexes := {
"A": Index(6, medium, shuffle, zlib(1)).is_csi=False,
"index": Index(6, medium, shuffle, zlib(1)).is_csi=False}
External Compatibility¶
HDFStore write storer objects in specific formats suitable for producing loss-less roundtrips to pandas objects. For external compatibility, HDFStore can read native PyTables format tables. It is possible to write an HDFStore object that can easily be imported into R using the rhdf5 library. Create a table format store like this:
In [274]: store_export = HDFStore('export.h5') In [275]: store_export.append('df_dc', df_dc, data_columns=df_dc.columns) In [276]: store_export <class 'pandas.io.pytables.HDFStore'> File path: export.h5 /df_dc frame_table (typ->appendable,nrows->8,ncols->5,indexers->[index],dc->[A,B,C,string,string2])
Backwards Compatibility¶
0.10.1 of HDFStore can read 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 legacy-format file. You must read in the entire file and write it out using the new format, using the method copy to take advantage of the updates. The group attribute pandas_version contains the version information. copy takes a number of options, please see the docstring.
# a legacy store In [277]: legacy_store = HDFStore(legacy_file_path,'r') In [278]: legacy_store <class 'pandas.io.pytables.HDFStore'> File path: /home/docbuild/CI/pandas/doc/source/_static/legacy_0.10.h5 /a series (shape->[30]) /b frame (shape->[30,4]) /df1_mixed frame_table [0.10.0] (typ->appendable,nrows->30,ncols->11,indexers->[index]) /p1_mixed wide_table [0.10.0] (typ->appendable,nrows->120,ncols->9,indexers->[major_axis,minor_axis]) /p4d_mixed ndim_table [0.10.0] (typ->appendable,nrows->360,ncols->9,indexers->[items,major_axis,minor_axis]) /foo/bar wide (shape->[3,30,4]) # copy (and return the new handle) In [279]: new_store = legacy_store.copy('store_new.h5') In [280]: new_store <class 'pandas.io.pytables.HDFStore'> File path: store_new.h5 /a series (shape->[30]) /b frame (shape->[30,4]) /df1_mixed frame_table (typ->appendable,nrows->30,ncols->11,indexers->[index]) /p1_mixed wide_table (typ->appendable,nrows->120,ncols->9,indexers->[major_axis,minor_axis]) /p4d_mixed wide_table (typ->appendable,nrows->360,ncols->9,indexers->[items,major_axis,minor_axis]) /foo/bar wide (shape->[3,30,4]) In [281]: new_store.close()
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.
- You can pass chunksize=<int> to append, specifying the write chunksize (default is 50000). This will signficantly lower your memory usage on writing.
- You can pass expectedrows=<int> to the first append, to set the TOTAL number of expected rows that PyTables will expected. This will optimize read/write performance.
- Duplicate rows can be written to tables, but are filtered out in selection (with the last items being selected; thus a table is unique on major, minor pairs)
- A PerformanceWarning will be raised if you are attempting to store types that will be pickled by PyTables (rather than stored as endemic types). See <http://stackoverflow.com/questions/14355151/how-to-make-pandas-hdfstore-put-operation-faster/14370190#14370190> for more information and some solutions.
Experimental¶
HDFStore supports Panel4D storage.
In [282]: p4d = Panel4D({ 'l1' : wp })
In [283]: p4d
<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 to D
In [284]: store.append('p4d', p4d)
In [285]: store
<class 'pandas.io.pytables.HDFStore'>
File path: store.h5
/df frame_table (typ->appendable,nrows->8,ncols->3,indexers->[index])
/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_dc frame_table (typ->appendable,nrows->8,ncols->5,indexers->[index],dc->[B,C,string,string2])
/df_mi frame_table (typ->appendable_multi,nrows->10,ncols->5,indexers->[index],dc->[bar,foo])
/df_mixed frame_table (typ->appendable,nrows->8,ncols->7,indexers->[index])
/dfs frame_table (typ->appendable,nrows->5,ncols->2,indexers->[index])
/dfs2 frame_table (typ->appendable,nrows->5,ncols->2,indexers->[index],dc->[A])
/p4d wide_table (typ->appendable,nrows->40,ncols->1,indexers->[items,major_axis,minor_axis])
/wp wide_table (typ->appendable,nrows->8,ncols->2,indexers->[major_axis,minor_axis])
/foo/bar/bah frame (shape->[8,3])
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 dimensions (currently must by exactly 1 less than the total dimensions of the object). This cannot be changed after table creation.
In [286]: store.append('p4d2', p4d, axes=['labels', 'major_axis', 'minor_axis'])
In [287]: store
<class 'pandas.io.pytables.HDFStore'>
File path: store.h5
/df frame_table (typ->appendable,nrows->8,ncols->3,indexers->[index])
/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_dc frame_table (typ->appendable,nrows->8,ncols->5,indexers->[index],dc->[B,C,string,string2])
/df_mi frame_table (typ->appendable_multi,nrows->10,ncols->5,indexers->[index],dc->[bar,foo])
/df_mixed frame_table (typ->appendable,nrows->8,ncols->7,indexers->[index])
/dfs frame_table (typ->appendable,nrows->5,ncols->2,indexers->[index])
/dfs2 frame_table (typ->appendable,nrows->5,ncols->2,indexers->[index],dc->[A])
/p4d wide_table (typ->appendable,nrows->40,ncols->1,indexers->[items,major_axis,minor_axis])
/p4d2 wide_table (typ->appendable,nrows->20,ncols->2,indexers->[labels,major_axis,minor_axis])
/wp wide_table (typ->appendable,nrows->8,ncols->2,indexers->[major_axis,minor_axis])
/foo/bar/bah frame (shape->[8,3])
In [288]: store.select('p4d2', [ Term('labels=l1'), Term('items=Item1'), Term('minor_axis=A_big_strings') ])
<class 'pandas.core.panelnd.Panel4D'>
Dimensions: 0 (labels) x 1 (items) x 0 (major_axis) x 0 (minor_axis)
Labels axis: None
Items axis: Item1 to Item1
Major_axis axis: None
Minor_axis axis: None
SQL Queries¶
The pandas.io.sql module provides a collection of query wrappers to both facilitate data retrieval and to reduce dependency on DB-specific API. These wrappers only support the Python database adapters which respect the Python DB-API. See some cookbook examples for some advanced strategies
For example, suppose you want to query some data with different types from a table such as:
id | Date | Col_1 | Col_2 | Col_3 |
---|---|---|---|---|
26 | 2012-10-18 | X | 25.7 | True |
42 | 2012-10-19 | Y | -12.4 | False |
63 | 2012-10-20 | Z | 5.73 | True |
Functions from pandas.io.sql can extract some data into a DataFrame. In the following example, we use the SQlite SQL database engine. You can use a temporary SQLite database where data are stored in “memory”. Just do:
import sqlite3
from pandas.io import sql
# Create your connection.
cnx = sqlite3.connect(':memory:')
Let data be the name of your SQL table. With a query and your database connection, just use the read_frame() function to get the query results into a DataFrame:
In [289]: sql.read_frame("SELECT * FROM data;", cnx)
id date Col_1 Col_2 Col_3
0 26 2010-10-18 00:00:00 X 27.50 1
1 42 2010-10-19 00:00:00 Y -12.50 0
2 63 2010-10-20 00:00:00 Z 5.73 1
You can also specify the name of the column as the DataFrame index:
In [290]: sql.read_frame("SELECT * FROM data;", cnx, index_col='id')
date Col_1 Col_2 Col_3
id
26 2010-10-18 00:00:00 X 27.50 1
42 2010-10-19 00:00:00 Y -12.50 0
63 2010-10-20 00:00:00 Z 5.73 1
In [291]: sql.read_frame("SELECT * FROM data;", cnx, index_col='date')
id Col_1 Col_2 Col_3
date
2010-10-18 00:00:00 26 X 27.50 1
2010-10-19 00:00:00 42 Y -12.50 0
2010-10-20 00:00:00 63 Z 5.73 1
Of course, you can specify a more “complex” query.
In [292]: sql.read_frame("SELECT id, Col_1, Col_2 FROM data WHERE id = 42;", cnx)
id Col_1 Col_2
0 42 Y -12.5
There are a few other available functions:
- tquery returns a list of tuples corresponding to each row.
- uquery does the same thing as tquery, but instead of returning results it returns the number of related rows.
- write_frame writes records stored in a DataFrame into the SQL table.
- has_table checks if a given SQLite table exists.
Note
For now, writing your DataFrame into a database works only with SQLite. Moreover, the index will currently be dropped.
STATA Format¶
Writing to STATA format¶
The method to_stata() will write a DataFrame into a .dta file. The format version of this file is always the latest one, 115.
In [293]: df = DataFrame(randn(10, 2), columns=list('AB'))
In [294]: df.to_stata('stata.dta')
Reading from STATA format¶
New in version 0.12.
The top-level function read_stata will read a dta format file and return a DataFrame: The class StataReader will read the header of the given dta file at initialization. Its method data() will read the observations, converting them to a DataFrame which is returned:
In [295]: pd.read_stata('stata.dta')
index A B
0 0 -0.521493 -3.201750
1 1 0.792716 0.146111
2 2 1.903247 -0.747169
3 3 -0.309038 0.393876
4 4 1.861468 0.936527
5 5 1.255746 -2.655452
6 6 1.219492 0.062297
7 7 -0.110388 -1.184357
8 8 -0.558081 0.077849
9 9 0.629498 -1.035260
Currently the index is retrieved as a column on read back.
The parameter convert_categoricals indicates wheter value labels should be read and used to create a Categorical variable from them. Value labels can also be retrieved by the function variable_labels, which requires data to be called before (see pandas.io.stata.StataReader).
The StataReader supports .dta Formats 104, 105, 108, 113-115. Alternatively, the function read_stata() can be used
Data Reader¶
Functions from pandas.io.data extract data from various Internet sources into a DataFrame. Currently the following sources are supported:
- Yahoo! Finance
- Google Finance
- St. Louis FED (FRED)
- Kenneth French’s data library
It should be noted, that various sources support different kinds of data, so not all sources implement the same methods and the data elements returned might also differ.
Yahoo! Finance¶
In [296]: import pandas.io.data as web
In [297]: start = datetime.datetime(2010, 1, 1)
In [298]: end = datetime.datetime(2013, 01, 27)
In [299]: f=web.DataReader("F", 'yahoo', start, end)
In [300]: f.ix['2010-01-04']
Open 10.17
High 10.28
Low 10.05
Close 10.28
Volume 60855800.00
Adj Close 9.75
Name: 2010-01-04 00:00:00, dtype: float64
Google Finance¶
In [301]: import pandas.io.data as web
In [302]: start = datetime.datetime(2010, 1, 1)
In [303]: end = datetime.datetime(2013, 01, 27)
In [304]: f=web.DataReader("F", 'google', start, end)
In [305]: f.ix['2010-01-04']
Open 10.17
High 10.28
Low 10.05
Close 10.28
Volume 60855796
Name: 2010-01-04 00:00:00, dtype: object
FRED¶
In [306]: import pandas.io.data as web
In [307]: start = datetime.datetime(2010, 1, 1)
In [308]: end = datetime.datetime(2013, 01, 27)
In [309]: gdp=web.DataReader("GDP", "fred", start, end)
In [310]: gdp.ix['2013-01-01']
GDP 16535.3
Name: 2013-01-01 00:00:00, dtype: float64
Fama/French¶
Tthe dataset names are listed at Fama/French Data Library)
In [311]: import pandas.io.data as web
In [312]: ip=web.DataReader("5_Industry_Portfolios", "famafrench")
In [313]: ip[4].ix[192607]
1 Cnsmr 5.43
2 Manuf 2.73
3 HiTec 1.83
4 Hlth 1.64
5 Other 2.15
Name: 192607, dtype: float64