IO Tools (Text, CSV, HDF5, ...)¶
Clipboard¶
A handy way to grab data is to use the read_clipboard method, which takes the contents of the clipboard buffer and passes them to the read_table method described in the next section. For instance, you can copy the following text to the clipboard (CTRL-C on many operating systems):
A B C
x 1 4 p
y 2 5 q
z 3 6 r
And then import the data directly to a DataFrame by calling:
clipdf = read_clipboard(sep='\s*')
In [712]: clipdf
Out[712]:
A B C
x 1 4 p
y 2 5 q
z 3 6 r
CSV & Text files¶
The two workhorse functions for reading text files (a.k.a. flat files) are read_csv() and read_table(). They both use the same parsing code to intelligently convert tabular data into a DataFrame object. They can take a number of arguments:
- filepath_or_buffer: Either a string path to a file, or any object with a read method (such as an open file or StringIO).
- sep or delimiter: A delimiter / separator to split fields on. read_csv is capable of inferring the delimiter automatically in some cases by “sniffing.” The separator may be specified as a regular expression; for instance you may use ‘s*’ to indicate arbitrary whitespace.
- dialect: string or csv.Dialect instance to expose more ways to specify the file format
- header: row number to use as the column names, and the start of the data. Defaults to 0 (first row); specify None if there is no header row.
- 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. If passed, header will be implicitly set to None.
- na_values: optional list of strings to recognize as NaN (missing values), in addition to a default set. If you pass an empty list or an empty list for a particular column, no values (including empty strings) will be considered NA
- parse_dates: if True then index will be parsed as dates (False by default). You can specify more complicated options to parse a subset of columns or a combination of columns into a single date column (list of ints or names, list of lists, or dict) [1, 2, 3] -> try parsing columns 1, 2, 3 each as a separate date column [[1, 3]] -> combine columns 1 and 3 and parse as a single date column {‘foo’ : [1, 3]} -> parse columns 1, 3 as date and call result ‘foo’
- keep_date_col: if True, then date component columns passed into parse_dates will be retained in the output (False by default).
- date_parser: function to use to parse strings into datetime objects. If parse_dates is True, it defaults to the very robust dateutil.parser. Specifying this implicitly sets parse_dates as True. You can also use functions from community supported date converters from date_converters.py
- dayfirst: if True then uses the DD/MM international/European date format (This is False by default)
- thousands: sepcifies the thousands separator. If not None, then parser will try to look for it in the output and parse relevant data to integers. Because it has to essentially scan through the data again, this causes a significant performance hit so only use if necessary.
- comment: denotes the start of a comment and ignores the rest of the line. Currently line commenting is not supported.
- nrows: Number of rows to read out of the file. Useful to only read a small portion of a large file
- iterator: If True, return a TextParser to enable reading a file into memory piece by piece
- chunksize: An number of rows to be used to “chunk” a file into pieces. Will cause an TextParser object to be returned. More on this below in the section on iterating and chunking
- skip_footer: number of lines to skip at bottom of file (default 0)
- converters: a dictionary of functions for converting values in certain columns, where keys are either integers or column labels
- encoding: a string representing the encoding to use if the contents are non-ascii
- verbose: show number of NA values inserted in non-numeric columns
- squeeze: if True then output with only one column is turned into Series
Consider a typical CSV file containing, in this case, some time series data:
In [713]: 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 [714]: read_csv('foo.csv')
Out[714]:
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 [715]: read_csv('foo.csv', index_col=0)
Out[715]:
A B C
date
20090101 a 1 2
20090102 b 3 4
20090103 c 4 5
In [716]: read_csv('foo.csv', index_col='date')
Out[716]:
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 [717]: read_csv('foo.csv', index_col=[0, 'A'])
Out[717]:
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 [718]: 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 [719]: dia = csv.excel()
In [720]: dia.quoting = csv.QUOTE_NONE
In [721]: read_csv(StringIO(data), dialect=dia)
Out[721]:
label1 label2 label3
index1 "a c e
index2 b d f
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 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 [722]: df = read_csv('foo.csv', index_col=0, parse_dates=True)
In [723]: df
Out[723]:
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 [724]: df.index
Out[724]:
<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 [725]: 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 [726]: df = read_csv('tmp.csv', header=None, parse_dates=[[1, 2], [1, 3]])
In [727]: df
Out[727]:
X.2_X.3 X.2_X.4 X.1 X.5
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 [728]: df = read_csv('tmp.csv', header=None, parse_dates=[[1, 2], [1, 3]],
.....: keep_date_col=True)
.....:
In [729]: df
Out[729]:
X.2_X.3 X.2_X.4 X.1 X.2 X.3 X.4 X.5
0 1999-01-27 19:00:00 1999-01-27 18:56:00 KORD 19990127 19:00:00 18:56:00 0.81
1 1999-01-27 20:00:00 1999-01-27 19:56:00 KORD 19990127 20:00:00 19:56:00 0.01
2 1999-01-27 21:00:00 1999-01-27 20:56:00 KORD 19990127 21:00:00 20:56:00 -0.59
3 1999-01-27 21:00:00 1999-01-27 21:18:00 KORD 19990127 21:00:00 21:18:00 -0.99
4 1999-01-27 22:00:00 1999-01-27 21:56:00 KORD 19990127 22:00:00 21:56:00 -0.59
5 1999-01-27 23:00:00 1999-01-27 22:56:00 KORD 19990127 23:00:00 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 [730]: date_spec = {'nominal': [1, 2], 'actual': [1, 3]}
In [731]: df = read_csv('tmp.csv', header=None, parse_dates=date_spec)
In [732]: df
Out[732]:
nominal actual X.1 X.5
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
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 [733]: import pandas.io.date_converters as conv
In [734]: df = read_csv('tmp.csv', header=None, parse_dates=date_spec,
.....: date_parser=conv.parse_date_time)
.....:
In [735]: df
Out[735]:
nominal actual X.1 X.5
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 [736]: print open('tmp.csv').read()
date,value,cat
1/6/2000,5,a
2/6/2000,10,b
3/6/2000,15,c
In [737]: read_csv('tmp.csv', parse_dates=[0])
Out[737]:
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 [738]: read_csv('tmp.csv', dayfirst=True, parse_dates=[0])
Out[738]:
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 [739]: print open('tmp.csv').read()
ID|level|category
Patient1|123,000|x
Patient2|23,000|y
Patient3|1,234,018|z
In [740]: df = read_csv('tmp.csv', sep='|')
In [741]: df
Out[741]:
ID level category
0 Patient1 123,000 x
1 Patient2 23,000 y
2 Patient3 1,234,018 z
In [742]: df.level.dtype
Out[742]: dtype('object')
The thousands keyword allows integers to be parsed correctly
In [743]: print open('tmp.csv').read()
ID|level|category
Patient1|123,000|x
Patient2|23,000|y
Patient3|1,234,018|z
In [744]: df = read_csv('tmp.csv', sep='|', thousands=',')
In [745]: df
Out[745]:
ID level category
0 Patient1 123000 x
1 Patient2 23000 y
2 Patient3 1234018 z
In [746]: df.level.dtype
Out[746]: dtype('int64')
Comments¶
Sometimes comments or meta data may be included in a file:
In [747]: 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 [748]: df = read_csv('tmp.csv')
In [749]: df
Out[749]:
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 [750]: df = read_csv('tmp.csv', comment='#')
In [751]: df
Out[751]:
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 [752]: print open('tmp.csv').read()
level
Patient1,123000
Patient2,23000
Patient3,1234018
In [753]: output = read_csv('tmp.csv', squeeze=True)
In [754]: output
Out[754]:
Patient1 123000
Patient2 23000
Patient3 1234018
Name: level
In [755]: type(output)
Out[755]: pandas.core.series.Series
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 [756]: 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 [757]: colspecs = [(0, 6), (8, 20), (21, 33), (34, 43)]
In [758]: df = read_fwf('bar.csv', colspecs=colspecs, header=None, index_col=0)
In [759]: df
Out[759]:
X.2 X.3 X.4
X.1
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 [760]: widths = [6, 14, 13, 10]
In [761]: df = read_fwf('bar.csv', widths=widths, header=None)
In [762]: df
Out[762]:
X.1 X.2 X.3 X.4
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 [763]: 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 [764]: read_csv('foo.csv')
Out[764]:
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 [765]: df = read_csv('foo.csv', parse_dates=True)
In [766]: df.index
Out[766]:
<class 'pandas.tseries.index.DatetimeIndex'>
[2009-01-01 00:00:00, ..., 2009-01-03 00:00:00]
Length: 3, Freq: None, Timezone: None
Reading DataFrame objects with MultiIndex¶
Suppose you have data indexed by two columns:
In [767]: print open('data/mindex_ex.csv').read()
year,indiv,zit,xit
1977,"A",1.2,.6
1977,"B",1.5,.5
1977,"C",1.7,.8
1978,"A",.2,.06
1978,"B",.7,.2
1978,"C",.8,.3
1978,"D",.9,.5
1978,"E",1.4,.9
1979,"C",.2,.15
1979,"D",.14,.05
1979,"E",.5,.15
1979,"F",1.2,.5
1979,"G",3.4,1.9
1979,"H",5.4,2.7
1979,"I",6.4,1.2
The index_col argument to read_csv and read_table can take a list of column numbers to turn multiple columns into a MultiIndex:
In [768]: df = read_csv("data/mindex_ex.csv", index_col=[0,1])
In [769]: df
Out[769]:
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 [770]: df.ix[1978]
Out[770]:
zit xit
indiv
A 0.2 0.06
B 0.7 0.20
C 0.8 0.30
D 0.9 0.50
E 1.4 0.90
Automatically “sniffing” the delimiter¶
read_csv is capable of inferring delimited (not necessarily comma-separated) files. YMMV, as pandas uses the Sniffer class of the csv module.
In [771]: print open('tmp2.sv').read()
:0:1:2:3
0:0.46911229990718628:-0.28286334432866328:-1.5090585031735124:-1.1356323710171934
1:1.2121120250208506:-0.17321464905330858:0.11920871129693428:-1.0442359662799567
2:-0.86184896334779992:-2.1045692188948086:-0.49492927406878129:1.0718038070373379
3:0.72155516224436689:-0.70677113363008448:-1.0395749851146963:0.27185988554282986
4:-0.42497232978883753:0.567020349793672:0.27623201927771873:-1.0874006912859915
5:-0.67368970808837059:0.1136484096888855:-1.4784265524372235:0.52498766711470468
6:0.40470521868023651:0.57704598592048362:-1.7150020161146375:-1.0392684835147725
7:-0.37064685823644639:-1.1578922506419993:-1.3443118127316671:0.84488514142488413
8:1.0757697837155533:-0.10904997528022223:1.6435630703622064:-1.4693879595399115
9:0.35702056413309086:-0.67460010372998824:-1.7769037169718671:-0.96891381244734975
In [772]: read_csv('tmp2.sv')
Out[772]:
:0:1:2:3
0 0:0.46911229990718628:-0.28286334432866328:-1.509
1 1:1.2121120250208506:-0.17321464905330858:0.11920
2 2:-0.86184896334779992:-2.1045692188948086:-0.494
3 3:0.72155516224436689:-0.70677113363008448:-1.039
4 4:-0.42497232978883753:0.567020349793672:0.276232
5 5:-0.67368970808837059:0.1136484096888855:-1.4784
6 6:0.40470521868023651:0.57704598592048362:-1.7150
7 7:-0.37064685823644639:-1.1578922506419993:-1.344
8 8:1.0757697837155533:-0.10904997528022223:1.64356
9 9:0.35702056413309086:-0.67460010372998824:-1.776
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 [773]: print open('tmp.sv').read()
|0|1|2|3
0|0.46911229990718628|-0.28286334432866328|-1.5090585031735124|-1.1356323710171934
1|1.2121120250208506|-0.17321464905330858|0.11920871129693428|-1.0442359662799567
2|-0.86184896334779992|-2.1045692188948086|-0.49492927406878129|1.0718038070373379
3|0.72155516224436689|-0.70677113363008448|-1.0395749851146963|0.27185988554282986
4|-0.42497232978883753|0.567020349793672|0.27623201927771873|-1.0874006912859915
5|-0.67368970808837059|0.1136484096888855|-1.4784265524372235|0.52498766711470468
6|0.40470521868023651|0.57704598592048362|-1.7150020161146375|-1.0392684835147725
7|-0.37064685823644639|-1.1578922506419993|-1.3443118127316671|0.84488514142488413
8|1.0757697837155533|-0.10904997528022223|1.6435630703622064|-1.4693879595399115
9|0.35702056413309086|-0.67460010372998824|-1.7769037169718671|-0.96891381244734975
In [774]: table = read_table('tmp.sv', sep='|')
In [775]: table
Out[775]:
Unnamed: 0 0 1 2 3
0 0 0.469112 -0.282863 -1.509059 -1.135632
1 1 1.212112 -0.173215 0.119209 -1.044236
2 2 -0.861849 -2.104569 -0.494929 1.071804
3 3 0.721555 -0.706771 -1.039575 0.271860
4 4 -0.424972 0.567020 0.276232 -1.087401
5 5 -0.673690 0.113648 -1.478427 0.524988
6 6 0.404705 0.577046 -1.715002 -1.039268
7 7 -0.370647 -1.157892 -1.344312 0.844885
8 8 1.075770 -0.109050 1.643563 -1.469388
9 9 0.357021 -0.674600 -1.776904 -0.968914
By specifiying a chunksize to read_csv or read_table, the return value will be an iterable object of type TextParser:
In [776]: reader = read_table('tmp.sv', sep='|', chunksize=4)
In [777]: reader
Out[777]: <pandas.io.parsers.TextParser at 0x114b5ad90>
In [778]: for chunk in reader:
.....: print chunk
.....:
Unnamed: 0 0 1 2 3
0 0 0.469112 -0.282863 -1.509059 -1.135632
1 1 1.212112 -0.173215 0.119209 -1.044236
2 2 -0.861849 -2.104569 -0.494929 1.071804
3 3 0.721555 -0.706771 -1.039575 0.271860
Unnamed: 0 0 1 2 3
0 4 -0.424972 0.567020 0.276232 -1.087401
1 5 -0.673690 0.113648 -1.478427 0.524988
2 6 0.404705 0.577046 -1.715002 -1.039268
3 7 -0.370647 -1.157892 -1.344312 0.844885
Unnamed: 0 0 1 2 3
0 8 1.075770 -0.10905 1.643563 -1.469388
1 9 0.357021 -0.67460 -1.776904 -0.968914
Specifying iterator=True will also return the TextParser object:
In [779]: reader = read_table('tmp.sv', sep='|', iterator=True)
In [780]: reader.get_chunk(5)
Out[780]:
Unnamed: 0 0 1 2 3
0 0 0.469112 -0.282863 -1.509059 -1.135632
1 1 1.212112 -0.173215 0.119209 -1.044236
2 2 -0.861849 -2.104569 -0.494929 1.071804
3 3 0.721555 -0.706771 -1.039575 0.271860
4 4 -0.424972 0.567020 0.276232 -1.087401
Writing to CSV format¶
The Series and DataFrame objects have an instance method to_csv which allows storing the contents of the object as a comma-separated-values file. The function takes a number of arguments. Only the first is required.
- path: A string path to the file to write nanRep: A string representation of a missing value (default ‘’)
- cols: Columns to write (default None)
- header: Whether to write out the column names (default True)
- index: whether to write row (index) names (default True)
- index_label: Column label(s) for index column(s) if desired. If None (default), and header and index are True, then the index names are used. (A sequence should be given if the DataFrame uses MultiIndex).
- mode : Python write mode, default ‘w’
- sep : Field delimiter for the output file (default “’”)
- encoding: a string representing the encoding to use if the contents are non-ascii, for python versions prior to 3
Writing a formatted string¶
The DataFrame object has an instance method to_string which allows control over the string representation of the object. All arguments are optional:
- buf default None, for example a StringIO object
- columns default None, which columns to write
- col_space default None, number of spaces to write between columns
- na_rep default NaN, representation of NA value
- formatters default None, a dictionary (by column) of functions each of which takes a single argument and returns a formatted string
- float_format default None, a function which takes a single (float) argument and returns a formatted string; to be applied to floats in the DataFrame.
- sparsify default True, set to False for a DataFrame with a hierarchical index to print every multiindex key at each row.
- index_names default True, will print the names of the indices
- index default True, will print the index (ie, row labels)
- header default True, will print the column labels
- justify default left, will print column headers left- or right-justified
The Series object also has a to_string method, but with only the buf, na_rep, float_format arguments. There is also a length argument which, if set to True, will additionally output the length of the Series.
Writing to HTML format¶
DataFrame object has an instance method to_html which renders the contents of the DataFrame as an html table. The function arguments are as in the method to_string described above.
Excel files¶
The ExcelFile class can read an Excel 2003 file using the xlrd Python module and use the same parsing code as the above to convert tabular data into a DataFrame. To use it, create the ExcelFile object:
xls = ExcelFile('path_to_file.xls')
Then use the parse instance method with a sheetname, then use the same additional arguments as the parsers above:
xls.parse('Sheet1', index_col=None, na_values=['NA'])
To read sheets from an Excel 2007 file, you can pass a filename with a .xlsx extension, in which case the openpyxl module will be used to read the file.
To write a DataFrame object to a sheet of an Excel file, you can use the to_excel instance method. The arguments are largely the same as to_csv described above, the first argument being the name of the excel file, and the optional second argument the name of the sheet to which the DataFrame should be written. For example:
df.to_excel('path_to_file.xlsx', sheet_name='sheet1')
Files with a .xls extension will be written using xlwt and those with a .xlsx extension will be written using openpyxl. The Panel class also has a to_excel instance method, which writes each DataFrame in the Panel to a separate sheet.
In order to write separate DataFrames to separate sheets in a single Excel file, one can use the ExcelWriter class, as in the following example:
writer = ExcelWriter('path_to_file.xlsx')
df1.to_excel(writer, sheet_name='sheet1')
df2.to_excel(writer, sheet_name='sheet2')
writer.save()
HDF5 (PyTables)¶
HDFStore is a dict-like object which reads and writes pandas to the high performance HDF5 format using the excellent PyTables library.
In [781]: store = HDFStore('store.h5')
In [782]: 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 [783]: index = date_range('1/1/2000', periods=8)
In [784]: s = Series(randn(5), index=['a', 'b', 'c', 'd', 'e'])
In [785]: df = DataFrame(randn(8, 3), index=index,
.....: columns=['A', 'B', 'C'])
.....:
In [786]: wp = Panel(randn(2, 5, 4), items=['Item1', 'Item2'],
.....: major_axis=date_range('1/1/2000', periods=5),
.....: minor_axis=['A', 'B', 'C', 'D'])
.....:
In [787]: store['s'] = s
In [788]: store['df'] = df
In [789]: store['wp'] = wp
In [790]: store
Out[790]:
<class 'pandas.io.pytables.HDFStore'>
File path: store.h5
df DataFrame
s Series
wp Panel
In a current or later Python session, you can retrieve stored objects:
In [791]: store['df']
Out[791]:
A B C
2000-01-01 -0.362543 -0.006154 -0.923061
2000-01-02 0.895717 0.805244 -1.206412
2000-01-03 2.565646 1.431256 1.340309
2000-01-04 -1.170299 -0.226169 0.410835
2000-01-05 0.813850 0.132003 -0.827317
2000-01-06 -0.076467 -1.187678 1.130127
2000-01-07 -1.436737 -1.413681 1.607920
2000-01-08 1.024180 0.569605 0.875906