Movatterモバイル変換


[0]ホーム

URL:


Navigation

Table Of Contents

Search

Enter search terms or a module, class or function name.

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

The pandas I/O API is a set of top levelreader functions accessed likepd.read_csv() that generally return apandasobject.

The correspondingwriter functions are object methods that are accessed likedf.to_csv()

Here is an informal performance comparison for some of these IO methods.

Note

For examples that use theStringIO class, make sure you import itaccording to your Python version, i.e.fromStringIOimportStringIO forPython 2 andfromioimportStringIO for Python 3.

CSV & Text files

The two workhorse functions for reading text files (a.k.a. flat files) areread_csv() andread_table(). They both use the same parsing code tointelligently convert tabular data into a DataFrame object. See thecookbook for some advanced strategies.

Parsing options

read_csv() andread_table() accept the following arguments:

Basic

filepath_or_buffer
:various
Either a path to a file (astr,pathlib.Path,orpy._path.local.LocalPath), URL (including http, ftp, and S3locations), or any object with aread() method (such as an open file orStringIO).
sep
:str, defaults to',' forread_csv(),\t forread_table()
Delimiter to use. If sep isNone,will try to automatically determine this. Separators longer than 1 characterand different from'\s+' will be interpreted as regular expressions, willforce use of the python parsing engine and will ignore quotes in the data.Regex example:'\\r\\t'.
delimiter
:str, defaultNone
Alternative argument name for sep.
delim_whitespace
:boolean, default False

Specifies whether or not whitespace (e.g.'' or'\t')will be used as the delimiter. Equivalent to settingsep='\s+'.If this option is set to True, nothing should be passed in for thedelimiter parameter.

New in version 0.18.1:support for the Python parser.

Column and Index Locations and Names

header
:int or list of ints, default'infer'
Row number(s) to use as the column names, and the start of the data. Defaultbehavior is as ifheader=0 if nonames passed, otherwise as ifheader=None. Explicitly passheader=0 to be able to replace existingnames. The header can be a list of ints that specify row locations for amulti-index on the columns e.g.[0,1,3]. Intervening rows that are notspecified will be skipped (e.g. 2 in this example is skipped). Note thatthis parameter ignores commented lines and empty lines ifskip_blank_lines=True, so header=0 denotes the first line of datarather than the first line of the file.
names
:array-like, defaultNone
List of column names to use. If file contains no header row, then you shouldexplicitly passheader=None. Duplicates in this list are not allowed unlessmangle_dupe_cols=True, which is the default.
index_col
:int or sequence orFalse, defaultNone
Column to use as the row labels of the DataFrame. If a sequence is given, aMultiIndex is used. If you have a malformed file with delimiters at the end ofeach line, you might considerindex_col=False to force pandas tonot usethe first column as the index (row names).
usecols
:array-like, defaultNone
Return a subset of the columns. All elements in this array must eitherbe positional (i.e. integer indices into the document columns) or stringsthat correspond to column names provided either by the user innames orinferred from the document header row(s). For example, a validusecolsparameter would be [0, 1, 2] or [‘foo’, ‘bar’, ‘baz’]. Using this parameterresults in much faster parsing time and lower memory usage.
as_recarray
:boolean, defaultFalse

DEPRECATED: this argument will be removed in a future version. Please callpd.read_csv(...).to_records() instead.

Return a NumPy recarray instead of a DataFrame after parsing the data. Ifset toTrue, this option takes precedence over thesqueeze parameter.In addition, as row indices are not available in such a format, theindex_colparameter will be ignored.

squeeze
:boolean, defaultFalse
If the parsed data only contains one column then return a Series.
prefix
:str, defaultNone
Prefix to add to column numbers when no header, e.g. ‘X’ for X0, X1, ...
mangle_dupe_cols
:boolean, defaultTrue
Duplicate columns will be specified as ‘X.0’...’X.N’, rather than ‘X’...’X’.Passing in False will cause data to be overwritten if there are duplicatenames in the columns.

General Parsing Configuration

dtype
:Type name or dict of column -> type, defaultNone
Data type for data or columns. E.g.{'a':np.float64,'b':np.int32}(unsupported withengine='python'). Usestr orobject to preserve andnot interpret dtype.
engine
:{'c','python'}
Parser engine to use. The C engine is faster while the python engine iscurrently more feature-complete.
converters
:dict, defaultNone
Dict of functions for converting values in certain columns. Keys can either beintegers or column labels.
true_values
:list, defaultNone
Values to consider asTrue.
false_values
:list, defaultNone
Values to consider asFalse.
skipinitialspace
:boolean, defaultFalse
Skip spaces after delimiter.
skiprows
:list-like or integer, defaultNone
Line numbers to skip (0-indexed) or number of lines to skip (int) at the startof the file.
skipfooter
:int, default0
Number of lines at bottom of file to skip (unsupported with engine=’c’).
skip_footer
:int, default0
DEPRECATED: use theskipfooter parameter instead, as they are identical
nrows
:int, defaultNone
Number of rows of file to read. Useful for reading pieces of large files.
low_memory
:boolean, defaultTrue
Internally process the file in chunks, resulting in lower memory usewhile parsing, but possibly mixed type inference. To ensure no mixedtypes either setFalse, or specify the type with thedtype parameter.Note that the entire file is read into a single DataFrame regardless,use thechunksize oriterator parameter to return the data in chunks.(Only valid with C parser)
buffer_lines
:int, default None
DEPRECATED: this argument will be removed in a future version because itsvalue is not respected by the parser
compact_ints
:boolean, default False

DEPRECATED: this argument will be removed in a future version

Ifcompact_ints isTrue, then for any column that is of integer dtype, theparser will attempt to cast it as the smallest integerdtype possible, eithersigned or unsigned depending on the specification from theuse_unsigned parameter.

use_unsigned
:boolean, default False

DEPRECATED: this argument will be removed in a future version

If integer columns are being compacted (i.e.compact_ints=True), specify whetherthe column should be compacted to the smallest signed or unsigned integer dtype.

memory_map
:boolean, default False
If a filepath is provided forfilepath_or_buffer, map the file objectdirectly onto memory and access the data directly from there. Using thisoption can improve performance because there is no longer any I/O overhead.

NA and Missing Data Handling

na_values
:scalar, str, list-like, or dict, defaultNone
Additional strings to recognize as NA/NaN. If dict passed, specific per-columnNA values. By default the following values are interpreted as NaN:'-1.#IND','1.#QNAN','1.#IND','-1.#QNAN','#N/AN/A','#N/A','N/A','NA','#NA','NULL','NaN','-NaN','nan','-nan',''.
keep_default_na
:boolean, defaultTrue
If na_values are specified and keep_default_na isFalse the default NaNvalues are overridden, otherwise they’re appended to.
na_filter
:boolean, defaultTrue
Detect missing value markers (empty strings and the value of na_values). Indata without any NAs, passingna_filter=False can improve the performanceof reading a large file.
verbose
:boolean, defaultFalse
Indicate number of NA values placed in non-numeric columns.
skip_blank_lines
:boolean, defaultTrue
IfTrue, skip over blank lines rather than interpreting as NaN values.

Datetime Handling

parse_dates
:boolean or list of ints or names or list of lists or dict, defaultFalse.
  • IfTrue -> try parsing the index.
  • If[1,2,3] -> try parsing columns 1, 2, 3 each as a separate datecolumn.
  • If[[1,3]] -> combine columns 1 and 3 and parse as a single datecolumn.
  • If{'foo':[1,3]} -> parse columns 1, 3 as date and call result ‘foo’.A fast-path exists for iso8601-formatted dates.
infer_datetime_format
:boolean, defaultFalse
IfTrue and parse_dates is enabled for a column, attempt to infer thedatetime format to speed up the processing.
keep_date_col
:boolean, defaultFalse
IfTrue and parse_dates specifies combining multiple columns then keep theoriginal columns.
date_parser
:function, defaultNone
Function to use for converting a sequence of string columns to an array ofdatetime instances. The default usesdateutil.parser.parser to do theconversion. Pandas will try to call date_parser in three different ways,advancing to the next if an exception occurs: 1) Pass one or more arrays (asdefined by parse_dates) as arguments; 2) concatenate (row-wise) the stringvalues from the columns defined by parse_dates into a single array and passthat; and 3) call date_parser once for each row using one or more strings(corresponding to the columns defined by parse_dates) as arguments.
dayfirst
:boolean, defaultFalse
DD/MM format dates, international and European format.

Iteration

iterator
:boolean, defaultFalse
ReturnTextFileReader object for iteration or getting chunks withget_chunk().
chunksize
:int, defaultNone
ReturnTextFileReader object for iteration. Seeiterating and chunking below.

Quoting, Compression, and File Format

compression
:{'infer','gzip','bz2','zip','xz',None}, default'infer'

For on-the-fly decompression of on-disk data. If ‘infer’, then use gzip,bz2, zip, or xz if filepath_or_buffer is a string ending in ‘.gz’, ‘.bz2’,‘.zip’, or ‘.xz’, respectively, and no decompression otherwise. If using ‘zip’,the ZIP file must contain only one data file to be read in.Set toNone for no decompression.

New in version 0.18.1:support for ‘zip’ and ‘xz’ compression.

thousands
:str, defaultNone
Thousands separator.
decimal
:str, default'.'
Character to recognize as decimal point. E.g. use',' for European data.
float_precision
:string, default None
Specifies which converter the C engine should use for floating-point values.The options areNone for the ordinary converter,high for thehigh-precision converter, andround_trip for the round-trip converter.
lineterminator
:str (length 1), defaultNone
Character to break file into lines. Only valid with C parser.
quotechar
:str (length 1)
The character used to denote the start and end of a quoted item. Quoted itemscan include the delimiter and it will be ignored.
quoting
:int orcsv.QUOTE_* instance, default0
Control field quoting behavior percsv.QUOTE_* constants. Use one ofQUOTE_MINIMAL (0),QUOTE_ALL (1),QUOTE_NONNUMERIC (2) orQUOTE_NONE (3).
doublequote
:boolean, defaultTrue
Whenquotechar is specified andquoting is notQUOTE_NONE,indicate whether or not to interpret two consecutivequotechar elementsinside a field as a singlequotechar element.
escapechar
:str (length 1), defaultNone
One-character string used to escape delimiter when quoting isQUOTE_NONE.
comment
:str, defaultNone
Indicates remainder of line should not be parsed. If found at the beginning ofa line, the line will be ignored altogether. This parameter must be a singlecharacter. Like empty lines (as long asskip_blank_lines=True), fullycommented lines are ignored by the parameterheader but not byskiprows.For example, ifcomment='#', parsing ‘#empty\na,b,c\n1,2,3’ withheader=0 will result in ‘a,b,c’ being treated as the header.
encoding
:str, defaultNone
Encoding to use for UTF when reading/writing (e.g.'utf-8').List ofPython standard encodings.
dialect
:str orcsv.Dialect instance, defaultNone
IfNone defaults to Excel dialect. Ignored if sep longer than 1 char. Seecsv.Dialect documentation for more details.
tupleize_cols
:boolean, defaultFalse
Leave a list of tuples on columns as is (default is to convert to a MultiIndexon the columns).

Error Handling

error_bad_lines
:boolean, defaultTrue
Lines with too many fields (e.g. a csv line with too many commas) will bydefault cause an exception to be raised, and no DataFrame will be returned. IfFalse, then these “bad lines” will dropped from the DataFrame that isreturned (only valid with C parser). Seebad linesbelow.
warn_bad_lines
:boolean, defaultTrue
If error_bad_lines isFalse, and warn_bad_lines isTrue, a warning foreach “bad line” will be output (only valid with C parser).

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

In [1]:print(open('foo.csv').read())date,A,B,C20090101,a,1,220090102,b,3,420090103,c,4,5

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

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

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

In [3]:pd.read_csv('foo.csv',index_col=0)Out[3]:          A  B  Cdate20090101  a  1  220090102  b  3  420090103  c  4  5
In [4]:pd.read_csv('foo.csv',index_col='date')Out[4]:          A  B  Cdate20090101  a  1  220090102  b  3  420090103  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'])Out[5]:            B  Cdate     A20090101 a  1  220090102 b  3  420090103 c  4  5

Thedialect keyword gives greater flexibility in specifying the file format.By default it uses the Excel dialect but you can specify either the dialect nameor acsv.Dialect instance.

Suppose you had data with unenclosed quotes:

In [6]:print(data)label1,label2,label3index1,"a,c,eindex2,b,d,f

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

We can get around this usingdialect

In [7]:dia=csv.excel()In [8]:dia.quoting=csv.QUOTE_NONEIn [9]:pd.read_csv(StringIO(data),dialect=dia)Out[9]:       label1 label2 label3index1     "a      c      eindex2      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='~')Out[11]:   a  b  c0  1  2  31  4  5  6

Another common dialect option isskipinitialspace, to skip any whitespaceafter a delimiter:

In [12]:data='a, b, c\n1, 2, 3\n4, 5, 6'In [13]:print(data)a, b, c1, 2, 34, 5, 6In [14]:pd.read_csv(StringIO(data),skipinitialspace=True)Out[14]:   a  b  c0  1  2  31  4  5  6

The parsers make every attempt to “do the right thing” and not be veryfragile. Type inference is a pretty big deal. So if a column can be coerced tointeger dtype without altering the contents, it will do so. Any non-numericcolumns 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 orindividual columns:

In [15]:data='a,b,c\n1,2,3\n4,5,6\n7,8,9'In [16]:print(data)a,b,c1,2,34,5,67,8,9In [17]:df=pd.read_csv(StringIO(data),dtype=object)In [18]:dfOut[18]:   a  b  c0  1  2  31  4  5  62  7  8  9In [19]:df['a'][0]Out[19]:'1'In [20]:df=pd.read_csv(StringIO(data),dtype={'b':object,'c':np.float64})In [21]:df.dtypesOut[21]:a      int64b     objectc    float64dtype: object

Fortunately,pandas offers more than one way to ensure that your column(s)contain only onedtype. If you’re unfamiliar with these concepts, you canseehere to learn more about dtypes, andhere to learn more aboutobject conversion inpandas.

For instance, you can use theconverters argumentofread_csv():

In [22]:data="col_1\n1\n2\n'A'\n4.22"In [23]:df=pd.read_csv(StringIO(data),converters={'col_1':str})In [24]:dfOut[24]:  col_10     11     22   'A'3  4.22In [25]:df['col_1'].apply(type).value_counts()Out[25]:<type 'str'>    4Name: col_1, dtype: int64

Or you can use theto_numeric() function to coerce thedtypes after reading in the data,

In [26]:df2=pd.read_csv(StringIO(data))In [27]:df2['col_1']=pd.to_numeric(df2['col_1'],errors='coerce')In [28]:df2Out[28]:   col_10   1.001   2.002    NaN3   4.22In [29]:df2['col_1'].apply(type).value_counts()Out[29]:<type 'float'>    4Name: col_1, dtype: int64

which would convert all valid parsing to floats, leaving the invalid parsingasNaN.

Ultimately, how you deal with reading in columns containing mixed dtypesdepends on your specific needs. In the case above, if you wanted toNaN outthe data anomalies, thento_numeric() is probably your best option.However, if you wanted for all the data to be coerced, no matter the type, thenusing theconverters argument ofread_csv() would certainly beworth trying.

Note

Thedtype option is currently only supported by the C engine.Specifyingdtype withengine other than ‘c’ raises aValueError.

Note

In some cases, reading in abnormal data with columns containing mixed dtypeswill result in an inconsistent dataset. If you rely on pandas to infer thedtypes of your columns, the parsing engine will go and infer the dtypes fordifferent chunks of the data, rather than the whole dataset at once. Consequently,you can end up with column(s) with mixed dtypes. For example,

In [30]:df=pd.DataFrame({'col_1':range(500000)+['a','b']+range(500000)})In [31]:df.to_csv('foo')In [32]:mixed_df=pd.read_csv('foo')In [33]:mixed_df['col_1'].apply(type).value_counts()Out[33]:<type 'int'>    737858<type 'str'>    262144Name: col_1, dtype: int64In [34]:mixed_df['col_1'].dtypeOut[34]:dtype('O')

will result withmixed_df containing anint dtype for certain chunksof the column, andstr for others due to the mixed dtypes from thedata that was read in. It is important to note that the overall column will bemarked with adtype ofobject, which is used for columns with mixed dtypes.

Specifying Categorical dtype

New in version 0.19.0.

Categorical columns can be parsed directly by specifyingdtype='category'

In [35]:data='col1,col2,col3\na,b,1\na,b,2\nc,d,3'In [36]:pd.read_csv(StringIO(data))Out[36]:  col1 col2  col30    a    b     11    a    b     22    c    d     3In [37]:pd.read_csv(StringIO(data)).dtypesOut[37]:col1    objectcol2    objectcol3     int64dtype: objectIn [38]:pd.read_csv(StringIO(data),dtype='category').dtypesOut[38]:col1    categorycol2    categorycol3    categorydtype: object

Individual columns can be parsed as aCategorical using a dict specification

In [39]:pd.read_csv(StringIO(data),dtype={'col1':'category'}).dtypesOut[39]:col1    categorycol2      objectcol3       int64dtype: object

Note

The resulting categories will always be parsed as strings (object dtype).If the categories are numeric they can be converted using theto_numeric() function, or as appropriate, another convertersuch asto_datetime().

In [40]:df=pd.read_csv(StringIO(data),dtype='category')In [41]:df.dtypesOut[41]:col1    categorycol2    categorycol3    categorydtype: objectIn [42]:df['col3']Out[42]:0    11    22    3Name: col3, dtype: categoryCategories (3, object): [1, 2, 3]In [43]:df['col3'].cat.categories=pd.to_numeric(df['col3'].cat.categories)In [44]:df['col3']Out[44]:0    11    22    3Name: col3, dtype: categoryCategories (3, int64): [1, 2, 3]

Naming and Using Columns

Handling column names

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

In [45]:data='a,b,c\n1,2,3\n4,5,6\n7,8,9'In [46]:print(data)a,b,c1,2,34,5,67,8,9In [47]:pd.read_csv(StringIO(data))Out[47]:   a  b  c0  1  2  31  4  5  62  7  8  9

By specifying thenames argument in conjunction withheader you canindicate other names to use and whether or not to throw away the header row (ifany):

In [48]:print(data)a,b,c1,2,34,5,67,8,9In [49]:pd.read_csv(StringIO(data),names=['foo','bar','baz'],header=0)Out[49]:   foo  bar  baz0    1    2    31    4    5    62    7    8    9In [50]:pd.read_csv(StringIO(data),names=['foo','bar','baz'],header=None)Out[50]:  foo bar baz0   a   b   c1   1   2   32   4   5   63   7   8   9

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

In [51]:data='skip this skip it\na,b,c\n1,2,3\n4,5,6\n7,8,9'In [52]:pd.read_csv(StringIO(data),header=1)Out[52]:   a  b  c0  1  2  31  4  5  62  7  8  9

Duplicate names parsing

If the file or header contains duplicate names, pandas by default will deduplicatethese names so as to prevent data overwrite:

In [53]:data='a,b,a\n0,1,2\n3,4,5'In [54]:pd.read_csv(StringIO(data))Out[54]:   a  b  a.10  0  1    21  3  4    5

There is no more duplicate data becausemangle_dupe_cols=True by default, which modifiesa series of duplicate columns ‘X’...’X’ to become ‘X.0’...’X.N’. Ifmangle_dupe_cols=False, duplicate data can arise:

In[2]:data='a,b,a\n0,1,2\n3,4,5'In[3]:pd.read_csv(StringIO(data),mangle_dupe_cols=False)Out[3]:aba02121545

To prevent users from encountering this problem with duplicate data, aValueErrorexception is raised ifmangle_dupe_cols!=True:

In[2]:data='a,b,a\n0,1,2\n3,4,5'In[3]:pd.read_csv(StringIO(data),mangle_dupe_cols=False)...ValueError:Settingmangle_dupe_cols=Falseisnotsupportedyet

Filtering columns (usecols)

Theusecols argument allows you to select any subset of the columns in afile, either using the column names or position numbers:

In [55]:data='a,b,c,d\n1,2,3,foo\n4,5,6,bar\n7,8,9,baz'In [56]:pd.read_csv(StringIO(data))Out[56]:   a  b  c    d0  1  2  3  foo1  4  5  6  bar2  7  8  9  bazIn [57]:pd.read_csv(StringIO(data),usecols=['b','d'])Out[57]:   b    d0  2  foo1  5  bar2  8  bazIn [58]:pd.read_csv(StringIO(data),usecols=[0,2,3])Out[58]:   a  c    d0  1  3  foo1  4  6  bar2  7  9  baz

Comments and Empty Lines

Ignoring line comments and empty lines

If thecomment parameter is specified, then completely commented lines willbe ignored. By default, completely blank lines will be ignored as well. Both ofthese are API changes introduced in version 0.15.

In [59]:data='\na,b,c\n\n# commented line\n1,2,3\n\n4,5,6'In [60]:print(data)a,b,c1,2,34,5,6# commented lineIn [61]:pd.read_csv(StringIO(data),comment='#')Out[61]:   a  b  c0  1  2  31  4  5  6

Ifskip_blank_lines=False, thenread_csv will not ignore blank lines:

In [62]:data='a,b,c\n\n1,2,3\n\n\n4,5,6'In [63]:pd.read_csv(StringIO(data),skip_blank_lines=False)Out[63]:     a    b    c0  NaN  NaN  NaN1  1.0  2.0  3.02  NaN  NaN  NaN3  NaN  NaN  NaN4  4.0  5.0  6.0

Warning

The presence of ignored lines might create ambiguities involving line numbers;the parameterheader uses row numbers (ignoring commented/emptylines), whileskiprows uses line numbers (including commented/empty lines):

In [64]:data='#comment\na,b,c\nA,B,C\n1,2,3'In [65]:pd.read_csv(StringIO(data),comment='#',header=1)Out[65]:   A  B  C0  1  2  3In [66]:data='A,B,C\n#comment\na,b,c\n1,2,3'In [67]:pd.read_csv(StringIO(data),comment='#',skiprows=2)Out[67]:   a  b  c0  1  2  3

If bothheader andskiprows are specified,header will berelative to the end ofskiprows. For example:

In [68]:data='# empty\n# second empty line\n# third empty' \In [68]:'line\nX,Y,Z\n1,2,3\nA,B,C\n1,2.,4.\n5.,NaN,10.0'In [69]:print(data)# empty# second empty line# third emptylineX,Y,Z1,2,3A,B,C1,2.,4.5.,NaN,10.0In [70]:pd.read_csv(StringIO(data),comment='#',skiprows=4,header=1)Out[70]:     A    B     C0  1.0  2.0   4.01  5.0  NaN  10.0

Comments

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

In [71]:print(open('tmp.csv').read())ID,level,categoryPatient1,123000,x # really unpleasantPatient2,23000,y # wouldn't take his medicinePatient3,1234018,z # awesome

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

In [72]:df=pd.read_csv('tmp.csv')In [73]:dfOut[73]:         ID    level                        category0  Patient1   123000           x # really unpleasant1  Patient2    23000  y # wouldn't take his medicine2  Patient3  1234018                     z # awesome

We can suppress the comments using thecomment keyword:

In [74]:df=pd.read_csv('tmp.csv',comment='#')In [75]:dfOut[75]:         ID    level category0  Patient1   123000       x1  Patient2    23000       y2  Patient3  1234018       z

Dealing with Unicode Data

Theencoding argument should be used for encoded unicode data, which willresult in byte strings being decoded to unicode in the result:

In [76]:data=b'word,length\nTr\xc3\xa4umen,7\nGr\xc3\xbc\xc3\x9fe,5'.decode('utf8').encode('latin-1')In [77]:df=pd.read_csv(BytesIO(data),encoding='latin-1')In [78]:dfOut[78]:      word  length0  Träumen       71    Grüße       5In [79]:df['word'][1]Out[79]:u'Gr\xfc\xdfe'

Some formats which encode all characters as multiple bytes, like UTF-16, won’tparse correctly at all without specifying the encoding.Full list of Pythonstandard encodings

Index columns and trailing delimiters

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

In [80]:data='a,b,c\n4,apple,bat,5.7\n8,orange,cow,10'In [81]:pd.read_csv(StringIO(data))Out[81]:        a    b     c4   apple  bat   5.78  orange  cow  10.0
In [82]:data='index,a,b,c\n4,apple,bat,5.7\n8,orange,cow,10'In [83]:pd.read_csv(StringIO(data),index_col=0)Out[83]:            a    b     cindex4       apple  bat   5.78      orange  cow  10.0

Ordinarily, you can achieve this behavior using theindex_col option.

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

In [84]:data='a,b,c\n4,apple,bat,\n8,orange,cow,'In [85]:print(data)a,b,c4,apple,bat,8,orange,cow,In [86]:pd.read_csv(StringIO(data))Out[86]:        a    b   c4   apple  bat NaN8  orange  cow NaNIn [87]:pd.read_csv(StringIO(data),index_col=False)Out[87]:   a       b    c0  4   apple  bat1  8  orange  cow

Date Handling

Specifying Date Columns

To better facilitate working with datetime data,read_csv() andread_table() use the keyword argumentsparse_dates anddate_parserto allow users to specify a variety of columns and date/time formats to turn theinput text data intodatetime objects.

The simplest case is to just pass inparse_dates=True:

# Use a column as an index, and parse it as dates.In [88]:df=pd.read_csv('foo.csv',index_col=0,parse_dates=True)In [89]:dfOut[89]:            A  B  Cdate2009-01-01  a  1  22009-01-02  b  3  42009-01-03  c  4  5# These are python datetime objectsIn [90]:df.indexOut[90]:DatetimeIndex(['2009-01-01','2009-01-02','2009-01-03'],dtype='datetime64[ns]',name=u'date',freq=None)

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

You can specify a list of column lists toparse_dates, the resulting datecolumns will be prepended to the output (so as to not affect the existing columnorder) and the new column names will be the concatenation of the componentcolumn names:

In [91]:print(open('tmp.csv').read())KORD,19990127, 19:00:00, 18:56:00, 0.8100KORD,19990127, 20:00:00, 19:56:00, 0.0100KORD,19990127, 21:00:00, 20:56:00, -0.5900KORD,19990127, 21:00:00, 21:18:00, -0.9900KORD,19990127, 22:00:00, 21:56:00, -0.5900KORD,19990127, 23:00:00, 22:56:00, -0.5900In [92]:df=pd.read_csv('tmp.csv',header=None,parse_dates=[[1,2],[1,3]])In [93]:dfOut[93]:                  1_2                 1_3     0     40 1999-01-27 19:00:00 1999-01-27 18:56:00  KORD  0.811 1999-01-27 20:00:00 1999-01-27 19:56:00  KORD  0.012 1999-01-27 21:00:00 1999-01-27 20:56:00  KORD -0.593 1999-01-27 21:00:00 1999-01-27 21:18:00  KORD -0.994 1999-01-27 22:00:00 1999-01-27 21:56:00  KORD -0.595 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 chooseto retain them via thekeep_date_col keyword:

In [94]:df=pd.read_csv('tmp.csv',header=None,parse_dates=[[1,2],[1,3]],   ....:keep_date_col=True)   ....:In [95]:dfOut[95]:                  1_2                 1_3     0         1          2  \0 1999-01-27 19:00:00 1999-01-27 18:56:00  KORD  19990127   19:00:001 1999-01-27 20:00:00 1999-01-27 19:56:00  KORD  19990127   20:00:002 1999-01-27 21:00:00 1999-01-27 20:56:00  KORD  19990127   21:00:003 1999-01-27 21:00:00 1999-01-27 21:18:00  KORD  19990127   21:00:004 1999-01-27 22:00:00 1999-01-27 21:56:00  KORD  19990127   22:00:005 1999-01-27 23:00:00 1999-01-27 22:56:00  KORD  19990127   23:00:00           3     40   18:56:00  0.811   19:56:00  0.012   20:56:00 -0.593   21:18:00 -0.994   21:56:00 -0.595   22:56:00 -0.59

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

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

In [96]:date_spec={'nominal':[1,2],'actual':[1,3]}In [97]:df=pd.read_csv('tmp.csv',header=None,parse_dates=date_spec)In [98]:dfOut[98]:              nominal              actual     0     40 1999-01-27 19:00:00 1999-01-27 18:56:00  KORD  0.811 1999-01-27 20:00:00 1999-01-27 19:56:00  KORD  0.012 1999-01-27 21:00:00 1999-01-27 20:56:00  KORD -0.593 1999-01-27 21:00:00 1999-01-27 21:18:00  KORD -0.994 1999-01-27 22:00:00 1999-01-27 21:56:00  KORD -0.595 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 intoa single date column, then a new column is prepended to the data. Theindex_colspecification is based off of this new set of columns rather than the originaldata columns:

In [99]:date_spec={'nominal':[1,2],'actual':[1,3]}In [100]:df=pd.read_csv('tmp.csv',header=None,parse_dates=date_spec,   .....:index_col=0)#index is the nominal column   .....:In [101]:dfOut[101]:                                 actual     0     4nominal1999-01-27 19:00:00 1999-01-27 18:56:00  KORD  0.811999-01-27 20:00:00 1999-01-27 19:56:00  KORD  0.011999-01-27 21:00:00 1999-01-27 20:56:00  KORD -0.591999-01-27 21:00:00 1999-01-27 21:18:00  KORD -0.991999-01-27 22:00:00 1999-01-27 21:56:00  KORD -0.591999-01-27 23:00:00 1999-01-27 22:56:00  KORD -0.59

Note

read_csv has a fast_path for parsing datetime strings in iso8601 format,e.g “2000-01-01T00:01:02+00:00” and similar variations. If you can arrangefor your data to store datetimes in this format, load times will besignificantly faster, ~20x has been observed.

Note

When passing a dict as theparse_dates argument, the order ofthe columns prepended is not guaranteed, becausedict objects do not imposean ordering on their keys. On Python 2.7+ you may usecollections.OrderedDictinstead of a regulardict if this matters to you. Because of this, when using adict for ‘parse_dates’ in conjunction with theindex_col argument, it’s best tospecifyindex_col as a column label rather then as an index on the resulting frame.

Date Parsing Functions

Finally, the parser allows you to specify a customdate_parser function totake full advantage of the flexibility of the date parsing API:

In [102]:importpandas.io.date_convertersasconvIn [103]:df=pd.read_csv('tmp.csv',header=None,parse_dates=date_spec,   .....:date_parser=conv.parse_date_time)   .....:In [104]:dfOut[104]:              nominal              actual     0     40 1999-01-27 19:00:00 1999-01-27 18:56:00  KORD  0.811 1999-01-27 20:00:00 1999-01-27 19:56:00  KORD  0.012 1999-01-27 21:00:00 1999-01-27 20:56:00  KORD -0.593 1999-01-27 21:00:00 1999-01-27 21:18:00  KORD -0.994 1999-01-27 22:00:00 1999-01-27 21:56:00  KORD -0.595 1999-01-27 23:00:00 1999-01-27 22:56:00  KORD -0.59

Pandas will try to call thedate_parser function in three different ways. Ifan exception is raised, the next one is tried:

  1. date_parser is first called with one or more arrays as arguments,as defined usingparse_dates (e.g.,date_parser(['2013','2013'],['1','2']))
  2. If #1 fails,date_parser is called with all the columnsconcatenated row-wise into a single array (e.g.,date_parser(['20131','20132']))
  3. If #2 fails,date_parser is called once for every row with one or morestring arguments from the columns indicated withparse_dates(e.g.,date_parser('2013','1') for the first row,date_parser('2013','2')for the second, etc.)

Note that performance-wise, you should try these methods of parsing dates in order:

  1. Try to infer the format usinginfer_datetime_format=True (see section below)
  2. If you know the format, usepd.to_datetime():date_parser=lambdax:pd.to_datetime(x,format=...)
  3. If you have a really non-standard format, use a customdate_parser function.For optimal performance, this should be vectorized, i.e., it should accept arraysas arguments.

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

Inferring Datetime Format

If you haveparse_dates enabled for some or all of your columns, and yourdatetime strings are all formatted the same way, you may get a large speedup by settinginfer_datetime_format=True. If set, pandas will attemptto guess the format of your datetime strings, and then use a faster meansof parsing the strings. 5-10x parsing speeds have been observed. pandaswill fallback to the usual parsing if either the format cannot be guessedor the format that was guessed cannot properly parse the entire columnof strings. So in general,infer_datetime_format should not have anynegative consequences if enabled.

Here are some examples of datetime strings that can be guessed (Allrepresenting December 30th, 2011 at 00:00:00)

  • “20111230”
  • “2011/12/30”
  • “20111230 00:00:00”
  • “12/30/2011 00:00:00”
  • “30/Dec/2011 00:00:00”
  • “30/December/2011 00:00:00”

infer_datetime_format is sensitive todayfirst. Withdayfirst=True, it will guess “01/12/2011” to be December 1st. Withdayfirst=False (default) it will guess “01/12/2011” to be January 12th.

# Try to infer the format for the index columnIn [105]:df=pd.read_csv('foo.csv',index_col=0,parse_dates=True,   .....:infer_datetime_format=True)   .....:In [106]:dfOut[106]:            A  B  Cdate2009-01-01  a  1  22009-01-02  b  3  42009-01-03  c  4  5

International Date Formats

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

In [107]:print(open('tmp.csv').read())date,value,cat1/6/2000,5,a2/6/2000,10,b3/6/2000,15,cIn [108]:pd.read_csv('tmp.csv',parse_dates=[0])Out[108]:        date  value cat0 2000-01-06      5   a1 2000-02-06     10   b2 2000-03-06     15   cIn [109]:pd.read_csv('tmp.csv',dayfirst=True,parse_dates=[0])Out[109]:        date  value cat0 2000-06-01      5   a1 2000-06-02     10   b2 2000-06-03     15   c

Specifying method for floating-point conversion

The parameterfloat_precision can be specified in order to usea specific floating-point converter during parsing with the C engine.The options are the ordinary converter, the high-precision converter, andthe round-trip converter (which is guaranteed to round-trip values afterwriting to a file). For example:

In [110]:val='0.3066101993807095471566981359501369297504425048828125'In [111]:data='a,b,c\n1,2,{0}'.format(val)In [112]:abs(pd.read_csv(StringIO(data),engine='c',float_precision=None)['c'][0]-float(val))Out[112]:1.1102230246251565e-16In [113]:abs(pd.read_csv(StringIO(data),engine='c',float_precision='high')['c'][0]-float(val))Out[113]:5.5511151231257827e-17In [114]:abs(pd.read_csv(StringIO(data),engine='c',float_precision='round_trip')['c'][0]-float(val))Out[114]:0.0

Thousand Separators

For large numbers that have been written with a thousands separator, you canset thethousands keyword to a string of length 1 so that integers will be parsedcorrectly:

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

In [115]:print(open('tmp.csv').read())ID|level|categoryPatient1|123,000|xPatient2|23,000|yPatient3|1,234,018|zIn [116]:df=pd.read_csv('tmp.csv',sep='|')In [117]:dfOut[117]:         ID      level category0  Patient1    123,000        x1  Patient2     23,000        y2  Patient3  1,234,018        zIn [118]:df.level.dtypeOut[118]:dtype('O')

Thethousands keyword allows integers to be parsed correctly

In [119]:print(open('tmp.csv').read())ID|level|categoryPatient1|123,000|xPatient2|23,000|yPatient3|1,234,018|zIn [120]:df=pd.read_csv('tmp.csv',sep='|',thousands=',')In [121]:dfOut[121]:         ID    level category0  Patient1   123000        x1  Patient2    23000        y2  Patient3  1234018        zIn [122]:df.level.dtypeOut[122]:dtype('int64')

NA Values

To control which values are parsed as missing values (which are signified byNaN), specifiy astring inna_values. If you specify a list of strings, then all values init are considered to be missing values. If you specify a number (afloat, like5.0 or aninteger like5),the corresponding equivalent values will also imply a missing value (in this case effectively[5.0,5] are recognized asNaN.

To completely override the default values that are recognized as missing, specifykeep_default_na=False.The defaultNaN recognized values are['-1.#IND','1.#QNAN','1.#IND','-1.#QNAN','#N/A','N/A','NA','#NA','NULL','NaN','-NaN','nan','-nan']. Although a 0-length string'' is not included in the defaultNaN values list, it is still treatedas a missing value.

read_csv(path,na_values=[5])

the default values, in addition to5 ,5.0 when interpreted as numbers are recognized asNaN

read_csv(path,keep_default_na=False,na_values=[""])

only an empty field will beNaN

read_csv(path,keep_default_na=False,na_values=["NA","0"])

onlyNA and0 as strings areNaN

read_csv(path,na_values=["Nope"])

the default values, in addition to the string"Nope" are recognized asNaN

Infinity

inf like values will be parsed asnp.inf (positive infinity), and-inf as-np.inf (negative infinity).These will ignore the case of the value, meaningInf, will also be parsed asnp.inf.

Returning Series

Using thesqueeze keyword, the parser will return output with a single columnas aSeries:

In [123]:print(open('tmp.csv').read())levelPatient1,123000Patient2,23000Patient3,1234018In [124]:output=pd.read_csv('tmp.csv',squeeze=True)In [125]:outputOut[125]:Patient1     123000Patient2      23000Patient3    1234018Name: level, dtype: int64In [126]:type(output)Out[126]:pandas.core.series.Series

Boolean values

The common valuesTrue,False,TRUE, andFALSE are allrecognized as boolean. Sometime you would want to recognize some other valuesas being boolean. To do this use thetrue_values andfalse_valuesoptions:

In [127]:data='a,b,c\n1,Yes,2\n3,No,4'In [128]:print(data)a,b,c1,Yes,23,No,4In [129]:pd.read_csv(StringIO(data))Out[129]:   a    b  c0  1  Yes  21  3   No  4In [130]:pd.read_csv(StringIO(data),true_values=['Yes'],false_values=['No'])Out[130]:   a      b  c0  1   True  21  3  False  4

Handling “bad” lines

Some files may have malformed lines with too few fields or too many. Lines withtoo few fields will have NA values filled in the trailing fields. Lines withtoo 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 4Out[29]:   a  b   c0  1  2   31  8  9  10

Quoting and Escape Characters

Quotes (and other escape characters) in embedded fields can be handled in anynumber of ways. One way is to use backslashes; to properly parse this data, youshould pass theescapechar option:

In [131]:data='a,b\n"hello,\\"Bob\\", nice to see you",5'In [132]:print(data)a,b"hello, \"Bob\", nice to see you",5In [133]:pd.read_csv(StringIO(data),escapechar='\\')Out[133]:                               a  b0  hello, "Bob", nice to see you  5

Files with Fixed Width Columns

Whileread_csv reads delimited data, theread_fwf() function workswith data files that have known and fixed column widths. The function parameterstoread_fwf are largely the same asread_csv with two extra parameters:

  • colspecs: A list of pairs (tuples) giving the extents of thefixed-width fields of each line as half-open intervals (i.e., [from, to[ ).String value ‘infer’ can be used to instruct the parser to try detectingthe column specifications from the first 100 rows of the data. Defaultbehaviour, if not specified, is to infer.
  • 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 [134]:print(open('bar.csv').read())id8141    360.242940   149.910199   11950.7id1594    444.953632   166.985655   11788.4id1849    364.136849   183.628767   11806.2id1230    413.836124   184.375703   11916.8id1948    502.953953   173.237159   12468.3

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

#Column specifications are a list of half-intervalsIn [135]:colspecs=[(0,6),(8,20),(21,33),(34,43)]In [136]:df=pd.read_fwf('bar.csv',colspecs=colspecs,header=None,index_col=0)In [137]:dfOut[137]:                 1           2        30id8141  360.242940  149.910199  11950.7id1594  444.953632  166.985655  11788.4id1849  364.136849  183.628767  11806.2id1230  413.836124  184.375703  11916.8id1948  502.953953  173.237159  12468.3

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

#Widths are a list of integersIn [138]:widths=[6,14,13,10]In [139]:df=pd.read_fwf('bar.csv',widths=widths,header=None)In [140]:dfOut[140]:        0           1           2        30  id8141  360.242940  149.910199  11950.71  id1594  444.953632  166.985655  11788.42  id1849  364.136849  183.628767  11806.23  id1230  413.836124  184.375703  11916.84  id1948  502.953953  173.237159  12468.3

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

New in version 0.13.0.

By default,read_fwf will try to infer the file’scolspecs by using thefirst 100 rows of the file. It can do it only in cases when the columns arealigned and correctly separated by the provideddelimiter (default delimiteris whitespace).

In [141]:df=pd.read_fwf('bar.csv',header=None,index_col=0)In [142]:dfOut[142]:                 1           2        30id8141  360.242940  149.910199  11950.7id1594  444.953632  166.985655  11788.4id1849  364.136849  183.628767  11806.2id1230  413.836124  184.375703  11916.8id1948  502.953953  173.237159  12468.3

Indexes

Files with an “implicit” index column

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

In [143]:print(open('foo.csv').read())A,B,C20090101,a,1,220090102,b,3,420090103,c,4,5

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

In [144]:pd.read_csv('foo.csv')Out[144]:          A  B  C20090101  a  1  220090102  b  3  420090103  c  4  5

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

In [145]:df=pd.read_csv('foo.csv',parse_dates=True)In [146]:df.indexOut[146]:DatetimeIndex(['2009-01-01','2009-01-02','2009-01-03'],dtype='datetime64[ns]',freq=None)

Reading an index with aMultiIndex

Suppose you have data indexed by two columns:

In [147]:print(open('data/mindex_ex.csv').read())year,indiv,zit,xit1977,"A",1.2,.61977,"B",1.5,.51977,"C",1.7,.81978,"A",.2,.061978,"B",.7,.21978,"C",.8,.31978,"D",.9,.51978,"E",1.4,.91979,"C",.2,.151979,"D",.14,.051979,"E",.5,.151979,"F",1.2,.51979,"G",3.4,1.91979,"H",5.4,2.71979,"I",6.4,1.2

Theindex_col argument toread_csv andread_table can take a list ofcolumn numbers to turn multiple columns into aMultiIndex for the index of thereturned object:

In [148]:df=pd.read_csv("data/mindex_ex.csv",index_col=[0,1])In [149]:dfOut[149]:             zit   xityear indiv1977 A      1.20  0.60     B      1.50  0.50     C      1.70  0.801978 A      0.20  0.06     B      0.70  0.20     C      0.80  0.30     D      0.90  0.50     E      1.40  0.901979 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.20In [150]:df.ix[1978]Out[150]:       zit   xitindivA      0.2  0.06B      0.7  0.20C      0.8  0.30D      0.9  0.50E      1.4  0.90

Reading columns with aMultiIndex

By specifying list of row locations for theheader argument, youcan read in aMultiIndex for the columns. Specifying non-consecutiverows will skip the intervening rows. In order to have the pre-0.13 behaviorof tupleizing columns, specifytupleize_cols=True.

In [151]:frompandas.util.testingimportmakeCustomDataframeasmkdfIn [152]:df=mkdf(5,3,r_idx_nlevels=2,c_idx_nlevels=4)In [153]:df.to_csv('mi.csv')In [154]:print(open('mi.csv').read())C0,,C_l0_g0,C_l0_g1,C_l0_g2C1,,C_l1_g0,C_l1_g1,C_l1_g2C2,,C_l2_g0,C_l2_g1,C_l2_g2C3,,C_l3_g0,C_l3_g1,C_l3_g2R0,R1,,,R_l0_g0,R_l1_g0,R0C0,R0C1,R0C2R_l0_g1,R_l1_g1,R1C0,R1C1,R1C2R_l0_g2,R_l1_g2,R2C0,R2C1,R2C2R_l0_g3,R_l1_g3,R3C0,R3C1,R3C2R_l0_g4,R_l1_g4,R4C0,R4C1,R4C2In [155]:pd.read_csv('mi.csv',header=[0,1,2,3],index_col=[0,1])Out[155]:C0              C_l0_g0 C_l0_g1 C_l0_g2C1              C_l1_g0 C_l1_g1 C_l1_g2C2              C_l2_g0 C_l2_g1 C_l2_g2C3              C_l3_g0 C_l3_g1 C_l3_g2R0      R1R_l0_g0 R_l1_g0    R0C0    R0C1    R0C2R_l0_g1 R_l1_g1    R1C0    R1C1    R1C2R_l0_g2 R_l1_g2    R2C0    R2C1    R2C2R_l0_g3 R_l1_g3    R3C0    R3C1    R3C2R_l0_g4 R_l1_g4    R4C0    R4C1    R4C2

Starting in 0.13.0,read_csv will be able to interpret a more common formatof multi-columns indices.

In [156]:print(open('mi2.csv').read()),a,a,a,b,c,c,q,r,s,t,u,vone,1,2,3,4,5,6two,7,8,9,10,11,12In [157]:pd.read_csv('mi2.csv',header=[0,1],index_col=0)Out[157]:     a         b   c     q  r  s   t   u   vone  1  2  3   4   5   6two  7  8  9  10  11  12

Note: If anindex_col is not specified (e.g. you don’t have an index, or wrote itwithdf.to_csv(...,index=False), then anynames on the columns index will belost.

Automatically “sniffing” the delimiter

read_csv is capable of inferring delimited (not necessarilycomma-separated) files, as pandas uses thecsv.Snifferclass of the csv module. For this, you have to specifysep=None.

In [158]:print(open('tmp2.sv').read()):0:1:2:30:0.469112299907:-0.282863344329:-1.50905850317:-1.135632371021:1.21211202502:-0.173214649053:0.119208711297:-1.044235966282:-0.861848963348:-2.10456921889:-0.494929274069:1.071803807043:0.721555162244:-0.70677113363:-1.03957498511:0.2718598855434:-0.424972329789:0.567020349794:0.276232019278:-1.087400691295:-0.673689708088:0.113648409689:-1.47842655244:0.5249876671156:0.40470521868:0.57704598592:-1.71500201611:-1.039268483517:-0.370646858236:-1.15789225064:-1.34431181273:0.8448851414258:1.07576978372:-0.10904997528:1.64356307036:-1.469387959549:0.357020564133:-0.67460010373:-1.77690371697:-0.968913812447In [159]:pd.read_csv('tmp2.sv',sep=None,engine='python')Out[159]:   Unnamed: 0         0         1         2         30           0  0.469112 -0.282863 -1.509059 -1.1356321           1  1.212112 -0.173215  0.119209 -1.0442362           2 -0.861849 -2.104569 -0.494929  1.0718043           3  0.721555 -0.706771 -1.039575  0.2718604           4 -0.424972  0.567020  0.276232 -1.0874015           5 -0.673690  0.113648 -1.478427  0.5249886           6  0.404705  0.577046 -1.715002 -1.0392687           7 -0.370647 -1.157892 -1.344312  0.8448858           8  1.075770 -0.109050  1.643563 -1.4693889           9  0.357021 -0.674600 -1.776904 -0.968914

Iterating through files chunk by chunk

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

In [160]:print(open('tmp.sv').read())|0|1|2|30|0.469112299907|-0.282863344329|-1.50905850317|-1.135632371021|1.21211202502|-0.173214649053|0.119208711297|-1.044235966282|-0.861848963348|-2.10456921889|-0.494929274069|1.071803807043|0.721555162244|-0.70677113363|-1.03957498511|0.2718598855434|-0.424972329789|0.567020349794|0.276232019278|-1.087400691295|-0.673689708088|0.113648409689|-1.47842655244|0.5249876671156|0.40470521868|0.57704598592|-1.71500201611|-1.039268483517|-0.370646858236|-1.15789225064|-1.34431181273|0.8448851414258|1.07576978372|-0.10904997528|1.64356307036|-1.469387959549|0.357020564133|-0.67460010373|-1.77690371697|-0.968913812447In [161]:table=pd.read_table('tmp.sv',sep='|')In [162]:tableOut[162]:   Unnamed: 0         0         1         2         30           0  0.469112 -0.282863 -1.509059 -1.1356321           1  1.212112 -0.173215  0.119209 -1.0442362           2 -0.861849 -2.104569 -0.494929  1.0718043           3  0.721555 -0.706771 -1.039575  0.2718604           4 -0.424972  0.567020  0.276232 -1.0874015           5 -0.673690  0.113648 -1.478427  0.5249886           6  0.404705  0.577046 -1.715002 -1.0392687           7 -0.370647 -1.157892 -1.344312  0.8448858           8  1.075770 -0.109050  1.643563 -1.4693889           9  0.357021 -0.674600 -1.776904 -0.968914

By specifying achunksize toread_csv orread_table, the returnvalue will be an iterable object of typeTextFileReader:

In [163]:reader=pd.read_table('tmp.sv',sep='|',chunksize=4)In [164]:readerOut[164]:<pandas.io.parsers.TextFileReaderat0x7fd24bc1f310>In [165]:forchunkinreader:   .....:print(chunk)   .....:   Unnamed: 0         0         1         2         30           0  0.469112 -0.282863 -1.509059 -1.1356321           1  1.212112 -0.173215  0.119209 -1.0442362           2 -0.861849 -2.104569 -0.494929  1.0718043           3  0.721555 -0.706771 -1.039575  0.271860   Unnamed: 0         0         1         2         34           4 -0.424972  0.567020  0.276232 -1.0874015           5 -0.673690  0.113648 -1.478427  0.5249886           6  0.404705  0.577046 -1.715002 -1.0392687           7 -0.370647 -1.157892 -1.344312  0.844885   Unnamed: 0         0        1         2         38           8  1.075770 -0.10905  1.643563 -1.4693889           9  0.357021 -0.67460 -1.776904 -0.968914

Specifyingiterator=True will also return theTextFileReader object:

In [166]:reader=pd.read_table('tmp.sv',sep='|',iterator=True)In [167]:reader.get_chunk(5)Out[167]:   Unnamed: 0         0         1         2         30           0  0.469112 -0.282863 -1.509059 -1.1356321           1  1.212112 -0.173215  0.119209 -1.0442362           2 -0.861849 -2.104569 -0.494929  1.0718043           3  0.721555 -0.706771 -1.039575  0.2718604           4 -0.424972  0.567020  0.276232 -1.087401

Specifying the parser engine

Under the hood pandas uses a fast and efficient parser implemented in C as wellas a python implementation which is currently more feature-complete. Wherepossible pandas uses the C parser (specified asengine='c'), but may fallback to python if C-unsupported options are specified. Currently, C-unsupportedoptions include:

  • sep other than a single character (e.g. regex separators)
  • skipfooter
  • sep=None withdelim_whitespace=False

Specifying any of the above options will produce aParserWarning unless thepython engine is selected explicitly usingengine='python'.

Writing out Data

Writing to CSV format

The Series and DataFrame objects have an instance methodto_csv whichallows storing the contents of the object as a comma-separated-values file. Thefunction takes a number of arguments. Only the first is required.

  • path_or_buf: A string path to the file to write or a StringIO
  • sep : Field delimiter for the output file (default ”,”)
  • na_rep: A string representation of a missing value (default ‘’)
  • float_format: Format string for floating point numbers
  • 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), andheader andindex are True, then the index names areused. (A sequence should be given if the DataFrame uses MultiIndex).
  • mode : Python write mode, default ‘w’
  • encoding: a string representing the encoding to use if the contents arenon-ASCII, for python versions prior to 3
  • line_terminator: Character sequence denoting line end (default ‘\n’)
  • quoting: Set quoting rules as in csv module (default csv.QUOTE_MINIMAL). Note that if you have set afloat_format then floats are converted to strings and csv.QUOTE_NONNUMERIC will treat them as non-numeric
  • quotechar: Character used to quote fields (default ‘”’)
  • doublequote: Control quoting ofquotechar in fields (default True)
  • escapechar: Character used to escapesep andquotechar whenappropriate (default None)
  • chunksize: Number of rows to write at a time
  • tupleize_cols: If False (default), write as a list of tuples, otherwisewrite in an expanded line format suitable forread_csv
  • date_format: Format string for datetime objects

Writing a formatted string

The DataFrame object has an instance methodto_string which allows controlover 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 defaultNaN, representation of NA value
  • formatters default None, a dictionary (by column) of functions each ofwhich 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 theDataFrame.
  • sparsify default True, set to False for a DataFrame with a hierarchicalindex 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 defaultleft, will print column headers left- orright-justified

The Series object also has ato_string method, but with only thebuf,na_rep,float_format arguments. There is also alength argumentwhich, if set toTrue, will additionally output the length of the Series.

JSON

Read and writeJSON format files and strings.

Writing JSON

ASeries orDataFrame can be converted to a valid JSON string. Useto_jsonwith optional parameters:

  • path_or_buf : the pathname or buffer to write the outputThis can beNone in which case a JSON string is returned

  • orient :

    Series :
    • default isindex
    • allowed values are {split,records,index}
    DataFrame
    • default iscolumns
    • allowed values are {split,records,index,columns,values}

    The format of the JSON string

    splitdict like {index -> [index], columns -> [columns], data -> [values]}
    recordslist like [{column -> value}, ... , {column -> value}]
    indexdict like {index -> {column -> value}}
    columnsdict like {column -> {index -> value}}
    valuesjust the values array
  • date_format : string, type of date conversion, ‘epoch’ for timestamp, ‘iso’ for ISO8601.

  • 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.

  • date_unit : The time unit to encode to, governs timestamp and ISO8601 precision. One of ‘s’, ‘ms’, ‘us’ or ‘ns’ for seconds, milliseconds, microseconds and nanoseconds respectively. Default ‘ms’.

  • default_handler : The handler to call if an object cannot otherwise be converted to a suitable format for JSON. Takes a single argument, which is the object to convert, and returns a serializable object.

  • lines : Ifrecords orient, then will write each record per line as json.

NoteNaN‘s,NaT‘s andNone will be converted tonull anddatetime objects will be converted based on thedate_format anddate_unit parameters.

In [168]:dfj=pd.DataFrame(randn(5,2),columns=list('AB'))In [169]:json=dfj.to_json()In [170]:jsonOut[170]:'{"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}}'

Orient Options

There are a number of different options for the format of the resulting JSONfile / string. Consider the following DataFrame and Series:

In [171]:dfjo=pd.DataFrame(dict(A=range(1,4),B=range(4,7),C=range(7,10)),   .....:columns=list('ABC'),index=list('xyz'))   .....:In [172]:dfjoOut[172]:   A  B  Cx  1  4  7y  2  5  8z  3  6  9In [173]:sjo=pd.Series(dict(x=15,y=16,z=17),name='D')In [174]:sjoOut[174]:x    15y    16z    17Name: D, dtype: int64

Column oriented (the default forDataFrame) serializes the data asnested JSON objects with column labels acting as the primary index:

In [175]:dfjo.to_json(orient="columns")Out[175]:'{"A":{"x":1,"y":2,"z":3},"B":{"x":4,"y":5,"z":6},"C":{"x":7,"y":8,"z":9}}'

Index oriented (the default forSeries) similar to column orientedbut the index labels are now primary:

In [176]:dfjo.to_json(orient="index")Out[176]:'{"x":{"A":1,"B":4,"C":7},"y":{"A":2,"B":5,"C":8},"z":{"A":3,"B":6,"C":9}}'In [177]:sjo.to_json(orient="index")Out[177]:'{"x":15,"y":16,"z":17}'

Record oriented serializes the data to a JSON array of column -> value records,index labels are not included. This is useful for passing DataFrame data to plottinglibraries, for example the JavaScript library d3.js:

In [178]:dfjo.to_json(orient="records")Out[178]:'[{"A":1,"B":4,"C":7},{"A":2,"B":5,"C":8},{"A":3,"B":6,"C":9}]'In [179]:sjo.to_json(orient="records")Out[179]:'[15,16,17]'

Value oriented is a bare-bones option which serializes to nested JSON arrays ofvalues only, column and index labels are not included:

In [180]:dfjo.to_json(orient="values")Out[180]:'[[1,4,7],[2,5,8],[3,6,9]]'

Split oriented serializes to a JSON object containing separate entries forvalues, index and columns. Name is also included forSeries:

In [181]:dfjo.to_json(orient="split")Out[181]:'{"columns":["A","B","C"],"index":["x","y","z"],"data":[[1,4,7],[2,5,8],[3,6,9]]}'In [182]:sjo.to_json(orient="split")Out[182]:'{"name":"D","index":["x","y","z"],"data":[15,16,17]}'

Note

Any orient option that encodes to a JSON object will not preserve the ordering ofindex and column labels during round-trip serialization. If you wish to preservelabel ordering use thesplit option as it uses ordered containers.

Date Handling

Writing in ISO date format

In [183]:dfd=pd.DataFrame(randn(5,2),columns=list('AB'))In [184]:dfd['date']=pd.Timestamp('20130101')In [185]:dfd=dfd.sort_index(1,ascending=False)In [186]:json=dfd.to_json(date_format='iso')In [187]:jsonOut[187]:'{"date":{"0":"2013-01-01T00:00:00.000Z","1":"2013-01-01T00:00:00.000Z","2":"2013-01-01T00:00:00.000Z","3":"2013-01-01T00:00:00.000Z","4":"2013-01-01T00:00:00.000Z"},"B":{"0":2.5656459463,"1":1.3403088498,"2":-0.2261692849,"3":0.8138502857,"4":-0.8273169356},"A":{"0":-1.2064117817,"1":1.4312559863,"2":-1.1702987971,"3":0.4108345112,"4":0.1320031703}}'

Writing in ISO date format, with microseconds

In [188]:json=dfd.to_json(date_format='iso',date_unit='us')In [189]:jsonOut[189]:'{"date":{"0":"2013-01-01T00:00:00.000000Z","1":"2013-01-01T00:00:00.000000Z","2":"2013-01-01T00:00:00.000000Z","3":"2013-01-01T00:00:00.000000Z","4":"2013-01-01T00:00:00.000000Z"},"B":{"0":2.5656459463,"1":1.3403088498,"2":-0.2261692849,"3":0.8138502857,"4":-0.8273169356},"A":{"0":-1.2064117817,"1":1.4312559863,"2":-1.1702987971,"3":0.4108345112,"4":0.1320031703}}'

Epoch timestamps, in seconds

In [190]:json=dfd.to_json(date_format='epoch',date_unit='s')In [191]:jsonOut[191]:'{"date":{"0":1356998400,"1":1356998400,"2":1356998400,"3":1356998400,"4":1356998400},"B":{"0":2.5656459463,"1":1.3403088498,"2":-0.2261692849,"3":0.8138502857,"4":-0.8273169356},"A":{"0":-1.2064117817,"1":1.4312559863,"2":-1.1702987971,"3":0.4108345112,"4":0.1320031703}}'

Writing to a file, with a date index and a date column

In [192]:dfj2=dfj.copy()In [193]:dfj2['date']=pd.Timestamp('20130101')In [194]:dfj2['ints']=list(range(5))In [195]:dfj2['bools']=TrueIn [196]:dfj2.index=pd.date_range('20130101',periods=5)In [197]:dfj2.to_json('test.json')In [198]:open('test.json').read()Out[198]:'{"A":{"1356998400000":-1.2945235903,"1357084800000":0.2766617129,"1357171200000":-0.0139597524,"1357257600000":-0.0061535699,"1357344000000":0.8957173022},"B":{"1356998400000":0.4137381054,"1357084800000":-0.472034511,"1357171200000":-0.3625429925,"1357257600000":-0.923060654,"1357344000000":0.8052440254},"date":{"1356998400000":1356998400000,"1357084800000":1356998400000,"1357171200000":1356998400000,"1357257600000":1356998400000,"1357344000000":1356998400000},"ints":{"1356998400000":0,"1357084800000":1,"1357171200000":2,"1357257600000":3,"1357344000000":4},"bools":{"1356998400000":true,"1357084800000":true,"1357171200000":true,"1357257600000":true,"1357344000000":true}}'

Fallback Behavior

If the JSON serializer cannot handle the container contents directly it will fallback in the following manner:

  • if the dtype is unsupported (e.g.np.complex) then thedefault_handler, if provided, will be calledfor each value, otherwise an exception is raised.
  • if an object is unsupported it will attempt the following:
    • check if the object has defined atoDict method and call it.AtoDict method should return adict which will then be JSON serialized.
    • invoke thedefault_handler if one was provided.
    • convert the object to adict by traversing its contents. However this will often failwith anOverflowError or give unexpected results.

In general the best approach for unsupported objects or dtypes is to provide adefault_handler.For example:

DataFrame([1.0,2.0,complex(1.0,2.0)]).to_json()# raisesRuntimeError:Unhandlednumpydtype15

can be dealt with by specifying a simpledefault_handler:

In [199]:pd.DataFrame([1.0,2.0,complex(1.0,2.0)]).to_json(default_handler=str)Out[199]:'{"0":{"0":"(1+0j)","1":"(2+0j)","2":"(1+2j)"}}'

Reading JSON

Reading a JSON string to pandas object can take a number of parameters.The parser will try to parse aDataFrame iftyp is not supplied orisNone. To explicitly forceSeries parsing, passtyp=series

  • filepath_or_buffer : aVALID JSON string or file handle / StringIO. The string could bea URL. Valid URL schemes include http, ftp, S3, and file. For file URLs, a hostis expected. For instance, a local file could befile ://localhost/path/to/table.json

  • typ : type of object to recover (series or frame), default ‘frame’

  • orient :

    Series :
    • default isindex
    • allowed values are {split,records,index}
    DataFrame
    • default iscolumns
    • allowed values are {split,records,index,columns,values}

    The format of the JSON string

    splitdict like {index -> [index], columns -> [columns], data -> [values]}
    recordslist like [{column -> value}, ... , {column -> value}]
    indexdict like {index -> {column -> value}}
    columnsdict like {column -> {index -> value}}
    valuesjust 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 date-like columns, default is True

  • keep_default_dates : boolean, default True. If parsing dates, then parse the default date-like columns

  • numpy : direct decoding to numpy arrays. default is False;Supports numeric data only, although labels may be non-numeric. Also note that the JSON orderingMUST be the same for each term ifnumpy=True

  • precise_float : boolean, defaultFalse. 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

  • date_unit : string, the timestamp unit to detect if converting dates. DefaultNone. By default the timestamp precision will be detected, if this is not desiredthen pass one of ‘s’, ‘ms’, ‘us’ or ‘ns’ to force timestamp precision toseconds, milliseconds, microseconds or nanoseconds respectively.

  • lines : reads file as one json object per line.

  • encoding : The encoding to use to decode py3 bytes.

The parser will raise one ofValueError/TypeError/AssertionError if the JSON is not parseable.

If a non-defaultorient was used when encoding to JSON be sure to pass the sameoption here so that decoding produces sensible results, seeOrient Options for anoverview.

Data Conversion

The default ofconvert_axes=True,dtype=True, andconvert_dates=True will try to parse the axes, and all of the datainto appropriate types, including dates. If you need to override specific dtypes, pass a dict todtype.convert_axes should onlybe set toFalse if you need to preserve string-like numbers (e.g. ‘1’, ‘2’) in an axes.

Note

Large integer values may be converted to dates ifconvert_dates=True and the data and / or column labels appear ‘date-like’. The exact threshold depends on thedate_unit specified. ‘date-like’ means that the column label meets one of the following criteria:

  • it ends with'_at'
  • it ends with'_time'
  • it begins with'timestamp'
  • it is'modified'
  • it is'date'

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 wasfloat data will be converted tointeger if it can be done safely, e.g. a column of1.
  • bool columns will be converted tointeger on reconstruction

Thus there are times where you may want to specify specific dtypes via thedtype keyword argument.

Reading from a JSON string:

In [200]:pd.read_json(json)Out[200]:          A         B       date0 -1.206412  2.565646 2013-01-011  1.431256  1.340309 2013-01-012 -1.170299 -0.226169 2013-01-013  0.410835  0.813850 2013-01-014  0.132003 -0.827317 2013-01-01

Reading from a file:

In [201]:pd.read_json('test.json')Out[201]:                   A         B bools       date  ints2013-01-01 -1.294524  0.413738  True 2013-01-01     02013-01-02  0.276662 -0.472035  True 2013-01-01     12013-01-03 -0.013960 -0.362543  True 2013-01-01     22013-01-04 -0.006154 -0.923061  True 2013-01-01     32013-01-05  0.895717  0.805244  True 2013-01-01     4

Don’t convert any data (but still convert axes and dates):

In [202]:pd.read_json('test.json',dtype=object).dtypesOut[202]:A        objectB        objectbools    objectdate     objectints     objectdtype: object

Specify dtypes for conversion:

In [203]:pd.read_json('test.json',dtype={'A':'float32','bools':'int8'}).dtypesOut[203]:A               float32B               float64bools              int8date     datetime64[ns]ints              int64dtype: object

Preserve string indices:

In [204]:si=pd.DataFrame(np.zeros((4,4)),   .....:columns=list(range(4)),   .....:index=[str(i)foriinrange(4)])   .....:In [205]:siOut[205]:     0    1    2    30  0.0  0.0  0.0  0.01  0.0  0.0  0.0  0.02  0.0  0.0  0.0  0.03  0.0  0.0  0.0  0.0In [206]:si.indexOut[206]:Index([u'0',u'1',u'2',u'3'],dtype='object')In [207]:si.columnsOut[207]:Int64Index([0,1,2,3],dtype='int64')In [208]:json=si.to_json()In [209]:sij=pd.read_json(json,convert_axes=False)In [210]:sijOut[210]:   0  1  2  30  0  0  0  01  0  0  0  02  0  0  0  03  0  0  0  0In [211]:sij.indexOut[211]:Index([u'0',u'1',u'2',u'3'],dtype='object')In [212]:sij.columnsOut[212]:Index([u'0',u'1',u'2',u'3'],dtype='object')

Dates written in nanoseconds need to be read back in nanoseconds:

In [213]:json=dfj2.to_json(date_unit='ns')# Try to parse timestamps as millseconds -> Won't WorkIn [214]:dfju=pd.read_json(json,date_unit='ms')In [215]:dfjuOut[215]:                            A         B bools                 date  ints1356998400000000000 -1.294524  0.413738  True  1356998400000000000     01357084800000000000  0.276662 -0.472035  True  1356998400000000000     11357171200000000000 -0.013960 -0.362543  True  1356998400000000000     21357257600000000000 -0.006154 -0.923061  True  1356998400000000000     31357344000000000000  0.895717  0.805244  True  1356998400000000000     4# Let pandas detect the correct precisionIn [216]:dfju=pd.read_json(json)In [217]:dfjuOut[217]:                   A         B bools       date  ints2013-01-01 -1.294524  0.413738  True 2013-01-01     02013-01-02  0.276662 -0.472035  True 2013-01-01     12013-01-03 -0.013960 -0.362543  True 2013-01-01     22013-01-04 -0.006154 -0.923061  True 2013-01-01     32013-01-05  0.895717  0.805244  True 2013-01-01     4# Or specify that all timestamps are in nanosecondsIn [218]:dfju=pd.read_json(json,date_unit='ns')In [219]:dfjuOut[219]:                   A         B bools       date  ints2013-01-01 -1.294524  0.413738  True 2013-01-01     02013-01-02  0.276662 -0.472035  True 2013-01-01     12013-01-03 -0.013960 -0.362543  True 2013-01-01     22013-01-04 -0.006154 -0.923061  True 2013-01-01     32013-01-05  0.895717  0.805244  True 2013-01-01     4

The Numpy Parameter

Note

This supports numeric data only. Index and columns labels may be non-numeric, e.g. strings, dates etc.

Ifnumpy=True is passed toread_json an attempt will be made to sniffan appropriate dtype during deserialization and to subsequently decode directlyto numpy arrays, bypassing the need for intermediate Python objects.

This can provide speedups if you are deserialising a large amount of numericdata:

In [220]:randfloats=np.random.uniform(-100,1000,10000)In [221]:randfloats.shape=(1000,10)In [222]:dffloats=pd.DataFrame(randfloats,columns=list('ABCDEFGHIJ'))In [223]:jsonfloats=dffloats.to_json()
In [224]:timeitpd.read_json(jsonfloats)100 loops, best of 3: 10.4 ms per loop
In [225]:timeitpd.read_json(jsonfloats,numpy=True)100 loops, best of 3: 5.89 ms per loop

The speedup is less noticeable for smaller datasets:

In [226]:jsonfloats=dffloats.head(100).to_json()
In [227]:timeitpd.read_json(jsonfloats)100 loops, best of 3: 4.88 ms per loop
In [228]:timeitpd.read_json(jsonfloats,numpy=True)100 loops, best of 3: 3.97 ms per loop

Warning

Direct numpy decoding makes a number of assumptions and may fail or produceunexpected output if these assumptions are not satisfied:

  • data is numeric.
  • data is uniform. The dtype is sniffed from the first value decoded.AValueError may be raised, or incorrect output may be producedif this condition is not satisfied.
  • labels are ordered. Labels are only read from the first container, it is assumedthat each subsequent row / column has been encoded in the same order. This should be satisfied if thedata was encoded usingto_json but may not be the case if the JSONis from another source.

Normalization

New in version 0.13.0.

pandas provides a utility function to take a dict or list of dicts andnormalize this semi-structured datainto a flat table.

In [229]:frompandas.io.jsonimportjson_normalizeIn [230]:data=[{'state':'Florida',   .....:'shortname':'FL',   .....:'info':{   .....:'governor':'Rick Scott'   .....:},   .....:'counties':[{'name':'Dade','population':12345},   .....:{'name':'Broward','population':40000},   .....:{'name':'Palm Beach','population':60000}]},   .....:{'state':'Ohio',   .....:'shortname':'OH',   .....:'info':{   .....:'governor':'John Kasich'   .....:},   .....:'counties':[{'name':'Summit','population':1234},   .....:{'name':'Cuyahoga','population':1337}]}]   .....:In [231]:json_normalize(data,'counties',['state','shortname',['info','governor']])Out[231]:         name  population info.governor    state shortname0        Dade       12345    Rick Scott  Florida        FL1     Broward       40000    Rick Scott  Florida        FL2  Palm Beach       60000    Rick Scott  Florida        FL3      Summit        1234   John Kasich     Ohio        OH4    Cuyahoga        1337   John Kasich     Ohio        OH

Line delimited json

New in version 0.19.0.

pandas is able to read and write line-delimited json files that are common in data processing pipelinesusing Hadoop or Spark.

In [232]:jsonl='''   .....:     {"a":1,"b":2}   .....:     {"a":3,"b":4}   .....: '''   .....:In [233]:df=pd.read_json(jsonl,lines=True)In [234]:dfOut[234]:   a  b0  1  21  3  4In [235]:df.to_json(orient='records',lines=True)Out[235]:u'{"a":1,"b":2}\n{"a":3,"b":4}'

HTML

Reading HTML Content

Warning

Wehighly encourage you to read theHTML parsing gotchas regarding the issues surrounding theBeautifulSoup4/html5lib/lxml parsers.

New in version 0.12.0.

The top-levelread_html() function can accept an HTMLstring/file/URL and will parse HTML tables into list of pandas DataFrames.Let’s look at a few examples.

Note

read_html returns alist ofDataFrame objects, even if there isonly a single table contained in the HTML content

Read a URL with no options

In [236]:url='http://www.fdic.gov/bank/individual/failed/banklist.html'In [237]:dfs=pd.read_html(url)In [238]:dfsOut[238]:[                             Bank Name             City  ST   CERT  \ 0                          Allied Bank         Mulberry  AR     91 1         The Woodbury Banking Company         Woodbury  GA  11297 2               First CornerStone Bank  King of Prussia  PA  35312 3                   Trust Company Bank          Memphis  TN   9956 4           North Milwaukee State Bank        Milwaukee  WI  20364 5               Hometown National Bank         Longview  WA  35156 6                  The Bank of Georgia   Peachtree City  GA  35259 ..                                 ...              ...  ..    ... 540      Hamilton Bank, NA  En Espanol            Miami  FL  24382 541             Sinclair National Bank         Gravette  AR  34248 542                 Superior Bank, FSB         Hinsdale  IL  32646 543                Malta National Bank            Malta  OH   6629 544    First Alliance Bank & Trust Co.       Manchester  NH  34264 545  National State Bank of Metropolis       Metropolis  IL   3815 546                   Bank of Honolulu         Honolulu  HI  21029                    Acquiring Institution        Closing Date  \ 0                           Today's Bank  September 23, 2016 1                            United Bank     August 19, 2016 2    First-Citizens Bank & Trust Company         May 6, 2016 3             The Bank of Fayette County      April 29, 2016 4    First-Citizens Bank & Trust Company      March 11, 2016 5                         Twin City Bank     October 2, 2015 6                          Fidelity Bank     October 2, 2015 ..                                   ...                 ... 540     Israel Discount Bank of New York    January 11, 2002 541                   Delta Trust & Bank   September 7, 2001 542                Superior Federal, FSB       July 27, 2001 543                    North Valley Bank         May 3, 2001 544  Southern New Hampshire Bank & Trust    February 2, 2001 545              Banterra Bank of Marion   December 14, 2000 546                   Bank of the Orient    October 13, 2000            Updated Date 0      October 17, 2016 1      October 17, 2016 2     September 6, 2016 3     September 6, 2016 4         June 16, 2016 5        April 13, 2016 6      October 24, 2016 ..                  ... 540  September 21, 2015 541   February 10, 2004 542     August 19, 2014 543   November 18, 2002 544   February 18, 2003 545      March 17, 2005 546      March 17, 2005 [547 rows x 7 columns]]

Note

The data from the above URL changes every Monday so the resulting data aboveand the data below may be slightly different.

Read in the content of the file from the above URL and pass it toread_htmlas a string

In [239]:withopen(file_path,'r')asf:   .....:dfs=pd.read_html(f.read())   .....:In [240]:dfsOut[240]:[                                    Bank Name          City  ST   CERT  \ 0    Banks of Wisconsin d/b/a Bank of Kenosha       Kenosha  WI  35386 1                        Central Arizona Bank    Scottsdale  AZ  34527 2                                Sunrise Bank      Valdosta  GA  58185 3                       Pisgah Community Bank     Asheville  NC  58701 4                         Douglas County Bank  Douglasville  GA  21649 5                                Parkway Bank        Lenoir  NC  57158 6                      Chipola Community Bank      Marianna  FL  58034 ..                                        ...           ...  ..    ... 499               Hamilton Bank, NAEn Espanol         Miami  FL  24382 500                    Sinclair National Bank      Gravette  AR  34248 501                        Superior Bank, FSB      Hinsdale  IL  32646 502                       Malta National Bank         Malta  OH   6629 503           First Alliance Bank & Trust Co.    Manchester  NH  34264 504         National State Bank of Metropolis    Metropolis  IL   3815 505                          Bank of Honolulu      Honolulu  HI  21029                    Acquiring Institution       Closing Date       Updated Date 0                  North Shore Bank, FSB       May 31, 2013       May 31, 2013 1                     Western State Bank       May 14, 2013       May 20, 2013 2                           Synovus Bank       May 10, 2013       May 21, 2013 3                     Capital Bank, N.A.       May 10, 2013       May 14, 2013 4                    Hamilton State Bank     April 26, 2013       May 16, 2013 5       CertusBank, National Association     April 26, 2013       May 17, 2013 6          First Federal Bank of Florida     April 19, 2013       May 16, 2013 ..                                   ...                ...                ... 499     Israel Discount Bank of New York   January 11, 2002       June 5, 2012 500                   Delta Trust & Bank  September 7, 2001  February 10, 2004 501                Superior Federal, FSB      July 27, 2001       June 5, 2012 502                    North Valley Bank        May 3, 2001  November 18, 2002 503  Southern New Hampshire Bank & Trust   February 2, 2001  February 18, 2003 504              Banterra Bank of Marion  December 14, 2000     March 17, 2005 505                   Bank of the Orient   October 13, 2000     March 17, 2005 [506 rows x 7 columns]]

You can even pass in an instance ofStringIO if you so desire

In [241]:withopen(file_path,'r')asf:   .....:sio=StringIO(f.read())   .....:In [242]:dfs=pd.read_html(sio)In [243]:dfsOut[243]:[                                    Bank Name          City  ST   CERT  \ 0    Banks of Wisconsin d/b/a Bank of Kenosha       Kenosha  WI  35386 1                        Central Arizona Bank    Scottsdale  AZ  34527 2                                Sunrise Bank      Valdosta  GA  58185 3                       Pisgah Community Bank     Asheville  NC  58701 4                         Douglas County Bank  Douglasville  GA  21649 5                                Parkway Bank        Lenoir  NC  57158 6                      Chipola Community Bank      Marianna  FL  58034 ..                                        ...           ...  ..    ... 499               Hamilton Bank, NAEn Espanol         Miami  FL  24382 500                    Sinclair National Bank      Gravette  AR  34248 501                        Superior Bank, FSB      Hinsdale  IL  32646 502                       Malta National Bank         Malta  OH   6629 503           First Alliance Bank & Trust Co.    Manchester  NH  34264 504         National State Bank of Metropolis    Metropolis  IL   3815 505                          Bank of Honolulu      Honolulu  HI  21029                    Acquiring Institution       Closing Date       Updated Date 0                  North Shore Bank, FSB       May 31, 2013       May 31, 2013 1                     Western State Bank       May 14, 2013       May 20, 2013 2                           Synovus Bank       May 10, 2013       May 21, 2013 3                     Capital Bank, N.A.       May 10, 2013       May 14, 2013 4                    Hamilton State Bank     April 26, 2013       May 16, 2013 5       CertusBank, National Association     April 26, 2013       May 17, 2013 6          First Federal Bank of Florida     April 19, 2013       May 16, 2013 ..                                   ...                ...                ... 499     Israel Discount Bank of New York   January 11, 2002       June 5, 2012 500                   Delta Trust & Bank  September 7, 2001  February 10, 2004 501                Superior Federal, FSB      July 27, 2001       June 5, 2012 502                    North Valley Bank        May 3, 2001  November 18, 2002 503  Southern New Hampshire Bank & Trust   February 2, 2001  February 18, 2003 504              Banterra Bank of Marion  December 14, 2000     March 17, 2005 505                   Bank of the Orient   October 13, 2000     March 17, 2005 [506 rows x 7 columns]]

Note

The following examples are not run by the IPython evaluator due to the factthat having so many network-accessing functions slows down the documentationbuild. If you spot an error or an example that doesn’t run, please do nothesitate to report it over onpandas GitHub issues page.

Read a URL and match a table that contains specific text

match='Metcalf Bank'df_list=pd.read_html(url,match=match)

Specify a header row (by default<th> elements are used to form the columnindex); if specified, the header row is taken from the data minus the parsedheader elements (<th> elements).

dfs=pd.read_html(url,header=0)

Specify an index column

dfs=pd.read_html(url,index_col=0)

Specify a number of rows to skip

dfs=pd.read_html(url,skiprows=0)

Specify a number of rows to skip using a list (xrange (Python 2 only) worksas well)

dfs=pd.read_html(url,skiprows=range(2))

Specify an HTML attribute

dfs1=pd.read_html(url,attrs={'id':'table'})dfs2=pd.read_html(url,attrs={'class':'sortable'})print(np.array_equal(dfs1[0],dfs2[0]))# Should be True

Specify values that should be converted to NaN

dfs=pd.read_html(url,na_values=['No Acquirer'])

New in version 0.19.

Specify whether to keep the default set of NaN values

dfs=pd.read_html(url,keep_default_na=False)

New in version 0.19.

Specify converters for columns. This is useful for numerical text data that hasleading zeros. By default columns that are numerical are cast to numerictypes and the leading zeros are lost. To avoid this, we can convert thesecolumns to strings.

url_mcc='https://en.wikipedia.org/wiki/Mobile_country_code'dfs=pd.read_html(url_mcc,match='Telekom Albania',header=0,converters={'MNC':str})

New in version 0.19.

Use some combination of the above

dfs=pd.read_html(url,match='Metcalf Bank',index_col=0)

Read in pandasto_html output (with some loss of floating point precision)

df=pd.DataFrame(randn(2,2))s=df.to_html(float_format='{0:.40g}'.format)dfin=pd.read_html(s,index_col=0)

Thelxml backend will raise an error on a failed parse if that is the onlyparser you provide (if you only have a single parser you can provide just astring, but it is considered good practice to pass a list with one string if,for example, the function expects a sequence of strings)

dfs=pd.read_html(url,'Metcalf Bank',index_col=0,flavor=['lxml'])

or

dfs=pd.read_html(url,'Metcalf Bank',index_col=0,flavor='lxml')

However, if you have bs4 and html5lib installed and passNone or['lxml','bs4'] then the parse will most likely succeed. Note thatas soon as a parsesucceeds, the function will return.

dfs=pd.read_html(url,'Metcalf Bank',index_col=0,flavor=['lxml','bs4'])

Writing to HTML files

DataFrame objects have an instance methodto_html which renders thecontents of theDataFrame as an HTML table. The function arguments are asin the methodto_string described above.

Note

Not all of the possible options forDataFrame.to_html are shown here forbrevity’s sake. Seeto_html() for thefull set of options.

In [244]:df=pd.DataFrame(randn(2,2))In [245]:dfOut[245]:          0         10 -0.184744  0.4969711 -0.856240  1.857977In [246]: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.184744</td>      <td>0.496971</td>    </tr>    <tr>      <th>1</th>      <td>-0.856240</td>      <td>1.857977</td>    </tr>  </tbody></table>

HTML:

01
0-0.1847440.496971
1-0.8562401.857977

Thecolumns argument will limit the columns shown

In [247]: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.184744</td>    </tr>    <tr>      <th>1</th>      <td>-0.856240</td>    </tr>  </tbody></table>

HTML:

0
0-0.184744
1-0.856240

float_format takes a Python callable to control the precision of floatingpoint values

In [248]: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.1847438576</td>      <td>0.4969711327</td>    </tr>    <tr>      <th>1</th>      <td>-0.8562396763</td>      <td>1.8579766508</td>    </tr>  </tbody></table>

HTML:

01
0-0.18474385760.4969711327
1-0.85623967631.8579766508

bold_rows will make the row labels bold by default, but you can turn thatoff

In [249]: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.184744</td>      <td>0.496971</td>    </tr>    <tr>      <td>1</td>      <td>-0.856240</td>      <td>1.857977</td>    </tr>  </tbody></table>
01
0-0.1847440.496971
1-0.8562401.857977

Theclasses argument provides the ability to give the resulting HTMLtable CSS classes. Note that these classes areappended to the existing'dataframe' class.

In [250]: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.184744</td>      <td>0.496971</td>    </tr>    <tr>      <th>1</th>      <td>-0.856240</td>      <td>1.857977</td>    </tr>  </tbody></table>

Finally, theescape argument allows you to control whether the“<”, “>” and “&” characters escaped in the resulting HTML (by default it isTrue). So to get the HTML without escaped characters passescape=False

In [251]:df=pd.DataFrame({'a':list('&<>'),'b':randn(3)})

Escaped:

In [252]: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>&amp;</td>      <td>-0.474063</td>    </tr>    <tr>      <th>1</th>      <td>&lt;</td>      <td>-0.230305</td>    </tr>    <tr>      <th>2</th>      <td>&gt;</td>      <td>-0.400654</td>    </tr>  </tbody></table>
ab
0&-0.474063
1<-0.230305
2>-0.400654

Not escaped:

In [253]: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>-0.474063</td>    </tr>    <tr>      <th>1</th>      <td><</td>      <td>-0.230305</td>    </tr>    <tr>      <th>2</th>      <td>></td>      <td>-0.400654</td>    </tr>  </tbody></table>
ab
0&-0.474063
1<-0.230305
2>-0.400654

Note

Some browsers may not show a difference in the rendering of the previous twoHTML tables.

Excel files

Theread_excel() method can read Excel 2003 (.xls) andExcel 2007+ (.xlsx) files using thexlrd Pythonmodule. Theto_excel() instance method is used forsaving aDataFrame to Excel. Generally the semantics aresimilar to working withcsv data. See thecookbook for someadvanced strategies

Reading Excel Files

In the most basic use-case,read_excel takes a path to an Excelfile, and thesheetname indicating which sheet to parse.

# Returns a DataFrameread_excel('path_to_file.xls',sheetname='Sheet1')

ExcelFile class

To facilitate working with multiple sheets from the same file, theExcelFileclass can be used to wrap the file and can be be passed intoread_excelThere will be a performance benefit for reading multiple sheets as the file isread into memory only once.

xlsx=pd.ExcelFile('path_to_file.xls)df=pd.read_excel(xlsx,'Sheet1')

TheExcelFile class can also be used as a context manager.

withpd.ExcelFile('path_to_file.xls')asxls:df1=pd.read_excel(xls,'Sheet1')df2=pd.read_excel(xls,'Sheet2')

Thesheet_names property will generatea list of the sheet names in the file.

The primary use-case for anExcelFile is parsing multiple sheets withdifferent parameters

data={}# For when Sheet1's format differs from Sheet2withpd.ExcelFile('path_to_file.xls')asxls:data['Sheet1']=pd.read_excel(xls,'Sheet1',index_col=None,na_values=['NA'])data['Sheet2']=pd.read_excel(xls,'Sheet2',index_col=1)

Note that if the same parsing parameters are used for all sheets, a listof sheet names can simply be passed toread_excel with no loss in performance.

# using the ExcelFile classdata={}withpd.ExcelFile('path_to_file.xls')asxls:data['Sheet1']=read_excel(xls,'Sheet1',index_col=None,na_values=['NA'])data['Sheet2']=read_excel(xls,'Sheet2',index_col=None,na_values=['NA'])# equivalent using the read_excel functiondata=read_excel('path_to_file.xls',['Sheet1','Sheet2'],index_col=None,na_values=['NA'])

New in version 0.12.

ExcelFile has been moved to the top level namespace.

New in version 0.17.

read_excel can take anExcelFile object as input

Specifying Sheets

Note

The second argument issheetname, not to be confused withExcelFile.sheet_names

Note

An ExcelFile’s attributesheet_names provides access to a list of sheets.

  • The argumentssheetname allows specifying the sheet or sheets to read.
  • The default value forsheetname is 0, indicating to read the first sheet
  • Pass a string to refer to the name of a particular sheet in the workbook.
  • Pass an integer to refer to the index of a sheet. Indices follow Pythonconvention, beginning at 0.
  • Pass a list of either strings or integers, to return a dictionary of specified sheets.
  • Pass aNone to return a dictionary of all available sheets.
# Returns a DataFrameread_excel('path_to_file.xls','Sheet1',index_col=None,na_values=['NA'])

Using the sheet index:

# Returns a DataFrameread_excel('path_to_file.xls',0,index_col=None,na_values=['NA'])

Using all default values:

# Returns a DataFrameread_excel('path_to_file.xls')

Using None to get all sheets:

# Returns a dictionary of DataFramesread_excel('path_to_file.xls',sheetname=None)

Using a list to get multiple sheets:

# Returns the 1st and 4th sheet, as a dictionary of DataFrames.read_excel('path_to_file.xls',sheetname=['Sheet1',3])

New in version 0.16.

read_excel can read more than one sheet, by settingsheetname to eithera list of sheet names, a list of sheet positions, orNone to read all sheets.

New in version 0.13.

Sheets can be specified by sheet index or sheet name, using an integer or string,respectively.

Reading aMultiIndex

New in version 0.17.

read_excel can read aMultiIndex index, by passing a list of columns toindex_coland aMultiIndex column by passing a list of rows toheader. If either theindexorcolumns have serialized level names those will be read in as well by specifyingthe rows/columns that make up the levels.

For example, to read in aMultiIndex index without names:

In [254]:df=pd.DataFrame({'a':[1,2,3,4],'b':[5,6,7,8]},   .....:index=pd.MultiIndex.from_product([['a','b'],['c','d']]))   .....:In [255]:df.to_excel('path_to_file.xlsx')In [256]:df=pd.read_excel('path_to_file.xlsx',index_col=[0,1])In [257]:dfOut[257]:     a  ba c  1  5  d  2  6b c  3  7  d  4  8

If the index has level names, they will parsed as well, using the sameparameters.

In [258]:df.index=df.index.set_names(['lvl1','lvl2'])In [259]:df.to_excel('path_to_file.xlsx')In [260]:df=pd.read_excel('path_to_file.xlsx',index_col=[0,1])In [261]:dfOut[261]:           a  blvl1 lvl2a    c     1  5     d     2  6b    c     3  7     d     4  8

If the source file has bothMultiIndex index and columns, lists specifying eachshould be passed toindex_col andheader

In [262]:df.columns=pd.MultiIndex.from_product([['a'],['b','d']],names=['c1','c2'])In [263]:df.to_excel('path_to_file.xlsx')In [264]:df=pd.read_excel('path_to_file.xlsx',   .....:index_col=[0,1],header=[0,1])   .....:In [265]:dfOut[265]:c1         ac2         b  dlvl1 lvl2a    c     1  5     d     2  6b    c     3  7     d     4  8

Warning

Excel files saved in version 0.16.2 or prior that had index names will still able to be read in,but thehas_index_names argument must specified toTrue.

Parsing Specific Columns

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

Ifparse_cols is an integer, then it is assumed to indicate the last columnto be parsed.

read_excel('path_to_file.xls','Sheet1',parse_cols=2)

Ifparse_cols is a list of integers, then it is assumed to be the file columnindices to be parsed.

read_excel('path_to_file.xls','Sheet1',parse_cols=[0,2,3])

Cell Converters

It is possible to transform the contents of Excel cells via theconvertersoption. For instance, to convert a column to boolean:

read_excel('path_to_file.xls','Sheet1',converters={'MyBools':bool})

This options handles missing values and treats exceptions in the convertersas missing data. Transformations are applied cell by cell rather than to thecolumn as a whole, so the array dtype is not guaranteed. For instance, acolumn of integers with missing values cannot be transformed to an arraywith integer dtype, because NaN is strictly a float. You can manually maskmissing data to recover integer dtype:

cfun=lambdax:int(x)ifxelse-1read_excel('path_to_file.xls','Sheet1',converters={'MyInts':cfun})

Writing Excel Files

Writing Excel Files to Disk

To write a DataFrame object to a sheet of an Excel file, you can use theto_excel instance method. The arguments are largely the same asto_csvdescribed above, the first argument being the name of the excel file, and theoptional second argument the name of the sheet to which the DataFrame should bewritten. For example:

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

Files with a.xls extension will be written usingxlwt and those with a.xlsx extension will be written usingxlsxwriter (if available) oropenpyxl.

The DataFrame will be written in a way that tries to mimic the REPL output. Onedifference from 0.12.0 is that theindex_label will be placed in the secondrow instead of the first. You can get the previous behaviour by setting themerge_cells option into_excel() toFalse:

df.to_excel('path_to_file.xlsx',index_label='label',merge_cells=False)

The Panel class also has ato_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 pass anExcelWriter.

withExcelWriter('path_to_file.xlsx')aswriter:df1.to_excel(writer,sheet_name='Sheet1')df2.to_excel(writer,sheet_name='Sheet2')

Note

Wringing a little more performance out ofread_excelInternally, Excel stores all numeric data as floats. Because this canproduce unexpected behavior when reading in data, pandas defaults to tryingto convert integers to floats if it doesn’t lose information (1.0-->1). You can passconvert_float=False to disable this behavior, whichmay give a slight performance improvement.

Writing Excel Files to Memory

New in version 0.17.

Pandas supports writing Excel files to buffer-like objects such asStringIO orBytesIO usingExcelWriter.

New in version 0.17.

Added support for Openpyxl >= 2.2

# Safe import for either Python 2.x or 3.xtry:fromioimportBytesIOexceptImportError:fromcStringIOimportStringIOasBytesIObio=BytesIO()# By setting the 'engine' in the ExcelWriter constructor.writer=ExcelWriter(bio,engine='xlsxwriter')df.to_excel(writer,sheet_name='Sheet1')# Save the workbookwriter.save()# Seek to the beginning and read to copy the workbook to a variable in memorybio.seek(0)workbook=bio.read()

Note

engine is optional but recommended. Setting the engine determinesthe version of workbook produced. Settingengine='xlrd' will produce anExcel 2003-format workbook (xls). Using either'openpyxl' or'xlsxwriter' will produce an Excel 2007-format workbook (xlsx). Ifomitted, an Excel 2007-formatted workbook is produced.

Excel writer engines

New in version 0.13.

pandas chooses an Excel writer via two methods:

  1. theengine keyword argument
  2. the filename extension (via the default specified in config options)

By default,pandas uses theXlsxWriter for.xlsx andopenpyxlfor.xlsm files andxlwt for.xls files. If you have multipleengines installed, you can set the default engine throughsetting theconfig optionsio.excel.xlsx.writer andio.excel.xls.writer. pandas will fall back onopenpyxl for.xlsxfiles ifXlsxwriter is not available.

To specify which writer you want to use, you can pass an engine keywordargument toto_excel and toExcelWriter. The built-in engines are:

  • openpyxl: This includes stable support for Openpyxl from 1.6.1. However,it is advised to use version 2.2 and higher, especially when working withstyles.
  • xlsxwriter
  • xlwt
# By setting the 'engine' in the DataFrame and Panel 'to_excel()' methods.df.to_excel('path_to_file.xlsx',sheet_name='Sheet1',engine='xlsxwriter')# By setting the 'engine' in the ExcelWriter constructor.writer=ExcelWriter('path_to_file.xlsx',engine='xlsxwriter')# Or via pandas configuration.frompandasimportoptionsoptions.io.excel.xlsx.writer='xlsxwriter'df.to_excel('path_to_file.xlsx',sheet_name='Sheet1')

Clipboard

A handy way to grab data is to use theread_clipboard method, which takesthe contents of the clipboard buffer and passes them to theread_tablemethod. For instance, you can copy the followingtext to the clipboard (CTRL-C on many operating systems):

ABCx14py25qz36r

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

clipdf=pd.read_clipboard()
In [266]:clipdfOut[266]:   A  B  Cx  1  4  py  2  5  qz  3  6  r

Theto_clipboard method can be used to write the contents of a DataFrame tothe clipboard. Following which you can paste the clipboard contents into otherapplications (CTRL-V on many operating systems). Here we illustrate writing aDataFrame into clipboard and reading it back.

In [267]:df=pd.DataFrame(randn(5,3))In [268]:dfOut[268]:          0         1         20 -0.288267 -0.084905  0.0047721  1.382989  0.343635 -1.2539942 -0.124925  0.212244  0.4966543  0.525417  1.238640 -1.2105434 -1.175743 -0.172372 -0.734129In [269]:df.to_clipboard()In [270]:pd.read_clipboard()Out[270]:          0         1         20 -0.288267 -0.084905  0.0047721  1.382989  0.343635 -1.2539942 -0.124925  0.212244  0.4966543  0.525417  1.238640 -1.2105434 -1.175743 -0.172372 -0.734129

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

All pandas objects are equipped withto_pickle methods which use Python’scPickle module to save data structures to disk using the pickle format.

In [271]:dfOut[271]:          0         1         20 -0.288267 -0.084905  0.0047721  1.382989  0.343635 -1.2539942 -0.124925  0.212244  0.4966543  0.525417  1.238640 -1.2105434 -1.175743 -0.172372 -0.734129In [272]:df.to_pickle('foo.pkl')

Theread_pickle function in thepandas namespace can be used to loadany pickled pandas object (or any other pickled object) from file:

In [273]:pd.read_pickle('foo.pkl')Out[273]:          0         1         20 -0.288267 -0.084905  0.0047721  1.382989  0.343635 -1.2539942 -0.124925  0.212244  0.4966543  0.525417  1.238640 -1.2105434 -1.175743 -0.172372 -0.734129

Warning

Loading pickled data received from untrusted sources can be unsafe.

See:http://docs.python.org/2.7/library/pickle.html

Warning

Several internal refactorings, 0.13 (Series Refactoring), and 0.15 (Index Refactoring),preserve compatibility with pickles created prior to these versions. However, these mustbe read withpd.read_pickle, rather than the default pythonpickle.load.Seethis questionfor a detailed explanation.

Note

These methods were previouslypd.save andpd.load, prior to 0.12.0, and are now deprecated.

msgpack (experimental)

New in version 0.13.0.

Starting in 0.13.0, pandas is supporting themsgpack format forobject serialization. This is a lightweight portable binary format, similarto binary JSON, that is highly space efficient, and provides good performanceboth on the writing (serialization), and reading (deserialization).

Warning

This is a very new feature of pandas. We intend to provide certainoptimizations in the io of themsgpack data. Since this is markedas an EXPERIMENTAL LIBRARY, the storage format may not be stable until a future release.

As a result of writing format changes and other issues:

Packed withCan be unpacked with
pre-0.17 / Python 2any
pre-0.17 / Python 3any
0.17 / Python 2
  • 0.17 / Python 2
  • >=0.18 / any Python
0.17 / Python 3>=0.18 / any Python
0.18>= 0.18

Reading (files packed by older versions) is backward-compatibile, except for files packed with 0.17 in Python 2, in which case only they can only be unpacked in Python 2.

In [274]:df=pd.DataFrame(np.random.rand(5,2),columns=list('AB'))In [275]:df.to_msgpack('foo.msg')In [276]:pd.read_msgpack('foo.msg')Out[276]:          A         B0  0.154336  0.7109991  0.398096  0.7652202  0.586749  0.2930523  0.290293  0.7107834  0.988593  0.062106In [277]:s=pd.Series(np.random.rand(5),index=pd.date_range('20130101',periods=5))

You can pass a list of objects and you will receive them back on deserialization.

In [278]:pd.to_msgpack('foo.msg',df,'foo',np.array([1,2,3]),s)In [279]:pd.read_msgpack('foo.msg')Out[279]:[          A         B 0  0.154336  0.710999 1  0.398096  0.765220 2  0.586749  0.293052 3  0.290293  0.710783 4  0.988593  0.062106, 'foo', array([1, 2, 3]), 2013-01-01    0.690810 2013-01-02    0.235907 2013-01-03    0.712756 2013-01-04    0.119599 2013-01-05    0.023493 Freq: D, dtype: float64]

You can passiterator=True to iterate over the unpacked results

In [280]:foroinpd.read_msgpack('foo.msg',iterator=True):   .....:printo   .....:          A         B0  0.154336  0.7109991  0.398096  0.7652202  0.586749  0.2930523  0.290293  0.7107834  0.988593  0.062106foo[1 2 3]2013-01-01    0.6908102013-01-02    0.2359072013-01-03    0.7127562013-01-04    0.1195992013-01-05    0.023493Freq: D, dtype: float64

You can passappend=True to the writer to append to an existing pack

In [281]:df.to_msgpack('foo.msg',append=True)In [282]:pd.read_msgpack('foo.msg')Out[282]:[          A         B 0  0.154336  0.710999 1  0.398096  0.765220 2  0.586749  0.293052 3  0.290293  0.710783 4  0.988593  0.062106, 'foo', array([1, 2, 3]), 2013-01-01    0.690810 2013-01-02    0.235907 2013-01-03    0.712756 2013-01-04    0.119599 2013-01-05    0.023493 Freq: D, dtype: float64,           A         B 0  0.154336  0.710999 1  0.398096  0.765220 2  0.586749  0.293052 3  0.290293  0.710783 4  0.988593  0.062106]

Unlike other io methods,to_msgpack is available on both a per-object basis,df.to_msgpack() and using the top-levelpd.to_msgpack(...) where youcan pack arbitrary collections of python lists, dicts, scalars, while intermixingpandas objects.

In [283]:pd.to_msgpack('foo2.msg',{'dict':[{'df':df},{'string':'foo'},{'scalar':1.},{'s':s}]})In [284]:pd.read_msgpack('foo2.msg')Out[284]:{'dict': ({'df':           A         B   0  0.154336  0.710999   1  0.398096  0.765220   2  0.586749  0.293052   3  0.290293  0.710783   4  0.988593  0.062106},  {'string': 'foo'},  {'scalar': 1.0},  {'s': 2013-01-01    0.690810   2013-01-02    0.235907   2013-01-03    0.712756   2013-01-04    0.119599   2013-01-05    0.023493   Freq: D, dtype: float64})}

Read/Write API

Msgpacks can also be read from and written to strings.

In [285]:df.to_msgpack()Out[285]:'\x84\xa6blocks\x91\x86\xa5dtype\xa7float64\xa8compress\xc0\xa4locs\x86\xa4ndim\x01\xa5dtype\xa5int64\xa8compress\xc0\xa4data\xd8\x00\x00\x00\x00\x00\x00\x00\x00\x00\x01\x00\x00\x00\x00\x00\x00\x00\xa5shape\x91\x02\xa3typ\xa7ndarray\xa5shape\x92\x02\x05\xa6values\xc7P\x00\xa0\xab\xfb6H\xc1\xc3?\x98(oMgz\xd9?\x17\xaed\\\xa5\xc6\xe2?\xdc\xd0\x1bd(\x94\xd2?\xb5\xe8\xf5\x0e\x8d\xa2\xef?\x02D\xebO\x80\xc0\xe6?\x16\xbddQ\xae|\xe8?\x10?Ya[\xc1\xd2?\xa8\xfd\xcf\xa0\xbc\xbe\xe6? Z\xe1\ti\xcc\xaf?\xa5klass\xaaFloatBlock\xa4axes\x92\x86\xa4name\xc0\xa5dtype\xa6object\xa8compress\xc0\xa4data\x92\xc4\x01A\xc4\x01B\xa5klass\xa5Index\xa3typ\xa5index\x86\xa4name\xc0\xa4stop\x05\xa5start\x00\xa4step\x01\xa5klass\xaaRangeIndex\xa3typ\xabrange_index\xa3typ\xadblock_manager\xa5klass\xa9DataFrame'

Furthermore you can concatenate the strings to produce a list of the original objects.

In [286]:pd.read_msgpack(df.to_msgpack()+s.to_msgpack())Out[286]:[          A         B 0  0.154336  0.710999 1  0.398096  0.765220 2  0.586749  0.293052 3  0.290293  0.710783 4  0.988593  0.062106, 2013-01-01    0.690810 2013-01-02    0.235907 2013-01-03    0.712756 2013-01-04    0.119599 2013-01-05    0.023493 Freq: D, dtype: float64]

HDF5 (PyTables)

HDFStore is a dict-like object which reads and writes pandas usingthe high performance HDF5 format using the excellentPyTables library. See thecookbookfor some advanced strategies

Warning

As of version 0.15.0, pandas requiresPyTables >= 3.0.0. Stores written with prior versions of pandas /PyTables >= 2.3 are fully compatible (this was the previous minimumPyTables required version).

Warning

There is aPyTables indexing bug which may appear when querying stores using an index. If you see a subset of results being returned, upgrade toPyTables >= 3.2. Stores created previously will need to be rewritten using the updated version.

Warning

As of version 0.17.0,HDFStore will not drop rows that have all missing values by default. Previously, if all values (except the index) were missing,HDFStore would not write those rows to disk.

In [287]:store=pd.HDFStore('store.h5')In [288]:print(store)<class 'pandas.io.pytables.HDFStore'>File path: store.h5Empty

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

In [289]:np.random.seed(1234)In [290]:index=pd.date_range('1/1/2000',periods=8)In [291]:s=pd.Series(randn(5),index=['a','b','c','d','e'])In [292]:df=pd.DataFrame(randn(8,3),index=index,   .....:columns=['A','B','C'])   .....:In [293]:wp=pd.Panel(randn(2,5,4),items=['Item1','Item2'],   .....:major_axis=pd.date_range('1/1/2000',periods=5),   .....:minor_axis=['A','B','C','D'])   .....:# store.put('s', s) is an equivalent methodIn [294]:store['s']=sIn [295]:store['df']=dfIn [296]:store['wp']=wp# the type of stored dataIn [297]:store.root.wp._v_attrs.pandas_typeOut[297]:'wide'In [298]:storeOut[298]:<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 methodIn [299]:store['df']Out[299]:                   A         B         C2000-01-01  0.887163  0.859588 -0.6365242000-01-02  0.015696 -2.242685  1.1500362000-01-03  0.991946  0.953324 -2.0212552000-01-04 -0.334077  0.002118  0.4054532000-01-05  0.289092  1.321158 -1.5469062000-01-06 -0.202646 -0.655969  0.1934212000-01-07  0.553439  1.318152 -0.4693052000-01-08  0.675554 -1.817027 -0.183109# dotted (attribute) access provides get as wellIn [300]:store.dfOut[300]:                   A         B         C2000-01-01  0.887163  0.859588 -0.6365242000-01-02  0.015696 -2.242685  1.1500362000-01-03  0.991946  0.953324 -2.0212552000-01-04 -0.334077  0.002118  0.4054532000-01-05  0.289092  1.321158 -1.5469062000-01-06 -0.202646 -0.655969  0.1934212000-01-07  0.553439  1.318152 -0.4693052000-01-08  0.675554 -1.817027 -0.183109

Deletion of the object specified by the key

# store.remove('wp') is an equivalent methodIn [301]:delstore['wp']In [302]:storeOut[302]:<class 'pandas.io.pytables.HDFStore'>File path: store.h5/df            frame        (shape->[8,3])/s             series       (shape->[5])

Closing a Store, Context Manager

In [303]:store.close()In [304]:storeOut[304]:<class 'pandas.io.pytables.HDFStore'>File path: store.h5File is CLOSEDIn [305]:store.is_openOut[305]:False# Working with, and automatically closing the store with the context# managerIn [306]:withpd.HDFStore('store.h5')asstore:   .....:store.keys()   .....:

Read/Write API

HDFStore supports an top-level API usingread_hdf for reading andto_hdf for writing,similar to howread_csv andto_csv work. (new in 0.11.0)

In [307]:df_tl=pd.DataFrame(dict(A=list(range(5)),B=list(range(5))))In [308]:df_tl.to_hdf('store_tl.h5','table',append=True)In [309]:pd.read_hdf('store_tl.h5','table',where=['index>2'])Out[309]:   A  B3  3  34  4  4

As of version 0.17.0, HDFStore will no longer drop rows that are all missing by default. This behavior can be enabled by settingdropna=True.

In [310]:df_with_missing=pd.DataFrame({'col1':[0,np.nan,2],   .....:'col2':[1,np.nan,np.nan]})   .....:In [311]:df_with_missingOut[311]:   col1  col20   0.0   1.01   NaN   NaN2   2.0   NaNIn [312]:df_with_missing.to_hdf('file.h5','df_with_missing',   .....:format='table',mode='w')   .....:In [313]:pd.read_hdf('file.h5','df_with_missing')Out[313]:   col1  col20   0.0   1.01   NaN   NaN2   2.0   NaNIn [314]:df_with_missing.to_hdf('file.h5','df_with_missing',   .....:format='table',mode='w',dropna=True)   .....:In [315]:pd.read_hdf('file.h5','df_with_missing')Out[315]:   col1  col20   0.0   1.02   2.0   NaN

This is also true for the major axis of aPanel:

In [316]:matrix=[[[np.nan,np.nan,np.nan],[1,np.nan,np.nan]],   .....:[[np.nan,np.nan,np.nan],[np.nan,5,6]],   .....:[[np.nan,np.nan,np.nan],[np.nan,3,np.nan]]]   .....:In [317]:panel_with_major_axis_all_missing=pd.Panel(matrix,   .....:items=['Item1','Item2','Item3'],   .....:major_axis=[1,2],   .....:minor_axis=['A','B','C'])   .....:In [318]:panel_with_major_axis_all_missingOut[318]:<class 'pandas.core.panel.Panel'>Dimensions: 3 (items) x 2 (major_axis) x 3 (minor_axis)Items axis: Item1 to Item3Major_axis axis: 1 to 2Minor_axis axis: A to CIn [319]:panel_with_major_axis_all_missing.to_hdf('file.h5','panel',   .....:dropna=True,   .....:format='table',   .....:mode='w')   .....:In [320]:reloaded=pd.read_hdf('file.h5','panel')In [321]:reloadedOut[321]:<class 'pandas.core.panel.Panel'>Dimensions: 3 (items) x 1 (major_axis) x 3 (minor_axis)Items axis: Item1 to Item3Major_axis axis: 2 to 2Minor_axis axis: A to C

Fixed Format

Note

This was prior to 0.13.0 theStorer format.

The examples above show storing usingput, which write the HDF5 toPyTables in a fixed array format, calledthefixed format. These types of stores are arenot appendable once written (though you can simplyremove them and rewrite). Nor are theyqueryable; they must beretrieved in their entirety. They also do not support dataframes with non-unique column names.Thefixed format stores offer very fast writing and slightly faster reading thantable stores.This format is specified by default when usingput orto_hdf or byformat='fixed' orformat='f'

Warning

Afixed format will raise aTypeError if you try to retrieve using awhere .

pd.DataFrame(randn(10,2)).to_hdf('test_fixed.h5','df')pd.read_hdf('test_fixed.h5','df',where='index>5')TypeError:cannotpassawherespecificationwhenreadingafixedformat.thisstoremustbeselectedinitsentirety

Table Format

HDFStore supports anotherPyTables format on disk, thetableformat. Conceptually atable is shaped very much like a DataFrame,with rows and columns. Atable may be appended to in the same orother sessions. In addition, delete & query type operations aresupported. This format is specified byformat='table' orformat='t'toappend orput orto_hdf

New in version 0.13.

This format can be set as an option as wellpd.set_option('io.hdf.default_format','table') toenableput/append/to_hdf to by default store in thetable format.

In [322]:store=pd.HDFStore('store.h5')In [323]:df1=df[0:4]In [324]:df2=df[4:]# append data (creates a table automatically)In [325]:store.append('df',df1)In [326]:store.append('df',df2)In [327]:storeOut[327]:<class 'pandas.io.pytables.HDFStore'>File path: store.h5/df            frame_table  (typ->appendable,nrows->8,ncols->3,indexers->[index])# select the entire objectIn [328]:store.select('df')Out[328]:                   A         B         C2000-01-01  0.887163  0.859588 -0.6365242000-01-02  0.015696 -2.242685  1.1500362000-01-03  0.991946  0.953324 -2.0212552000-01-04 -0.334077  0.002118  0.4054532000-01-05  0.289092  1.321158 -1.5469062000-01-06 -0.202646 -0.655969  0.1934212000-01-07  0.553439  1.318152 -0.4693052000-01-08  0.675554 -1.817027 -0.183109# the type of stored dataIn [329]:store.root.df._v_attrs.pandas_typeOut[329]:'frame_table'

Note

You can also create atable by passingformat='table' orformat='t' to aput operation.

Hierarchical Keys

Keys to a store can be specified as a string. These can be in ahierarchical path-name like format (e.g.foo/bar/bah), which willgenerate a hierarchy of sub-stores (orGroups in PyTablesparlance). Keys can be specified with out the leading ‘/’ and are ALWAYSabsolute (e.g. ‘foo’ refers to ‘/foo’). Removal operations can removeeverything in the sub-store and BELOW, so becareful.

In [330]:store.put('foo/bar/bah',df)In [331]:store.append('food/orange',df)In [332]:store.append('food/apple',df)In [333]:storeOut[333]:<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])/food/apple             frame_table  (typ->appendable,nrows->8,ncols->3,indexers->[index])/food/orange            frame_table  (typ->appendable,nrows->8,ncols->3,indexers->[index])# a list of keys are returnedIn [334]:store.keys()Out[334]:['/df','/food/apple','/food/orange','/foo/bar/bah']# remove all nodes under this levelIn [335]:store.remove('food')In [336]:storeOut[336]:<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])

Warning

Hierarchical keys cannot be retrieved as dotted (attribute) access as described above for items stored under the root node.

In[8]:store.foo.bar.bahAttributeError:'HDFStore'objecthasnoattribute'foo'# you can directly access the actual PyTables node but using the root nodeIn[9]:store.root.foo.bar.bahOut[9]:/foo/bar/bah(Group)''children:=['block0_items'(Array),'block0_values'(Array),'axis0'(Array),'axis1'(Array)]

Instead, use explicit string based keys

In [337]:store['foo/bar/bah']Out[337]:                   A         B         C2000-01-01  0.887163  0.859588 -0.6365242000-01-02  0.015696 -2.242685  1.1500362000-01-03  0.991946  0.953324 -2.0212552000-01-04 -0.334077  0.002118  0.4054532000-01-05  0.289092  1.321158 -1.5469062000-01-06 -0.202646 -0.655969  0.1934212000-01-07  0.553439  1.318152 -0.4693052000-01-08  0.675554 -1.817027 -0.183109

Storing Types

Storing Mixed Types in a Table

Storing mixed-dtype data is supported. Strings are stored as afixed-width using the maximum size of the appended column. Subsequent attemptsat appending longer strings will raise aValueError.

Passingmin_itemsize={`values`:size} as a parameter to appendwill set a larger minimum for the string columns. Storingfloats,strings,ints,bools,datetime64 are currently supported. For stringcolumns, passingnan_rep='nan' to append will change the defaultnan representation on disk (which converts to/fromnp.nan), thisdefaults tonan.

In [338]:df_mixed=pd.DataFrame({'A':randn(8),   .....:'B':randn(8),   .....:'C':np.array(randn(8),dtype='float32'),   .....:'string':'string',   .....:'int':1,   .....:'bool':True,   .....:'datetime64':pd.Timestamp('20010102')},   .....:index=list(range(8)))   .....:In [339]:df_mixed.ix[3:5,['A','B','string','datetime64']]=np.nanIn [340]:store.append('df_mixed',df_mixed,min_itemsize={'values':50})In [341]:df_mixed1=store.select('df_mixed')In [342]:df_mixed1Out[342]:          A         B         C  bool datetime64  int  string0  0.704721 -1.152659 -0.430096  True 2001-01-02    1  string1 -0.785435  0.631979  0.767369  True 2001-01-02    1  string2  0.462060  0.039513  0.984920  True 2001-01-02    1  string3       NaN       NaN  0.270836  True        NaT    1     NaN4       NaN       NaN  1.391986  True        NaT    1     NaN5       NaN       NaN  0.079842  True        NaT    1     NaN6  2.007843  0.152631 -0.399965  True 2001-01-02    1  string7  0.226963  0.164530 -1.027851  True 2001-01-02    1  stringIn [343]:df_mixed1.get_dtype_counts()Out[343]:bool              1datetime64[ns]    1float32           1float64           2int64             1object            1dtype: int64# we have provided a minimum string column sizeIn [344]:store.root.df_mixed.tableOut[344]:/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 tostoring/selecting from homogeneous index DataFrames.

In [345]:index=pd.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 [346]:df_mi=pd.DataFrame(np.random.randn(10,3),index=index,   .....:columns=['A','B','C'])   .....:In [347]:df_miOut[347]:                  A         B         Cfoo barfoo one   -0.584718  0.816594 -0.081947    two   -0.344766  0.528288 -1.068989    three -0.511881  0.291205  0.566534bar one    0.503592  0.285296  0.484288    two    1.363482 -0.781105 -0.468018baz two    1.224574 -1.281108  0.875476    three -1.710715 -0.450765  0.749164qux one   -0.203933 -0.182175  0.680656    two   -1.818499  0.047072  0.394844    three -0.248432 -0.617707 -0.682884In [348]:store.append('df_mi',df_mi)In [349]:store.select('df_mi')Out[349]:                  A         B         Cfoo barfoo one   -0.584718  0.816594 -0.081947    two   -0.344766  0.528288 -1.068989    three -0.511881  0.291205  0.566534bar one    0.503592  0.285296  0.484288    two    1.363482 -0.781105 -0.468018baz two    1.224574 -1.281108  0.875476    three -1.710715 -0.450765  0.749164qux one   -0.203933 -0.182175  0.680656    two   -1.818499  0.047072  0.394844    three -0.248432 -0.617707 -0.682884# the levels are automatically included as data columnsIn [350]:store.select('df_mi','foo=bar')Out[350]:                A         B         Cfoo barbar one  0.503592  0.285296  0.484288    two  1.363482 -0.781105 -0.468018

Querying

Querying a Table

Warning

This query capabilities have changed substantially starting in0.13.0.Queries from prior version are accepted (with aDeprecationWarning) printedif its not string-like.

select anddelete operations have an optional criterion that canbe specified to select/delete only a subset of the data. This allows oneto have a very large on-disk table and retrieve only a portion of thedata.

A query is specified using theTerm class under the hood, as a boolean expression.

  • index andcolumns are supported indexers of a DataFrame
  • major_axis,minor_axis, anditems are supported indexers ofthe Panel
  • ifdata_columns are specified, these can be used as additional indexers

Valid comparison operators are:

=,==,!=,>,>=,<,<=

Valid boolean expressions are combined with:

  • | : or
  • & : and
  • ( and) : for grouping

These rules are similar to how boolean expressions are used in pandas for indexing.

Note

  • = will be automatically expanded to the comparison operator==
  • ~ is the not operator, but can only be used in very limitedcircumstances
  • If a list/tuple of expressions is passed they will be combined via&

The following are valid expressions:

  • 'index>=date'
  • "columns=['A','D']"
  • "columnsin['A','D']"
  • 'columns=A'
  • 'columns==A'
  • "~(columns=['A','B'])"
  • 'index>df.index[3]&string="bar"'
  • '(index>df.index[3]&index<=df.index[6])|string="bar"'
  • "ts>=Timestamp('2012-02-01')"
  • "major_axis>=20130101"

Theindexers are on the left-hand side of the sub-expression:

columns,major_axis,ts

The right-hand side of the sub-expression (after a comparison operator) can be:

  • functions that will be evaluated, e.g.Timestamp('2012-02-01')
  • strings, e.g."bar"
  • date-like, e.g.20130101, or"20130101"
  • lists, e.g."['A','B']"
  • variables that are defined in the local names space, e.g.date

Note

Passing a string to a query by interpolating it into the queryexpression is not recommended. Simply assign the string of interest to avariable and use that variable in an expression. For example, do this

string="HolyMoly'"store.select('df','index == string')

instead of this

string="HolyMoly'"store.select('df','index ==%s'%string)

The latter willnot work and will raise aSyntaxError.Note thatthere’s a single quote followed by a double quote in thestringvariable.

If youmust interpolate, use the'%r' format specifier

store.select('df','index ==%r'%string)

which will quotestring.

Here are some examples:

In [351]:dfq=pd.DataFrame(randn(10,4),columns=list('ABCD'),index=pd.date_range('20130101',periods=10))In [352]:store.append('dfq',dfq,format='table',data_columns=True)

Use boolean expressions, with in-line function evaluation.

In [353]:store.select('dfq',"index>pd.Timestamp('20130104') & columns=['A', 'B']")Out[353]:                   A         B2013-01-05  1.210384  0.7974352013-01-06 -0.850346  1.1768122013-01-07  0.984188 -0.1217282013-01-08  0.796595 -0.4740212013-01-09 -0.804834 -2.1236202013-01-10  0.334198  0.536784

Use and inline column reference

In [354]:store.select('dfq',where="A>0 or C>0")Out[354]:                   A         B         C         D2013-01-01  0.436258 -1.703013  0.393711 -0.4793242013-01-02 -0.299016  0.694103  0.678630  0.2395562013-01-03  0.151227  0.816127  1.893534  0.6396332013-01-04 -0.962029 -2.085266  1.930247 -1.7353492013-01-05  1.210384  0.797435 -0.379811  0.7025622013-01-07  0.984188 -0.121728  2.365769  0.4961432013-01-08  0.796595 -0.474021 -0.056696  1.3577972013-01-10  0.334198  0.536784 -0.743830 -0.320204

Works with a Panel as well.

In [355]:store.append('wp',wp)In [356]:storeOut[356]:<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])/dfq                    frame_table  (typ->appendable,nrows->10,ncols->4,indexers->[index],dc->[A,B,C,D])/foo/bar/bah            frame        (shape->[8,3])/wp                     wide_table   (typ->appendable,nrows->20,ncols->2,indexers->[major_axis,minor_axis])In [357]:store.select('wp',"major_axis>pd.Timestamp('20000102') & minor_axis=['A', 'B']")Out[357]:<class 'pandas.core.panel.Panel'>Dimensions: 2 (items) x 3 (major_axis) x 2 (minor_axis)Items axis: Item1 to Item2Major_axis axis: 2000-01-03 00:00:00 to 2000-01-05 00:00:00Minor_axis axis: A to B

Thecolumns keyword can be supplied to select a list of columns to bereturned, this is equivalent to passing a'columns=list_of_columns_to_filter':

In [358]:store.select('df',"columns=['A', 'B']")Out[358]:                   A         B2000-01-01  0.887163  0.8595882000-01-02  0.015696 -2.2426852000-01-03  0.991946  0.9533242000-01-04 -0.334077  0.0021182000-01-05  0.289092  1.3211582000-01-06 -0.202646 -0.6559692000-01-07  0.553439  1.3181522000-01-08  0.675554 -1.817027

start andstop parameters can be specified to limit the total searchspace. These are in terms of the total number of rows in a table.

# this is effectively what the storage of a Panel looks likeIn [359]:wp.to_frame()Out[359]:                     Item1     Item2major      minor2000-01-01 A      1.058969  0.215269           B     -0.397840  0.841009           C      0.337438 -1.445810           D      1.047579 -1.4019732000-01-02 A      1.045938 -0.100918           B      0.863717 -0.548242           C     -0.122092 -0.144620...                    ...       ...2000-01-04 B      0.036142  0.307969           C     -2.074978 -0.208499           D      0.247792  1.0338012000-01-05 A     -0.897157 -2.400454           B     -0.136795  2.030604           C      0.018289 -1.142631           D      0.755414  0.211883[20 rows x 2 columns]# limiting the searchIn [360]:store.select('wp',"major_axis>20000102 & minor_axis=['A','B']",   .....:start=0,stop=10)   .....:Out[360]:<class 'pandas.core.panel.Panel'>Dimensions: 2 (items) x 1 (major_axis) x 2 (minor_axis)Items axis: Item1 to Item2Major_axis axis: 2000-01-03 00:00:00 to 2000-01-03 00:00:00Minor_axis axis: A to B

Note

select will raise aValueError if the query expression has an unknownvariable reference. Usually this means that you are trying to select on a columnthat isnot a data_column.

select will raise aSyntaxError if the query expression is not valid.

Using timedelta64[ns]

New in version 0.13.

Beginning in 0.13.0, you can store and query using thetimedelta64[ns] type. Terms can bespecified in the format:<float>(<unit>), where float may be signed (and fractional), and unit can beD,s,ms,us,ns for the timedelta. Here’s an example:

In [361]:fromdatetimeimporttimedeltaIn [362]:dftd=pd.DataFrame(dict(A=pd.Timestamp('20130101'),B=[pd.Timestamp('20130101')+timedelta(days=i,seconds=10)foriinrange(10)]))In [363]:dftd['C']=dftd['A']-dftd['B']In [364]:dftdOut[364]:           A                   B                  C0 2013-01-01 2013-01-01 00:00:10  -1 days +23:59:501 2013-01-01 2013-01-02 00:00:10  -2 days +23:59:502 2013-01-01 2013-01-03 00:00:10  -3 days +23:59:503 2013-01-01 2013-01-04 00:00:10  -4 days +23:59:504 2013-01-01 2013-01-05 00:00:10  -5 days +23:59:505 2013-01-01 2013-01-06 00:00:10  -6 days +23:59:506 2013-01-01 2013-01-07 00:00:10  -7 days +23:59:507 2013-01-01 2013-01-08 00:00:10  -8 days +23:59:508 2013-01-01 2013-01-09 00:00:10  -9 days +23:59:509 2013-01-01 2013-01-10 00:00:10 -10 days +23:59:50In [365]:store.append('dftd',dftd,data_columns=True)In [366]:store.select('dftd',"C<'-3.5D'")Out[366]:           A                   B                  C4 2013-01-01 2013-01-05 00:00:10  -5 days +23:59:505 2013-01-01 2013-01-06 00:00:10  -6 days +23:59:506 2013-01-01 2013-01-07 00:00:10  -7 days +23:59:507 2013-01-01 2013-01-08 00:00:10  -8 days +23:59:508 2013-01-01 2013-01-09 00:00:10  -9 days +23:59:509 2013-01-01 2013-01-10 00:00:10 -10 days +23:59:50

Indexing

You can create/modify an index for a table withcreate_table_indexafter data is already in the table (after andappend/putoperation). Creating a table index ishighly encouraged. This willspeed your queries a great deal when you use aselect with theindexed dimension as thewhere.

Note

Indexes are automagically created (starting0.10.1) on the indexablesand any data columns you specify. This behavior can be turned off by passingindex=False toappend.

# we have automagically already created an index (in the first section)In [367]:i=store.root.df.table.cols.index.indexIn [368]:i.optlevel,i.kindOut[368]:(6,'medium')# change an index by passing new parametersIn [369]:store.create_table_index('df',optlevel=9,kind='full')In [370]:i=store.root.df.table.cols.index.indexIn [371]:i.optlevel,i.kindOut[371]:(9,'full')

Oftentimes when appending large amounts of data to a store, it is useful to turn off index creation for each append, then recreate at the end.

In [372]:df_1=pd.DataFrame(randn(10,2),columns=list('AB'))In [373]:df_2=pd.DataFrame(randn(10,2),columns=list('AB'))In [374]:st=pd.HDFStore('appends.h5',mode='w')In [375]:st.append('df',df_1,data_columns=['B'],index=False)In [376]:st.append('df',df_2,data_columns=['B'],index=False)In [377]:st.get_storer('df').tableOut[377]:/df/table (Table(20,)) ''  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)}  byteorder := 'little'  chunkshape := (2730,)

Then create the index when finished appending.

In [378]:st.create_table_index('df',columns=['B'],optlevel=9,kind='full')In [379]:st.get_storer('df').tableOut[379]:/df/table (Table(20,)) ''  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)}  byteorder := 'little'  chunkshape := (2730,)  autoindex := True  colindexes := {    "B": Index(9, full, shuffle, zlib(1)).is_csi=True}In [380]:st.close()

Seehere for how to create a completely-sorted-index (CSI) on an existing store.

Query via Data Columns

You can designate (and index) certain columns that you want to be ableto perform queries (other than theindexable columns, which you canalways query). For instance say you want to perform this commonoperation, on-disk, and return just the frame that matches thisquery. You can specifydata_columns=True to force all columns tobe data_columns

In [381]:df_dc=df.copy()In [382]:df_dc['string']='foo'In [383]:df_dc.ix[4:6,'string']=np.nanIn [384]:df_dc.ix[7:9,'string']='bar'In [385]:df_dc['string2']='cool'In [386]:df_dc.ix[1:3,['B','C']]=1.0In [387]:df_dcOut[387]:                   A         B         C string string22000-01-01  0.887163  0.859588 -0.636524    foo    cool2000-01-02  0.015696  1.000000  1.000000    foo    cool2000-01-03  0.991946  1.000000  1.000000    foo    cool2000-01-04 -0.334077  0.002118  0.405453    foo    cool2000-01-05  0.289092  1.321158 -1.546906    NaN    cool2000-01-06 -0.202646 -0.655969  0.193421    NaN    cool2000-01-07  0.553439  1.318152 -0.469305    foo    cool2000-01-08  0.675554 -1.817027 -0.183109    bar    cool# on-disk operationsIn [388]:store.append('df_dc',df_dc,data_columns=['B','C','string','string2'])In [389]:store.select('df_dc',[pd.Term('B>0')])Out[389]:                   A         B         C string string22000-01-01  0.887163  0.859588 -0.636524    foo    cool2000-01-02  0.015696  1.000000  1.000000    foo    cool2000-01-03  0.991946  1.000000  1.000000    foo    cool2000-01-04 -0.334077  0.002118  0.405453    foo    cool2000-01-05  0.289092  1.321158 -1.546906    NaN    cool2000-01-07  0.553439  1.318152 -0.469305    foo    cool# getting creativeIn [390]:store.select('df_dc','B > 0 & C > 0 & string == foo')Out[390]:                   A         B         C string string22000-01-02  0.015696  1.000000  1.000000    foo    cool2000-01-03  0.991946  1.000000  1.000000    foo    cool2000-01-04 -0.334077  0.002118  0.405453    foo    cool# this is in-memory version of this type of selectionIn [391]:df_dc[(df_dc.B>0)&(df_dc.C>0)&(df_dc.string=='foo')]Out[391]:                   A         B         C string string22000-01-02  0.015696  1.000000  1.000000    foo    cool2000-01-03  0.991946  1.000000  1.000000    foo    cool2000-01-04 -0.334077  0.002118  0.405453    foo    cool# we have automagically created this index and the B/C/string/string2# columns are stored separately as ``PyTables`` columnsIn [392]:store.root.df_dc.tableOut[392]:/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 degradation by making lots of columns intodata columns, so it is up to the user to designate these. In addition,you cannot change data columns (nor indexables) after the firstappend/put operation (Of course you can simply read in the data andcreate a new table!)

Iterator

Starting in0.11.0, you can pass,iterator=True orchunksize=number_in_a_chunktoselect andselect_as_multiple to return an iterator on the results.The default is 50,000 rows returned in a chunk.

In [393]:fordfinstore.select('df',chunksize=3):   .....:print(df)   .....:                   A         B         C2000-01-01  0.887163  0.859588 -0.6365242000-01-02  0.015696 -2.242685  1.1500362000-01-03  0.991946  0.953324 -2.021255                   A         B         C2000-01-04 -0.334077  0.002118  0.4054532000-01-05  0.289092  1.321158 -1.5469062000-01-06 -0.202646 -0.655969  0.193421                   A         B         C2000-01-07  0.553439  1.318152 -0.4693052000-01-08  0.675554 -1.817027 -0.183109

Note

New in version 0.12.0.

You can also use the iterator withread_hdf which will open, thenautomatically close the store when finished iterating.

fordfinpd.read_hdf('store.h5','df',chunksize=3):print(df)

Note, that the chunksize keyword applies to thesource rows. So if youare doing a query, then the chunksize will subdivide the total rows in the tableand the query applied, returning an iterator on potentially unequal sized chunks.

Here is a recipe for generating a query and using it to create equal sized returnchunks.

In [394]:dfeq=pd.DataFrame({'number':np.arange(1,11)})In [395]:dfeqOut[395]:   number0       11       22       33       44       55       66       77       88       99      10In [396]:store.append('dfeq',dfeq,data_columns=['number'])In [397]:defchunks(l,n):   .....:return[l[i:i+n]foriinrange(0,len(l),n)]   .....:In [398]:evens=[2,4,6,8,10]In [399]:coordinates=store.select_as_coordinates('dfeq','number=evens')In [400]:forcinchunks(coordinates,2):   .....:printstore.select('dfeq',where=c)   .....:   number1       23       4   number5       67       8   number9      10

Advanced Queries

Select a Single Column

To retrieve a single indexable or data column, use themethodselect_column. This will, for example, enable you to get the indexvery quickly. These return aSeries of the result, indexed by the row number.These do not currently accept thewhere selector.

In [401]:store.select_column('df_dc','index')Out[401]:0   2000-01-011   2000-01-022   2000-01-033   2000-01-044   2000-01-055   2000-01-066   2000-01-077   2000-01-08Name: index, dtype: datetime64[ns]In [402]:store.select_column('df_dc','string')Out[402]:0    foo1    foo2    foo3    foo4    NaN5    NaN6    foo7    barName: string, dtype: object
Selecting coordinates

Sometimes you want to get the coordinates (a.k.a the index locations) of your query. This returns anInt64Index of the resulting locations. These coordinates can also be passed to subsequentwhere operations.

In [403]:df_coord=pd.DataFrame(np.random.randn(1000,2),index=pd.date_range('20000101',periods=1000))In [404]:store.append('df_coord',df_coord)In [405]:c=store.select_as_coordinates('df_coord','index>20020101')In [406]:c.summary()Out[406]:u'Int64Index: 268 entries, 732 to 999'In [407]:store.select('df_coord',where=c)Out[407]:                   0         12002-01-02 -0.178266 -0.0646382002-01-03 -1.204956 -3.8808982002-01-04  0.974470  0.4151602002-01-05  1.751967  0.4850112002-01-06 -0.170894  0.7488702002-01-07  0.629793  0.8110532002-01-08  2.133776  0.238459...              ...       ...2002-09-20 -0.181434  0.6123992002-09-21 -0.763324 -0.3549622002-09-22 -0.261776  0.8121262002-09-23  0.482615 -0.8865122002-09-24 -0.037757 -0.5629532002-09-25  0.897706  0.3832322002-09-26 -1.324806  1.139269[268 rows x 2 columns]
Selecting using a where mask

Sometime your query can involve creating a list of rows to select. Usually thismask wouldbe a resultingindex from an indexing operation. This example selects the months ofa datetimeindex which are 5.

In [408]:df_mask=pd.DataFrame(np.random.randn(1000,2),index=pd.date_range('20000101',periods=1000))In [409]:store.append('df_mask',df_mask)In [410]:c=store.select_column('df_mask','index')In [411]:where=c[pd.DatetimeIndex(c).month==5].indexIn [412]:store.select('df_mask',where=where)Out[412]:                   0         12000-05-01 -1.006245 -0.6167592000-05-02  0.218940  0.7178382000-05-03  0.013333  1.3480602000-05-04  0.662176 -1.0506452000-05-05 -1.034870 -0.2432422000-05-06 -0.753366 -1.4543292000-05-07 -1.022920 -0.476989...              ...       ...2002-05-25 -0.509090 -0.3893762002-05-26  0.150674  1.1643372002-05-27 -0.332944  0.1151812002-05-28 -1.048127 -0.6057332002-05-29  1.418754 -0.4428352002-05-30 -0.433200  0.8350012002-05-31 -1.041278  1.401811[93 rows x 2 columns]
Storer Object

If you want to inspect the stored object, retrieve viaget_storer. You could use this programmatically to say get the numberof rows in an object.

In [413]:store.get_storer('df_dc').nrowsOut[413]:8

Multiple Table Queries

New in 0.10.1 are the methodsappend_to_multiple andselect_as_multiple, that can perform appending/selecting frommultiple tables at once. The idea is to have one table (call it theselector table) that you index most/all of the columns, and perform yourqueries. The other table(s) are data tables with an index matching theselector table’s index. You can then perform a very fast queryon the selector table, yet get lots of data back. This method is similar tohaving a very wide table, but enables more efficient queries.

Theappend_to_multiple method splits a given single DataFrameinto multiple tables according tod, a dictionary that maps thetable names to a list of ‘columns’ you want in that table. IfNoneis used in place of a list, that table will have the remainingunspecified columns of the given DataFrame. The argumentselectordefines which table is the selector table (which you can make queries from).The argumentdropna will drop rows from the input DataFrame to ensuretables are synchronized. This means that if a row for one of the tablesbeing written to is entirelynp.NaN, that row will be dropped from all tables.

Ifdropna is False,THE USER IS RESPONSIBLE FOR SYNCHRONIZING THE TABLES.Remember that entirelynp.Nan rows are not written to the HDFStore, so ifyou choose to calldropna=False, some tables may have more rows than others,and thereforeselect_as_multiple may not work or it may return unexpectedresults.

In [414]:df_mt=pd.DataFrame(randn(8,6),index=pd.date_range('1/1/2000',periods=8),   .....:columns=['A','B','C','D','E','F'])   .....:In [415]:df_mt['foo']='bar'In [416]:df_mt.ix[1,('A','B')]=np.nan# you can also create the tables individuallyIn [417]:store.append_to_multiple({'df1_mt':['A','B'],'df2_mt':None},   .....:df_mt,selector='df1_mt')   .....:In [418]:storeOut[418]:<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_coord               frame_table  (typ->appendable,nrows->1000,ncols->2,indexers->[index])/df_dc                  frame_table  (typ->appendable,nrows->8,ncols->5,indexers->[index],dc->[B,C,string,string2])/df_mask                frame_table  (typ->appendable,nrows->1000,ncols->2,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])/dfeq                   frame_table  (typ->appendable,nrows->10,ncols->1,indexers->[index],dc->[number])/dfq                    frame_table  (typ->appendable,nrows->10,ncols->4,indexers->[index],dc->[A,B,C,D])/dftd                   frame_table  (typ->appendable,nrows->10,ncols->3,indexers->[index],dc->[A,B,C])/foo/bar/bah            frame        (shape->[8,3])/wp                     wide_table   (typ->appendable,nrows->20,ncols->2,indexers->[major_axis,minor_axis])# individual tables were createdIn [419]:store.select('df1_mt')Out[419]:                   A         B2000-01-01  0.714697  0.3182152000-01-02       NaN       NaN2000-01-03 -0.086919  0.4169052000-01-04  0.489131 -0.2533402000-01-05 -0.382952 -0.3973732000-01-06  0.538116  0.2263882000-01-07 -2.073479 -0.1159262000-01-08 -0.695400  0.402493In [420]:store.select('df2_mt')Out[420]:                   C         D         E         F  foo2000-01-01  0.607460  0.790907  0.852225  0.096696  bar2000-01-02  0.811031 -0.356817  1.047085  0.664705  bar2000-01-03 -0.764381 -0.287229 -0.089351 -1.035115  bar2000-01-04 -1.948100 -0.116556  0.800597 -0.796154  bar2000-01-05 -0.717627  0.156995 -0.344718 -0.171208  bar2000-01-06  1.541729  0.205256  1.998065  0.953591  bar2000-01-07  1.391070  0.303013  1.093347 -0.101000  bar2000-01-08 -1.507639  0.089575  0.658822 -1.037627  bar# as a multipleIn [421]:store.select_as_multiple(['df1_mt','df2_mt'],where=['A>0','B>0'],   .....:selector='df1_mt')   .....:Out[421]:                   A         B         C         D         E         F  foo2000-01-01  0.714697  0.318215  0.607460  0.790907  0.852225  0.096696  bar2000-01-06  0.538116  0.226388  1.541729  0.205256  1.998065  0.953591  bar

Delete from a Table

You can delete from a table selectively by specifying awhere. Indeleting rows, it is important to understand thePyTables deletesrows by erasing the rows, thenmoving the following data. Thusdeleting can potentially be a very expensive operation depending on theorientation of your data. This is especially true in higher dimensionalobjects (Panel andPanel4D). To get optimal performance, it’sworthwhile to have the dimension you are deleting be the first of theindexables.

Data is ordered (on the disk) in terms of theindexables. Here’s asimple use case. You store panel-type data, with dates in themajor_axis and ids in theminor_axis. The data is theninterleaved 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 themajor_axis will befairly quick, as one chunk is removed, then the following data moved. Onthe other hand a delete operation on theminor_axis will be veryexpensive. In this case it would almost certainly be faster to rewritethe table using awhere that selects all but the missing data.

# returns the number of rows deletedIn [422]:store.remove('wp','major_axis>20000102')Out[422]:12In [423]:store.select('wp')Out[423]:<class 'pandas.core.panel.Panel'>Dimensions: 2 (items) x 2 (major_axis) x 4 (minor_axis)Items axis: Item1 to Item2Major_axis axis: 2000-01-01 00:00:00 to 2000-01-02 00:00:00Minor_axis axis: A to D

Warning

Please note that HDF5DOES NOT RECLAIM SPACE in the h5 filesautomatically. Thus, repeatedly deleting (or removing nodes) and addingagain,WILL TEND TO INCREASE THE FILE SIZE.

Torepack and clean the file, useptrepack

Notes & Caveats

Compression

PyTables allows the stored data to be compressed. This applies toall kinds of stores, not just tables.

  • Passcomplevel=int for a compression level (1-9, with 0 being nocompression, and the default)
  • Passcomplib=lib where lib is any ofzlib,bzip2,lzo,blosc forwhichever compression library you prefer.

HDFStore will use the file based compression scheme if no overridingcomplib orcomplevel options are provided.blosc offers veryfast compression, and is my most used. Note thatlzo andbzip2may not be installed (by Python) by default.

Compression for all objects within the file

store_compressed=pd.HDFStore('store_compressed.h5',complevel=9,complib='blosc')

Or on-the-fly compression (this only applies to tables). You can turnoff file compression for a specific table by passingcomplevel=0

store.append('df',df,complib='zlib',complevel=5)

ptrepack

PyTables offers better write performance when tables are compressed afterthey are written, as opposed to turning on compression at the verybeginning. You can use the suppliedPyTables utilityptrepack. In addition,ptrepack can change compression levelsafter the fact.

ptrepack --chunkshape=auto --propindexes --complevel=9 --complib=blosc in.h5 out.h5

Furthermoreptrepackin.h5out.h5 willrepack the file to allowyou to reuse previously deleted space. Alternatively, one can simplyremove the file and write again, or use thecopy method.

Caveats

Warning

HDFStore isnot-threadsafe for writing. The underlyingPyTables only supports concurrent reads (via threading orprocesses). If you need reading and writingat the same time, youneed to serialize these operations in a single thread in a singleprocess. You will corrupt your data otherwise. See the (GH2397) for more information.

  • If you use locks to manage write access between multiple processes, youmay want to usefsync() before releasing write locks. Forconvenience you can usestore.flush(fsync=True) to do this for you.
  • Once atable is created its items (Panel) / columns (DataFrame)are fixed; only exactly the same columns can be appended
  • Be aware that timezones (e.g.,pytz.timezone('US/Eastern'))are not necessarily equal across timezone versions. So if data islocalized to a specific timezone in the HDFStore using one versionof a timezone library and that data is updated with another version, the datawill be converted to UTC since these timezones are not consideredequal. Either use the same version of timezone library or usetz_convert withthe updated timezone definition.

Warning

PyTables will show aNaturalNameWarning if a column namecannot be used as an attribute selector.Natural identifiers contain only letters, numbers, and underscores,and may not begin with a number.Other identifiers cannot be used in awhere clauseand are generally a bad idea.

DataTypes

HDFStore will map an object dtype to thePyTables underlyingdtype. This means the following types are known to work:

TypeRepresents missing values
floating :float64,float32,float16np.nan
integer :int64,int32,int8,uint64,uint32,uint8 
boolean 
datetime64[ns]NaT
timedelta64[ns]NaT
categorical : see the section below 
object :stringsnp.nan

unicode columns are not supported, andWILL FAIL.

Categorical Data

New in version 0.15.2.

Writing data to aHDFStore that contains acategory dtype was implementedin 0.15.2. Queries work the same as if it was an object array. However, thecategory dtyped data isstored in a more efficient manner.

In [424]:dfcat=pd.DataFrame({'A':pd.Series(list('aabbcdba')).astype('category'),   .....:'B':np.random.randn(8)})   .....:In [425]:dfcatOut[425]:   A         B0  a  0.6032731  a  0.2625542  b -0.9795863  b  2.1323874  c  0.8924855  d  1.9964746  b  0.2314257  a  0.980070In [426]:dfcat.dtypesOut[426]:A    categoryB     float64dtype: objectIn [427]:cstore=pd.HDFStore('cats.h5',mode='w')In [428]:cstore.append('dfcat',dfcat,format='table',data_columns=['A'])In [429]:result=cstore.select('dfcat',where="A in ['b','c']")In [430]:resultOut[430]:   A         B2  b -0.9795863  b  2.1323874  c  0.8924856  b  0.231425In [431]:result.dtypesOut[431]:A    categoryB     float64dtype: object

Warning

The format of theCategorical is readable by prior versions of pandas (< 0.15.2), but will retrievethe data as an integer based column (e.g. thecodes). However, thecategoriescan be retrievedbut require the user to select them manually using the explicit meta path.

The data is stored like so:

In [432]:cstoreOut[432]:<class 'pandas.io.pytables.HDFStore'>File path: cats.h5/dfcat                        frame_table  (typ->appendable,nrows->8,ncols->2,indexers->[index],dc->[A])/dfcat/meta/A/meta            series_table (typ->appendable,nrows->4,ncols->1,indexers->[index],dc->[values])# to get the categoriesIn [433]:cstore.select('dfcat/meta/A/meta')Out[433]:0    a1    b2    c3    ddtype: object

String Columns

min_itemsize

The underlying implementation ofHDFStore uses a fixed column width (itemsize) for string columns.A string column itemsize is calculated as the maximum of thelength of data (for that column) that is passed to theHDFStore,in the first append. Subsequent appends,may introduce a string for a columnlarger than the column can hold, an Exception will be raised (otherwise youcould have a silent truncation of these columns, leading to loss of information). In the future we may relax this andallow a user-specified truncation to occur.

Passmin_itemsize on the first table creation to a-priori specify 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 passvalues as a key toallow allindexables ordata_columns to have this min_itemsize.

Starting in 0.11.0, passing amin_itemsize dict will cause all passed columns to be created asdata_columns automatically.

Note

If you are not passing anydata_columns, then themin_itemsize will be the maximum of the length of any string passed

In [434]:dfs=pd.DataFrame(dict(A='foo',B='bar'),index=list(range(5)))In [435]:dfsOut[435]:     A    B0  foo  bar1  foo  bar2  foo  bar3  foo  bar4  foo  bar# A and B have a size of 30In [436]:store.append('dfs',dfs,min_itemsize=30)In [437]:store.get_storer('dfs').tableOut[437]:/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 calculatedIn [438]:store.append('dfs2',dfs,min_itemsize={'A':30})In [439]:store.get_storer('dfs2').tableOut[439]:/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}

nan_rep

String columns will serialize anp.nan (a missing value) with thenan_rep string representation. This defaults to the string valuenan.You could inadvertently turn an actualnan value into a missing value.

In [440]:dfss=pd.DataFrame(dict(A=['foo','bar','nan']))In [441]:dfssOut[441]:     A0  foo1  bar2  nanIn [442]:store.append('dfss',dfss)In [443]:store.select('dfss')Out[443]:     A0  foo1  bar2  NaN# here you need to specify a different nan repIn [444]:store.append('dfss2',dfss,nan_rep='_nan_')In [445]:store.select('dfss2')Out[445]:     A0  foo1  bar2  nan

External Compatibility

HDFStore writestable format objects in specific formats suitable forproducing loss-less round trips to pandas objects. For externalcompatibility,HDFStore can read nativePyTables formattables.

It is possible to write anHDFStore object that can easily be imported intoR using therhdf5 library (Package website). Create a table format store like this:

In [446]:np.random.seed(1)In [447]:df_for_r=pd.DataFrame({"first":np.random.rand(100),   .....:"second":np.random.rand(100),   .....:"class":np.random.randint(0,2,(100,))},   .....:index=range(100))   .....:In [448]:df_for_r.head()Out[448]:   class     first    second0      0  0.417022  0.3266451      0  0.720324  0.5270582      1  0.000114  0.8859423      1  0.302333  0.3572704      1  0.146756  0.908535In [449]:store_export=pd.HDFStore('export.h5')In [450]:store_export.append('df_for_r',df_for_r,data_columns=df_dc.columns)In [451]:store_exportOut[451]:<class 'pandas.io.pytables.HDFStore'>File path: export.h5/df_for_r            frame_table  (typ->appendable,nrows->100,ncols->3,indexers->[index])

In R this file can be read into adata.frame object using therhdf5library. The following example function reads the corresponding column namesand data values from the values and assembles them into adata.frame:

# Load values and column names for all datasets from corresponding nodes and# insert them into one data.frame object.library(rhdf5)loadhdf5data<-function(h5File){listing<- h5ls(h5File)# Find all data nodes, values are stored in *_values and corresponding column# titles in *_itemsdata_nodes<-grep("_values", listing$name)name_nodes<-grep("_items", listing$name)data_paths=paste(listing$group[data_nodes], listing$name[data_nodes], sep="/")name_paths=paste(listing$group[name_nodes], listing$name[name_nodes], sep="/")columns=list()for(idxinseq(data_paths)){# NOTE: matrices returned by h5read have to be transposed to to obtain# required Fortran order!  data<-data.frame(t(h5read(h5File, data_paths[idx])))  names<-t(h5read(h5File, name_paths[idx]))  entry<-data.frame(data)colnames(entry)<-names  columns<-append(columns, entry)}data<-data.frame(columns)return(data)}

Now you can import theDataFrame into R:

> data= loadhdf5data("transfer.hdf5")>head(data)         first    secondclass10.41702200470.3266449020.72032449340.5270581030.00011437480.8859421140.30233257260.3572698150.14675589080.9085352160.09233859480.62336011

Note

The R function lists the entire HDF5 file’s contents and assembles thedata.frame object from all matching nodes, so use this only as astarting point if you have stored multipleDataFrame objects to asingle HDF5 file.

Backwards Compatibility

0.10.1 ofHDFStore can read tables created in a prior version of pandas,however query terms using theprior (undocumented) methodology are unsupported.HDFStore willissue a warning if you try to use a legacy-format file. You mustread in the entire file and write it out using the new format, using themethodcopy to take advantage of the updates. The group attributepandas_version contains the version information.copy takes anumber of options, please see the docstring.

# a legacy storeIn [452]:legacy_store=pd.HDFStore(legacy_file_path,'r')In [453]:legacy_storeOut[453]:<class 'pandas.io.pytables.HDFStore'>File path: /home/joris/scipy/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])/foo/bar              wide         (shape->[3,30,4])/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])# copy (and return the new handle)In [454]:new_store=legacy_store.copy('store_new.h5')In [455]:new_storeOut[455]:<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])/foo/bar              wide         (shape->[3,30,4])/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])In [456]:new_store.close()

Performance

  • tables format come with a writing performance penalty as compared tofixed stores. The benefit is the ability to append/delete andquery (potentially very large amounts of data). Write times aregenerally longer as compared with regular stores. Query times canbe quite fast, especially on an indexed axis.
  • You can passchunksize=<int> toappend, specifying thewrite chunksize (default is 50000). This will significantly loweryour memory usage on writing.
  • You can passexpectedrows=<int> to the firstappend,to set the TOTAL number of expected rows thatPyTables willexpected. This will optimize read/write performance.
  • Duplicate rows can be written to tables, but are filtered out inselection (with the last items being selected; thus a table isunique on major, minor pairs)
  • APerformanceWarning will be raised if you are attempting tostore types that will be pickled by PyTables (rather than stored asendemic types). SeeHerefor more information and some solutions.

Experimental

HDFStore supportsPanel4D storage.

In [457]:p4d=pd.Panel4D({'l1':wp})In [458]:p4dOut[458]:<class 'pandas.core.panelnd.Panel4D'>Dimensions: 1 (labels) x 2 (items) x 5 (major_axis) x 4 (minor_axis)Labels axis: l1 to l1Items axis: Item1 to Item2Major_axis axis: 2000-01-01 00:00:00 to 2000-01-05 00:00:00Minor_axis axis: A to DIn [459]:store.append('p4d',p4d)In [460]:storeOut[460]:<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_coord               frame_table  (typ->appendable,nrows->1000,ncols->2,indexers->[index])/df_dc                  frame_table  (typ->appendable,nrows->8,ncols->5,indexers->[index],dc->[B,C,string,string2])/df_mask                frame_table  (typ->appendable,nrows->1000,ncols->2,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])/dfeq                   frame_table  (typ->appendable,nrows->10,ncols->1,indexers->[index],dc->[number])/dfq                    frame_table  (typ->appendable,nrows->10,ncols->4,indexers->[index],dc->[A,B,C,D])/dfs                    frame_table  (typ->appendable,nrows->5,ncols->2,indexers->[index])/dfs2                   frame_table  (typ->appendable,nrows->5,ncols->2,indexers->[index],dc->[A])/dfss                   frame_table  (typ->appendable,nrows->3,ncols->1,indexers->[index])/dfss2                  frame_table  (typ->appendable,nrows->3,ncols->1,indexers->[index])/dftd                   frame_table  (typ->appendable,nrows->10,ncols->3,indexers->[index],dc->[A,B,C])/foo/bar/bah            frame        (shape->[8,3])/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])

These, by default, index the three axesitems,major_axis,minor_axis. On anAppendableTable it is possible to setup with thefirst append a different indexing scheme, depending on how you want tostore your data. Pass theaxes keyword with a list of dimensions(currently must by exactly 1 less than the total dimensions of theobject). This cannot be changed after table creation.

In [461]:store.append('p4d2',p4d,axes=['labels','major_axis','minor_axis'])In [462]:storeOut[462]:<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_coord               frame_table  (typ->appendable,nrows->1000,ncols->2,indexers->[index])/df_dc                  frame_table  (typ->appendable,nrows->8,ncols->5,indexers->[index],dc->[B,C,string,string2])/df_mask                frame_table  (typ->appendable,nrows->1000,ncols->2,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])/dfeq                   frame_table  (typ->appendable,nrows->10,ncols->1,indexers->[index],dc->[number])/dfq                    frame_table  (typ->appendable,nrows->10,ncols->4,indexers->[index],dc->[A,B,C,D])/dfs                    frame_table  (typ->appendable,nrows->5,ncols->2,indexers->[index])/dfs2                   frame_table  (typ->appendable,nrows->5,ncols->2,indexers->[index],dc->[A])/dfss                   frame_table  (typ->appendable,nrows->3,ncols->1,indexers->[index])/dfss2                  frame_table  (typ->appendable,nrows->3,ncols->1,indexers->[index])/dftd                   frame_table  (typ->appendable,nrows->10,ncols->3,indexers->[index],dc->[A,B,C])/foo/bar/bah            frame        (shape->[8,3])/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])In [463]:store.select('p4d2',[pd.Term('labels=l1'),pd.Term('items=Item1'),pd.Term('minor_axis=A_big_strings')])Out[463]:<class 'pandas.core.panelnd.Panel4D'>Dimensions: 0 (labels) x 1 (items) x 0 (major_axis) x 0 (minor_axis)Labels axis: NoneItems axis: Item1 to Item1Major_axis axis: NoneMinor_axis axis: None

SQL Queries

Thepandas.io.sql module provides a collection of query wrappers to bothfacilitate data retrieval and to reduce dependency on DB-specific API. Database abstractionis provided by SQLAlchemy if installed. In addition you will need a driver library foryour database. Examples of such drivers arepsycopg2for PostgreSQL orpymysql for MySQL.ForSQLite this isincluded in Python’s standard library by default.You can find an overview of supported drivers for each SQL dialect in theSQLAlchemy docs.

New in version 0.14.0.

If SQLAlchemy is not installed, a fallback is only provided for sqlite (andfor mysql for backwards compatibility, but this is deprecated and will beremoved in a future version).This mode requires a Python database adapter which respect thePythonDB-API.

See also somecookbook examples for some advanced strategies.

The key functions are:

read_sql_table(table_name, con[, schema, ...])Read SQL database table into a DataFrame.
read_sql_query(sql, con[, index_col, ...])Read SQL query into a DataFrame.
read_sql(sql, con[, index_col, ...])Read SQL query or database table into a DataFrame.
DataFrame.to_sql(name, con[, flavor, ...])Write records stored in a DataFrame to a SQL database.

Note

The functionread_sql() is a convenience wrapper aroundread_sql_table() andread_sql_query() (and forbackward compatibility) and will delegate to specific function depending onthe provided input (database table name or sql query).Table names do not need to be quoted if they have special characters.

In the following example, we use theSQlite SQL databaseengine. You can use a temporary SQLite database where data are stored in“memory”.

To connect with SQLAlchemy you use thecreate_engine() function to create an engineobject from database URI. You only need to create the engine once per database you areconnecting to.For more information oncreate_engine() and the URI formatting, see the examplesbelow and the SQLAlchemydocumentation

In [464]:fromsqlalchemyimportcreate_engine# Create your engine.In [465]:engine=create_engine('sqlite:///:memory:')

If you want to manage your own connections you can pass one of those instead:

withengine.connect()asconn,conn.begin():data=pd.read_sql_table('data',conn)

Writing DataFrames

Assuming the following data is in a DataFramedata, we can insert it intothe database usingto_sql().

idDateCol_1Col_2Col_3
262012-10-18X25.7True
422012-10-19Y-12.4False
632012-10-20Z5.73True
In [466]:data.to_sql('data',engine)

With some databases, writing large DataFrames can result in errors due topacket size limitations being exceeded. This can be avoided by setting thechunksize parameter when callingto_sql. For example, the followingwritesdata to the database in batches of 1000 rows at a time:

In [467]:data.to_sql('data_chunked',engine,chunksize=1000)

SQL data types

to_sql() will try to map your data to an appropriateSQL data type based on the dtype of the data. When you have columns of dtypeobject, pandas will try to infer the data type.

You can always override the default type by specifying the desired SQL type ofany of the columns by using thedtype argument. This argument needs adictionary mapping column names to SQLAlchemy types (or strings for the sqlite3fallback mode).For example, specifying to use the sqlalchemyString type instead of thedefaultText type for string columns:

In [468]:fromsqlalchemy.typesimportStringIn [469]:data.to_sql('data_dtype',engine,dtype={'Col_1':String})

Note

Due to the limited support for timedelta’s in the different databaseflavors, columns with typetimedelta64 will be written as integervalues as nanoseconds to the database and a warning will be raised.

Note

Columns ofcategory dtype will be converted to the dense representationas you would get withnp.asarray(categorical) (e.g. for string categoriesthis gives an array of strings).Because of this, reading the database table back in doesnot generatea categorical.

Reading Tables

read_sql_table() will read a database table given thetable name and optionally a subset of columns to read.

Note

In order to useread_sql_table(), youmust have theSQLAlchemy optional dependency installed.

In [470]:pd.read_sql_table('data',engine)Out[470]:   index  id       Date Col_1  Col_2  Col_30      0  26 2010-10-18     X  27.50   True1      1  42 2010-10-19     Y -12.50  False2      2  63 2010-10-20     Z   5.73   True

You can also specify the name of the column as the DataFrame index,and specify a subset of columns to be read.

In [471]:pd.read_sql_table('data',engine,index_col='id')Out[471]:    index       Date Col_1  Col_2  Col_3id26      0 2010-10-18     X  27.50   True42      1 2010-10-19     Y -12.50  False63      2 2010-10-20     Z   5.73   TrueIn [472]:pd.read_sql_table('data',engine,columns=['Col_1','Col_2'])Out[472]:  Col_1  Col_20     X  27.501     Y -12.502     Z   5.73

And you can explicitly force columns to be parsed as dates:

In [473]:pd.read_sql_table('data',engine,parse_dates=['Date'])Out[473]:   index  id       Date Col_1  Col_2  Col_30      0  26 2010-10-18     X  27.50   True1      1  42 2010-10-19     Y -12.50  False2      2  63 2010-10-20     Z   5.73   True

If needed you can explicitly specify a format string, or a dict of argumentsto pass topandas.to_datetime():

pd.read_sql_table('data',engine,parse_dates={'Date':'%Y-%m-%d'})pd.read_sql_table('data',engine,parse_dates={'Date':{'format':'%Y-%m-%d %H:%M:%S'}})

You can check if a table exists usinghas_table()

Schema support

New in version 0.15.0.

Reading from and writing to different schema’s is supported through theschemakeyword in theread_sql_table() andto_sql()functions. Note however that this depends on the database flavor (sqlite does nothave schema’s). For example:

df.to_sql('table',engine,schema='other_schema')pd.read_sql_table('table',engine,schema='other_schema')

Querying

You can query using raw SQL in theread_sql_query() function.In this case you must use the SQL variant appropriate for your database.When using SQLAlchemy, you can also pass SQLAlchemy Expression language constructs,which are database-agnostic.

In [474]:pd.read_sql_query('SELECT * FROM data',engine)Out[474]:   index  id                        Date Col_1  Col_2  Col_30      0  26  2010-10-18 00:00:00.000000     X  27.50      11      1  42  2010-10-19 00:00:00.000000     Y -12.50      02      2  63  2010-10-20 00:00:00.000000     Z   5.73      1

Of course, you can specify a more “complex” query.

In [475]:pd.read_sql_query("SELECT id, Col_1, Col_2 FROM data WHERE id = 42;",engine)Out[475]:   id Col_1  Col_20  42     Y  -12.5

Theread_sql_query() function supports achunksize argument.Specifying this will return an iterator through chunks of the query result:

In [476]:df=pd.DataFrame(np.random.randn(20,3),columns=list('abc'))In [477]:df.to_sql('data_chunks',engine,index=False)
In [478]:forchunkinpd.read_sql_query("SELECT * FROM data_chunks",engine,chunksize=5):   .....:print(chunk)   .....:          a         b         c0  0.280665 -0.073113  1.1603391  0.369493  1.904659  1.1110572  0.659050 -1.627438  0.6023193  0.420282  0.810952  1.0444424 -0.400878  0.824006 -0.562305          a         b         c0  1.954878 -1.331952 -1.7606891 -1.650721 -0.890556 -1.1191152  1.956079 -0.326499 -1.3426763  1.114383 -0.586524 -1.2368534  0.875839  0.623362 -0.434957          a         b         c0  1.407540  0.129102  1.6169501  0.502741  1.558806  0.1094032 -1.219744  2.449369 -0.5457743 -0.198838 -0.700399 -0.2033944  0.242669  0.201830  0.661020          a         b         c0  1.792158 -0.120465 -1.2331211 -1.182318 -0.665755 -1.6741962  0.825030 -0.498214 -0.3109853 -0.001891 -1.396620 -0.8613164  0.674712  0.618539 -0.443172

You can also run a plain query without creating a dataframe withexecute(). This is useful for queries that don’t return values,such as INSERT. This is functionally equivalent to callingexecute on theSQLAlchemy engine or db connection object. Again, you must use the SQL syntaxvariant appropriate for your database.

frompandas.ioimportsqlsql.execute('SELECT * FROM table_name',engine)sql.execute('INSERT INTO table_name VALUES(?, ?, ?)',engine,params=[('id',1,12.2,True)])

Engine connection examples

To connect with SQLAlchemy you use thecreate_engine() function to create an engineobject from database URI. You only need to create the engine once per database you areconnecting to.

fromsqlalchemyimportcreate_engineengine=create_engine('postgresql://scott:tiger@localhost:5432/mydatabase')engine=create_engine('mysql+mysqldb://scott:tiger@localhost/foo')engine=create_engine('oracle://scott:[email protected]:1521/sidname')engine=create_engine('mssql+pyodbc://mydsn')# sqlite://<nohostname>/<path># where <path> is relative:engine=create_engine('sqlite:///foo.db')# or absolute, starting with a slash:engine=create_engine('sqlite:////absolute/path/to/foo.db')

For more information see the examples the SQLAlchemydocumentation

Advanced SQLAlchemy queries

You can use SQLAlchemy constructs to describe your query.

Usesqlalchemy.text() to specify query parameters in a backend-neutral way

In [479]:importsqlalchemyassaIn [480]:pd.read_sql(sa.text('SELECT * FROM data where Col_1=:col1'),engine,params={'col1':'X'})Out[480]:   index  id                        Date Col_1  Col_2  Col_30      0  26  2010-10-18 00:00:00.000000     X   27.5      1

If you have an SQLAlchemy description of your database you can express where conditions using SQLAlchemy expressions

In [481]:metadata=sa.MetaData()In [482]:data_table=sa.Table('data',metadata,   .....:sa.Column('index',sa.Integer),   .....:sa.Column('Date',sa.DateTime),   .....:sa.Column('Col_1',sa.String),   .....:sa.Column('Col_2',sa.Float),   .....:sa.Column('Col_3',sa.Boolean),   .....:)   .....:In [483]:pd.read_sql(sa.select([data_table]).where(data_table.c.Col_3==True),engine)Out[483]:   index       Date Col_1  Col_2 Col_30      0 2010-10-18     X  27.50  True1      2 2010-10-20     Z   5.73  True

You can combine SQLAlchemy expressions with parameters passed toread_sql() usingsqlalchemy.bindparam()

In [484]:importdatetimeasdtIn [485]:expr=sa.select([data_table]).where(data_table.c.Date>sa.bindparam('date'))In [486]:pd.read_sql(expr,engine,params={'date':dt.datetime(2010,10,18)})Out[486]:   index       Date Col_1  Col_2  Col_30      1 2010-10-19     Y -12.50  False1      2 2010-10-20     Z   5.73   True

Sqlite fallback

The use of sqlite is supported without using SQLAlchemy.This mode requires a Python database adapter which respect thePythonDB-API.

You can create connections like so:

importsqlite3con=sqlite3.connect(':memory:')

And then issue the following queries:

data.to_sql('data',cnx)pd.read_sql_query("SELECT * FROM data",con)

Google BigQuery (Experimental)

New in version 0.13.0.

Thepandas.io.gbq module provides a wrapper for Google’s BigQueryanalytics web service to simplify retrieving results from BigQuery tablesusing SQL-like queries. Result sets are parsed into a pandasDataFrame with a shape and data types derived from the source table.Additionally, DataFrames can be inserted into new BigQuery tables or appendedto existing tables.

You will need to install some additional dependencies:

Warning

To use this module, you will need a valid BigQuery account. Refer to theBigQuery Documentation for details on the service itself.

The key functions are:

read_gbq(query[, project_id, index_col, ...])Load data from Google BigQuery.
to_gbq(dataframe, destination_table, project_id)Write a DataFrame to a Google BigQuery table.

Authentication

New in version 0.18.0.

Authentication to the GoogleBigQuery service is viaOAuth2.0.Is possible to authenticate with either user account credentials or service account credentials.

Authenticating with user account credentials is as simple as following the prompts in a browser windowwhich will be automatically opened for you. You will be authenticated to the specifiedBigQuery account using the product namepandasGBQ. It is only possible on local host.The remote authentication using user account credentials is not currently supported in Pandas.Additional information on the authentication mechanism can be foundhere.

Authentication with service account credentials is possible via the‘private_key’ parameter. This methodis particularly useful when working on remote servers (eg. jupyter iPython notebook on remote host).Additional information on service accounts can be foundhere.

You will need to install an additional dependency:oauth2client.

Authentication viaapplicationdefaultcredentials is also possible. This is only validif the parameterprivate_key is not provided. This method also requires thatthe credentials can be fetched from the environment the code is running in.Otherwise, the OAuth2 client-side authentication is used.Additional information onapplication default credentials.

New in version 0.19.0.

Note

The‘private_key’ parameter can be set to either the file path of the service account keyin JSON format, or key contents of the service account key in JSON format.

Note

A private key can be obtained from the Google developers console by clickinghere. Use JSON key type.

Querying

Suppose you want to load all data from an existing BigQuery table :test_dataset.test_tableinto a DataFrame using theread_gbq() function.

# Insert your BigQuery Project ID Here# Can be found in the Google web consoleprojectid="xxxxxxxx"data_frame=pd.read_gbq('SELECT * FROM test_dataset.test_table',projectid)

You can define which column from BigQuery to use as an index in thedestination DataFrame as well as a preferred column order as follows:

data_frame=pd.read_gbq('SELECT * FROM test_dataset.test_table',index_col='index_column_name',col_order=['col1','col2','col3'],projectid)

Note

You can find your project id in theGoogle developers console.

Note

You can toggle the verbose output via theverbose flag which defaults toTrue.

Note

Thedialect argument can be used to indicate whether to use BigQuery’s'legacy' SQLor BigQuery’s'standard' SQL (beta). The default value is'legacy'. For more informationon BigQuery’s standard SQL, seeBigQuery SQL Reference

Writing DataFrames

Assume we want to write a DataFramedf into a BigQuery table usingto_gbq().

In [487]:df=pd.DataFrame({'my_string':list('abc'),   .....:'my_int64':list(range(1,4)),   .....:'my_float64':np.arange(4.0,7.0),   .....:'my_bool1':[True,False,True],   .....:'my_bool2':[False,True,False],   .....:'my_dates':pd.date_range('now',periods=3)})   .....:In [488]:dfOut[488]:  my_bool1 my_bool2                   my_dates  my_float64  my_int64 my_string0     True    False 2016-11-03 16:49:02.443745         4.0         1         a1    False     True 2016-11-04 16:49:02.443745         5.0         2         b2     True    False 2016-11-05 16:49:02.443745         6.0         3         cIn [489]:df.dtypesOut[489]:my_bool1                boolmy_bool2                boolmy_dates      datetime64[ns]my_float64           float64my_int64               int64my_string             objectdtype: object
df.to_gbq('my_dataset.my_table',projectid)

Note

The destination table and destination dataset will automatically be created if they do not already exist.

Theif_exists argument can be used to dictate whether to'fail','replace'or'append' if the destination table already exists. The default value is'fail'.

For example, assume thatif_exists is set to'fail'. The following snippet will raiseaTableCreationError if the destination table already exists.

df.to_gbq('my_dataset.my_table',projectid,if_exists='fail')

Note

If theif_exists argument is set to'append', the destination dataframe willbe written to the table using the defined table schema and column types. Thedataframe must match the destination table in structure and data types.If theif_exists argument is set to'replace', and the existing table has adifferent schema, a delay of 2 minutes will be forced to ensure that the new schemahas propagated in the Google environment. SeeGoogle BigQuery issue 191.

Writing large DataFrames can result in errors due to size limitations being exceeded.This can be avoided by setting thechunksize argument when callingto_gbq().For example, the following writesdf to a BigQuery table in batches of 10000 rows at a time:

df.to_gbq('my_dataset.my_table',projectid,chunksize=10000)

You can also see the progress of your post via theverbose flag which defaults toTrue.For example:

In[8]:df.to_gbq('my_dataset.my_table',projectid,chunksize=10000,verbose=True)StreamingInsertis10%CompleteStreamingInsertis20%CompleteStreamingInsertis30%CompleteStreamingInsertis40%CompleteStreamingInsertis50%CompleteStreamingInsertis60%CompleteStreamingInsertis70%CompleteStreamingInsertis80%CompleteStreamingInsertis90%CompleteStreamingInsertis100%Complete

Note

If an error occurs while streaming data to BigQuery, seeTroubleshooting BigQuery Errors.

Note

The BigQuery SQL query language has some oddities, see theBigQuery Query Reference Documentation.

Note

While BigQuery uses SQL-like syntax, it has some important differences from traditionaldatabases both in functionality, API limitations (size and quantity of queries or uploads),and how Google charges for use of the service. You should refer toGoogle BigQuery documentationoften as the service seems to be changing and evolving. BiqQuery is best for analyzing largesets of data quickly, but it is not a direct replacement for a transactional database.

Creating BigQuery Tables

Warning

As of 0.17, the functiongenerate_bq_schema() has been deprecated and will beremoved in a future version.

As of 0.15.2, the gbq module has a functiongenerate_bq_schema() which willproduce the dictionary representation schema of the specified pandas DataFrame.

In [10]:gbq.generate_bq_schema(df,default_type='STRING')Out[10]:{'fields':[{'name':'my_bool1','type':'BOOLEAN'},         {'name': 'my_bool2', 'type': 'BOOLEAN'},         {'name': 'my_dates', 'type': 'TIMESTAMP'},         {'name': 'my_float64', 'type': 'FLOAT'},         {'name': 'my_int64', 'type': 'INTEGER'},         {'name': 'my_string', 'type': 'STRING'}]}

Note

If you delete and re-create a BigQuery table with the same name, but different table schema,you must wait 2 minutes before streaming data into the table. As a workaround, consider creatingthe new table with a different name. Refer toGoogle BigQuery issue 191.

Stata Format

New in version 0.12.0.

Writing to Stata format

The methodto_stata() will write a DataFrameinto a .dta file. The format version of this file is always 115 (Stata 12).

In [490]:df=pd.DataFrame(randn(10,2),columns=list('AB'))In [491]:df.to_stata('stata.dta')

Stata data files have limited data type support; only strings with244 or fewer characters,int8,int16,int32,float32andfloat64 can be stored in.dta files. Additionally,Stata reserves certain values to represent missing data. Exporting anon-missing value that is outside of the permitted range in Stata fora particular data type will retype the variable to the next largersize. For example,int8 values are restricted to lie between -127and 100 in Stata, and so variables with values above 100 will triggera conversion toint16.nan values in floating points datatypes are stored as the basic missing data type (. inStata).

Note

It is not possible to export missing data values for integer data types.

TheStata writer gracefully handles other data types includingint64,bool,uint8,uint16,uint32 by casting tothe smallest supported type that can represent the data. For example, datawith a type ofuint8 will be cast toint8 if all values are less than100 (the upper bound for non-missingint8 data inStata), or, if values areoutside of this range, the variable is cast toint16.

Warning

Conversion fromint64 tofloat64 may result in a loss of precisionifint64 values are larger than 2**53.

Warning

StataWriter andto_stata() only support fixed widthstrings containing up to 244 characters, a limitation imposed by the version115 dta file format. Attempting to writeStata dta files with stringslonger than 244 characters raises aValueError.

Reading from Stata format

The top-level functionread_stata will read a dta file and returneither a DataFrame or aStataReader that canbe used to read the file incrementally.

In [492]:pd.read_stata('stata.dta')Out[492]:   index         A         B0      0  1.810535 -1.3057271      1 -0.344987 -0.2308402      2 -2.793085  1.9375293      3  0.366332 -1.0445894      4  2.051173  0.5856625      5  0.429526 -0.6069986      6  0.106223 -1.5256807      7  0.795026 -0.3744388      8  0.134048  1.2020559      9  0.284748  0.262467

New in version 0.16.0.

Specifying achunksize yields aStataReader instance that can be used toreadchunksize lines from the file at a time. TheStataReaderobject can be used as an iterator.

In [493]:reader=pd.read_stata('stata.dta',chunksize=3)In [494]:fordfinreader:   .....:print(df.shape)   .....:(3, 3)(3, 3)(3, 3)(1, 3)

For more fine-grained control, useiterator=True and specifychunksize with each call toread().

In [495]:reader=pd.read_stata('stata.dta',iterator=True)In [496]:chunk1=reader.read(5)In [497]:chunk2=reader.read(5)

Currently theindex is retrieved as a column.

The parameterconvert_categoricals indicates whether value labels should beread and used to create aCategorical variable from them. Value labels canalso be retrieved by the functionvalue_labels, which requiresread()to be called before use.

The parameterconvert_missing indicates whether missing valuerepresentations in Stata should be preserved. IfFalse (the default),missing values are represented asnp.nan. IfTrue, missing values arerepresented usingStataMissingValue objects, and columns containing missingvalues will haveobject data type.

Note

read_stata() andStataReader support .dta formats 113-115(Stata 10-12), 117 (Stata 13), and 118 (Stata 14).

Note

Settingpreserve_dtypes=False will upcast to the standard pandas data types:int64 for all integer types andfloat64 for floating point data. By default,the Stata data types are preserved when importing.

Categorical Data

New in version 0.15.2.

Categorical data can be exported toStata data files as value labeled data.The exported data consists of the underlying category codes as integer data valuesand the categories as value labels.Stata does not have an explicit equivalentto aCategorical and information aboutwhether the variable is orderedis lost when exporting.

Warning

Stata only supports string value labels, and sostr is called on thecategories when exporting data. ExportingCategorical variables withnon-string categories produces a warning, and can result a loss ofinformation if thestr representations of the categories are not unique.

Labeled data can similarly be imported fromStata data files asCategoricalvariables using the keyword argumentconvert_categoricals (True by default).The keyword argumentorder_categoricals (True by default) determineswhether importedCategorical variables are ordered.

Note

When importing categorical data, the values of the variables in theStatadata file are not preserved sinceCategorical variables alwaysuse integer data types between-1 andn-1 wheren is the numberof categories. If the original values in theStata data file are required,these can be imported by settingconvert_categoricals=False, which willimport original data (but not the variable labels). The original values canbe matched to the imported categorical data since there is a simple mappingbetween the originalStata data values and the category codes of importedCategorical variables: missing values are assigned code-1, and thesmallest original value is assigned0, the second smallest is assigned1 and so on until the largest original value is assigned the coden-1.

Note

Stata supports partially labeled series. These series have value labels forsome but not all data values. Importing a partially labeled series will produceaCategorical with string categories for the values that are labeled andnumeric categories for values with no label.

SAS Formats

New in version 0.17.0.

The top-level functionread_sas() can read (but not write) SASxport (.XPT) andSAS7BDAT (.sas7bdat) format files were added inv0.18.0.

SAS files only contain two value types: ASCII text and floating pointvalues (usually 8 bytes but sometimes truncated). For xport files,there is no automatic type conversion to integers, dates, orcategoricals. For SAS7BDAT files, the format codes may allow datevariables to be automatically converted to dates. By default thewhole file is read and returned as aDataFrame.

Specify achunksize or useiterator=True to obtain readerobjects (XportReader orSAS7BDATReader) for incrementallyreading the file. The reader objects also have attributes thatcontain additional information about the file and its variables.

Read a SAS7BDAT file:

df=pd.read_sas('sas_data.sas7bdat')

Obtain an iterator and read an XPORT file 100,000 lines at a time:

rdr=pd.read_sas('sas_xport.xpt',chunk=100000)forchunkinrdr:do_something(chunk)

Thespecification for the xport file format is available from the SASweb site.

No official documentation is available for the SAS7BDAT format.

Other file formats

pandas itself only supports IO with a limited set of file formats that mapcleanly to its tabular data model. For reading and writing other file formatsinto and from pandas, we recommend these packages from the broader community.

netCDF

xarray provides data structures inspired by the pandas DataFrame for workingwith multi-dimensional datasets, with a focus on the netCDF file format andeasy conversion to and from pandas.

Performance Considerations

This is an informal comparison of various IO methods, using pandas 0.13.1.

In [1]:df=pd.DataFrame(randn(1000000,2),columns=list('AB'))In [2]:df.info()<class 'pandas.core.frame.DataFrame'>Int64Index: 1000000 entries, 0 to 999999Data columns (total 2 columns):A    1000000 non-null float64B    1000000 non-null float64dtypes: float64(2)memory usage: 22.9 MB

Writing

In [14]:%timeittest_sql_write(df)1 loops, best of 3: 6.24 s per loopIn [15]:%timeittest_hdf_fixed_write(df)1 loops, best of 3: 237 ms per loopIn [26]:%timeittest_hdf_fixed_write_compress(df)1 loops, best of 3: 245 ms per loopIn [16]:%timeittest_hdf_table_write(df)1 loops, best of 3: 901 ms per loopIn [27]:%timeittest_hdf_table_write_compress(df)1 loops, best of 3: 952 ms per loopIn [17]:%timeittest_csv_write(df)1 loops, best of 3: 3.44 s per loop

Reading

In [18]:%timeittest_sql_read()1 loops, best of 3: 766 ms per loopIn [19]:%timeittest_hdf_fixed_read()10 loops, best of 3: 19.1 ms per loopIn [28]:%timeittest_hdf_fixed_read_compress()10 loops, best of 3: 36.3 ms per loopIn [20]:%timeittest_hdf_table_read()10 loops, best of 3: 39 ms per loopIn [29]:%timeittest_hdf_table_read_compress()10 loops, best of 3: 60.6 ms per loopIn [22]:%timeittest_csv_read()1 loops, best of 3: 620 ms per loop

Space on disk (in bytes)

25843712 Apr  8 14:11 test.sql24007368 Apr  8 14:11 test_fixed.hdf15580682 Apr  8 14:11 test_fixed_compress.hdf24458444 Apr  8 14:11 test_table.hdf16797283 Apr  8 14:11 test_table_compress.hdf46152810 Apr  8 14:11 test.csv

And here’s the code

importsqlite3importosfrompandas.ioimportsqldf=pd.DataFrame(randn(1000000,2),columns=list('AB'))deftest_sql_write(df):ifos.path.exists('test.sql'):os.remove('test.sql')sql_db=sqlite3.connect('test.sql')df.to_sql(name='test_table',con=sql_db)sql_db.close()deftest_sql_read():sql_db=sqlite3.connect('test.sql')pd.read_sql_query("select * from test_table",sql_db)sql_db.close()deftest_hdf_fixed_write(df):df.to_hdf('test_fixed.hdf','test',mode='w')deftest_hdf_fixed_read():pd.read_hdf('test_fixed.hdf','test')deftest_hdf_fixed_write_compress(df):df.to_hdf('test_fixed_compress.hdf','test',mode='w',complib='blosc')deftest_hdf_fixed_read_compress():pd.read_hdf('test_fixed_compress.hdf','test')deftest_hdf_table_write(df):df.to_hdf('test_table.hdf','test',mode='w',format='table')deftest_hdf_table_read():pd.read_hdf('test_table.hdf','test')deftest_hdf_table_write_compress(df):df.to_hdf('test_table_compress.hdf','test',mode='w',complib='blosc',format='table')deftest_hdf_table_read_compress():pd.read_hdf('test_table_compress.hdf','test')deftest_csv_write(df):df.to_csv('test.csv',mode='w')deftest_csv_read():pd.read_csv('test.csv',index_col=0)

Navigation

Scroll To Top
[8]ページ先頭

©2009-2025 Movatter.jp