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 [594]: clipdf
Out[594]:
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:
- path_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.
- 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.
- names: List of column names to use. If passed, header will be implicitly set to None.
- 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, or list of column numbers, 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.
- parse_dates: If True, attempt to parse the index column as dates. 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.
- na_values: optional list of strings to recognize as NaN (missing values), in addition to a default set.
- nrows: Number of rows to read out of the file. Useful to only read a small portion of a large file
- 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
- iterator: If True, return a TextParser to enable reading a file into memory piece by piece
- 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
Consider a typical CSV file containing, in this case, some time series data:
In [595]: 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 [596]: read_csv('foo.csv')
Out[596]:
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 a list of column numbers, for a hierarchical index) you wish to use as the index. If the index values are dates and you want them to be converted to datetime objects, pass parse_dates=True:
# Use a column as an index, and parse it as dates.
In [597]: df = read_csv('foo.csv', index_col=0, parse_dates=True)
In [598]: df
Out[598]:
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 [599]: df.index
Out[599]: Index([2009-01-01 00:00:00, 2009-01-02 00:00:00, 2009-01-03 00:00:00], dtype=object)
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.
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 [600]: 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 [601]: colspecs = [(0, 6), (8, 20), (21, 33), (34, 43)]
In [602]: df = read_fwf('bar.csv', colspecs=colspecs, header=None, index_col=0)
In [603]: df
Out[603]:
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 [604]: widths = [6, 14, 13, 10]
In [605]: df = read_fwf('bar.csv', widths=widths, header=None)
In [606]: df
Out[606]:
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 [607]: 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 [608]: read_csv('foo.csv')
Out[608]:
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 [609]: df = read_csv('foo.csv', parse_dates=True)
In [610]: df.index
Out[610]: Index([2009-01-01 00:00:00, 2009-01-02 00:00:00, 2009-01-03 00:00:00], dtype=object)
Reading DataFrame objects with MultiIndex¶
Suppose you have data indexed by two columns:
In [611]: 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 [612]: df = read_csv("data/mindex_ex.csv", index_col=[0,1])
In [613]: df
Out[613]:
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 [614]: df.ix[1978]
Out[614]:
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 [615]: print open('tmp2.sv').read()
year:indiv:zit:xit
1977:A:1.2:0.59999999999999998
1977:B:1.5:0.5
1977:C:1.7:0.80000000000000004
1978:A:0.20000000000000001:0.059999999999999998
1978:B:0.69999999999999996:0.20000000000000001
1978:C:0.80000000000000004:0.29999999999999999
1978:D:0.90000000000000002:0.5
In [616]: read_csv('tmp2.sv')
Out[616]:
year:indiv:zit:xit
0 1977:A:1.2:0.59999999999999998
1 1977:B:1.5:0.5
2 1977:C:1.7:0.80000000000000004
3 1978:A:0.20000000000000001:0.059999999999999998
4 1978:B:0.69999999999999996:0.20000000000000001
5 1978:C:0.80000000000000004:0.29999999999999999
6 1978:D:0.90000000000000002:0.5
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 [617]: print open('tmp.sv').read()
year|indiv|zit|xit
1977|A|1.2|0.59999999999999998
1977|B|1.5|0.5
1977|C|1.7|0.80000000000000004
1978|A|0.20000000000000001|0.059999999999999998
1978|B|0.69999999999999996|0.20000000000000001
1978|C|0.80000000000000004|0.29999999999999999
1978|D|0.90000000000000002|0.5
In [618]: table = read_table('tmp.sv', sep='|')
In [619]: table
Out[619]:
year indiv zit xit
0 1977 A 1.2 0.60
1 1977 B 1.5 0.50
2 1977 C 1.7 0.80
3 1978 A 0.2 0.06
4 1978 B 0.7 0.20
5 1978 C 0.8 0.30
6 1978 D 0.9 0.50
By specifiying a chunksize to read_csv or read_table, the return value will be an iterable object of type TextParser:
In [620]: reader = read_table('tmp.sv', sep='|', chunksize=4)
In [621]: reader
Out[621]: <pandas.io.parsers.TextParser at 0x1138bef10>
In [622]: for chunk in reader:
.....: print chunk
.....:
year indiv zit xit
0 1977 A 1.2 0.60
1 1977 B 1.5 0.50
2 1977 C 1.7 0.80
3 1978 A 0.2 0.06
year indiv zit xit
0 1978 B 0.7 0.2
1 1978 C 0.8 0.3
2 1978 D 0.9 0.5
Specifying iterator=True will also return the TextParser object:
In [623]: reader = read_table('tmp.sv', sep='|', iterator=True)
In [624]: reader.get_chunk(5)
Out[624]:
year indiv zit xit
0 1977 A 1.2 0.60
1 1977 B 1.5 0.50
2 1977 C 1.7 0.80
3 1978 A 0.2 0.06
4 1978 B 0.7 0.20
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 [625]: store = HDFStore('store.h5')
In [626]: 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 [627]: index = DateRange('1/1/2000', periods=8)
In [628]: s = Series(randn(5), index=['a', 'b', 'c', 'd', 'e'])
In [629]: df = DataFrame(randn(8, 3), index=index,
.....: columns=['A', 'B', 'C'])
In [630]: wp = Panel(randn(2, 5, 4), items=['Item1', 'Item2'],
.....: major_axis=DateRange('1/1/2000', periods=5),
.....: minor_axis=['A', 'B', 'C', 'D'])
In [631]: store['s'] = s
In [632]: store['df'] = df
In [633]: store['wp'] = wp
In [634]: store
Out[634]:
<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 [635]: store['df']
Out[635]:
A B C
2000-01-03 -0.173215 0.119209 -1.044236
2000-01-04 -0.861849 -2.104569 -0.494929
2000-01-05 1.071804 0.721555 -0.706771
2000-01-06 -1.039575 0.271860 -0.424972
2000-01-07 0.567020 0.276232 -1.087401
2000-01-10 -0.673690 0.113648 -1.478427
2000-01-11 0.524988 0.404705 0.577046
2000-01-12 -1.715002 -1.039268 -0.370647