IO tools (text, CSV, HDF5, …)

The pandas I/O API is a set of top level reader functions accessed likepandas.read_csv() that generally return a pandas object. The correspondingwriter functions are object methods that are accessed likeDataFrame.to_csv(). Below is a table containing available readers andwriters.

Format TypeData DescriptionReaderWriter
textCSVread_csvto_csv
textJSONread_jsonto_json
textHTMLread_htmlto_html
textLocal clipboardread_clipboardto_clipboard
binaryMS Excelread_excelto_excel
binaryOpenDocumentread_excel
binaryHDF5 Formatread_hdfto_hdf
binaryFeather Formatread_featherto_feather
binaryParquet Formatread_parquetto_parquet
binaryMsgpackread_msgpackto_msgpack
binaryStataread_statato_stata
binarySAS)read_sas
binaryPython Pickle Formatread_pickleto_pickle
SQLSQLread_sqlto_sql
SQLGoogle Big Queryread_gbqto_gbq

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

Note

For examples that use the StringIO class, make sure you import itaccording to your Python version, i.e. from StringIO import StringIO forPython 2 and from io import StringIO for Python 3.

CSV & text files

The workhorse function for reading text files (a.k.a. flat files) isread_csv(). See the cookbook for some advanced strategies.

Parsing options

read_csv() accepts the following common arguments:

Basic

  • filepath_or_buffer :various
  • Either a path to a file (a str, pathlib.Path,or py._path.local.LocalPath), URL (including http, ftp, and S3locations), or any object with a read() method (such as an open file orStringIO).
  • sep :str, defaults to ',' for read_csv(), \t for read_table()
  • Delimiter to use. If sep is None, the C engine cannot automatically detectthe separator, but the Python parsing engine can, meaning the latter will beused and automatically detect the separator by Python’s builtin sniffer tool,csv.Sniffer. In addition, separators longer than 1 character anddifferent from '\s+' will be interpreted as regular expressions andwill also force the use of the Python parsing engine. Note that regexdelimiters are prone to ignoring quoted data. Regex example: '\r\t'.
  • delimiter :str, default None
  • 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 setting sep='\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 thedata. Default behavior is to infer the column names: if no names arepassed the behavior is identical to header=0 and column namesare inferred from the first line of the file, if column names arepassed explicitly then the behavior is identical toheader=None. Explicitly pass header=0 to be able to replaceexisting names.

The header can be a list of ints that specify row locationsfor a MultiIndex on the columns e.g. [0,1,3]. Intervening rowsthat are not specified will be skipped (e.g. 2 in this example isskipped). Note that this parameter ignores commented lines and emptylines if skip_blank_lines=True, so header=0 denotes the firstline of data rather than the first line of the file.

  • names :array-like, default None
  • List of column names to use. If file contains no header row, then you shouldexplicitly pass header=None. Duplicates in this list are not allowed.
  • index_col :int, str, sequence of int / str, or False, default None
  • Column(s) to use as the row labels of the DataFrame, either given asstring name or column index. If a sequence of int / str is given, aMultiIndex is used.

Note: indexcol=False can be used to force pandas to _not use the firstcolumn as the index, e.g. when you have a malformed file with delimiters atthe end of each line.

  • usecols :list-like or callable, default None
  • Return a subset of the columns. If list-like, all elements must eitherbe positional (i.e. integer indices into the document columns) or stringsthat correspond to column names provided either by the user in names orinferred from the document header row(s). For example, a valid list-likeusecols parameter would be [0, 1, 2] or ['foo', 'bar', 'baz'].

Element order is ignored, so usecols=[0, 1] is the same as [1, 0]. Toinstantiate a DataFrame from data with element order preserved usepd.read_csv(data, usecols=['foo', 'bar'])[['foo', 'bar']] for columnsin ['foo', 'bar'] order orpd.read_csv(data, usecols=['foo', 'bar'])[['bar', 'foo']] for['bar', 'foo'] order.

If callable, the callable function will be evaluated against the column names,returning names where the callable function evaluates to True:

  1. In [1]: from io import StringIO, BytesIO
  2.  
  3. In [2]: data = ('col1,col2,col3\n'
  4. ...: 'a,b,1\n'
  5. ...: 'a,b,2\n'
  6. ...: 'c,d,3')
  7. ...:
  8.  
  9. In [3]: pd.read_csv(StringIO(data))
  10. Out[3]:
  11. col1 col2 col3
  12. 0 a b 1
  13. 1 a b 2
  14. 2 c d 3
  15.  
  16. In [4]: pd.read_csv(StringIO(data), usecols=lambda x: x.upper() in ['COL1', 'COL3'])
  17. Out[4]:
  18. col1 col3
  19. 0 a 1
  20. 1 a 2
  21. 2 c 3

Using this parameter results in much faster parsing time and lower memory usage.

  • squeeze :boolean, default False
  • If the parsed data only contains one column then return a Series.
  • prefix :str, default None
  • Prefix to add to column numbers when no header, e.g. ‘X’ for X0, X1, …
  • mangle_dupe_cols :boolean, default True
  • Duplicate columns will be specified as ‘X’, ‘X.1’…’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, default None
  • Data type for data or columns. E.g. {'a': np.float64, 'b': np.int32}(unsupported with engine='python'). Use str or object togetherwith suitable na_values settings to preserve andnot interpret dtype.

New in version 0.20.0: support for the Python parser.

  • engine :{'c', 'python'}
  • Parser engine to use. The C engine is faster while the Python engine iscurrently more feature-complete.
  • converters :dict, default None
  • Dict of functions for converting values in certain columns. Keys can either beintegers or column labels.
  • true_values :list, default None
  • Values to consider as True.
  • false_values :list, default None
  • Values to consider as False.
  • skipinitialspace :boolean, default False
  • Skip spaces after delimiter.
  • skiprows :list-like or integer, default None
  • Line numbers to skip (0-indexed) or number of lines to skip (int) at the startof the file.

If callable, the callable function will be evaluated against the rowindices, returning True if the row should be skipped and False otherwise:

  1. In [5]: data = ('col1,col2,col3\n'
  2. ...: 'a,b,1\n'
  3. ...: 'a,b,2\n'
  4. ...: 'c,d,3')
  5. ...:
  6.  
  7. In [6]: pd.read_csv(StringIO(data))
  8. Out[6]:
  9. col1 col2 col3
  10. 0 a b 1
  11. 1 a b 2
  12. 2 c d 3
  13.  
  14. In [7]: pd.read_csv(StringIO(data), skiprows=lambda x: x % 2 != 0)
  15. Out[7]:
  16. col1 col2 col3
  17. 0 a b 2
  • skipfooter :int, default 0
  • Number of lines at bottom of file to skip (unsupported with engine=’c’).
  • nrows :int, default None
  • Number of rows of file to read. Useful for reading pieces of large files.
  • low_memory :boolean, default True
  • Internally process the file in chunks, resulting in lower memory usewhile parsing, but possibly mixed type inference. To ensure no mixedtypes either set False, or specify the type with the dtype parameter.Note that the entire file is read into a single DataFrame regardless,use the chunksize or iterator parameter to return the data in chunks.(Only valid with C parser)
  • memory_map :boolean, default False
  • If a filepath is provided for filepath_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, default None
  • Additional strings to recognize as NA/NaN. If dict passed, specific per-columnNA values. See na values const belowfor a list of the values interpreted as NaN by default.
  • keep_default_na :boolean, default True
  • Whether or not to include the default NaN values when parsing the data.Depending on whether na_values is passed in, the behavior is as follows:

    • If keep_default_na is True, and na_values are specified, _na_values_is appended to the default NaN values used for parsing.
    • If keep_default_na is True, and na_values are not specified, onlythe default NaN values are used for parsing.
    • If keep_default_na is False, and na_values are specified, onlythe NaN values specified na_values are used for parsing.
    • If keep_default_na is False, and na_values are not specified, nostrings will be parsed as NaN.Note that if na_filter is passed in as False, the keep_default_na andna_values parameters will be ignored.
  • na_filter :boolean, default True

  • Detect missing value markers (empty strings and the value of na_values). Indata without any NAs, passing na_filter=False can improve the performanceof reading a large file.
  • verbose :boolean, default False
  • Indicate number of NA values placed in non-numeric columns.
  • skip_blank_lines :boolean, default True
  • If True, 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, default False.
    • If True -> 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, default False
  • If True and parse_dates is enabled for a column, attempt to infer thedatetime format to speed up the processing.
  • keep_date_col :boolean, default False
  • If True and parse_dates specifies combining multiple columns then keep theoriginal columns.
  • date_parser :function, default None
  • Function to use for converting a sequence of string columns to an array ofdatetime instances. The default uses dateutil.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, default False
  • DD/MM format dates, international and European format.
  • cache_dates :boolean, default True
  • If True, use a cache of unique, converted dates to apply the datetimeconversion. May produce significant speed-up when parsing duplicatedate strings, especially ones with timezone offsets.

New in version 0.25.0.

Iteration

  • iterator :boolean, default False
  • Return TextFileReader object for iteration or getting chunks withget_chunk().
  • chunksize :int, default None
  • Return TextFileReader object for iteration. See iterating 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 to None for no decompression.

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

Changed in version 0.24.0: ‘infer’ option added and set to default.

  • thousands :str, default None
  • 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 are None for the ordinary converter, high for thehigh-precision converter, and round_trip for the round-trip converter.
  • lineterminator :str (length 1), default None
  • 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 or csv.QUOTE_* instance, default 0
  • Control field quoting behavior per csv.QUOTE_* constants. Use one ofQUOTE_MINIMAL (0), QUOTE_ALL (1), QUOTE_NONNUMERIC (2) orQUOTE_NONE (3).
  • doublequote :boolean, default True
  • When quotechar is specified and quoting is not QUOTE_NONE,indicate whether or not to interpret two consecutive quotechar elementsinside a field as a single quotechar element.
  • escapechar :str (length 1), default None
  • One-character string used to escape delimiter when quoting is QUOTE_NONE.
  • comment :str, default None
  • 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 as skipblank_lines=True), fullycommented lines are ignored by the parameter _header but not by skiprows.For example, if comment='#', parsing ‘#empty\na,b,c\n1,2,3’ withheader=0 will result in ‘a,b,c’ being treated as the header.
  • encoding :str, default None
  • Encoding to use for UTF when reading/writing (e.g. 'utf-8'). List ofPython standard encodings.
  • dialect :str or csv.Dialect instance, default None
  • If provided, this parameter will override values (default or not) for thefollowing parameters: delimiter, doublequote, escapechar,skipinitialspace, quotechar, and quoting. If it is necessary tooverride values, a ParserWarning will be issued. See csv.Dialectdocumentation for more details.

Error handling

  • error_bad_lines :boolean, default True
  • 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 bereturned. If False, then these “bad lines” will dropped from theDataFrame that is returned. See bad linesbelow.
  • warn_bad_lines :boolean, default True
  • If error_bad_lines is False, and warn_bad_lines is True, a warning foreach “bad line” will be output.

Specifying column data types

You can indicate the data type for the whole DataFrame or individualcolumns:

  1. In [8]: data = ('a,b,c,d\n'
  2. ...: '1,2,3,4\n'
  3. ...: '5,6,7,8\n'
  4. ...: '9,10,11')
  5. ...:
  6.  
  7. In [9]: print(data)
  8. a,b,c,d
  9. 1,2,3,4
  10. 5,6,7,8
  11. 9,10,11
  12.  
  13. In [10]: df = pd.read_csv(StringIO(data), dtype=object)
  14.  
  15. In [11]: df
  16. Out[11]:
  17. a b c d
  18. 0 1 2 3 4
  19. 1 5 6 7 8
  20. 2 9 10 11 NaN
  21.  
  22. In [12]: df['a'][0]
  23. Out[12]: '1'
  24.  
  25. In [13]: df = pd.read_csv(StringIO(data),
  26. ....: dtype={'b': object, 'c': np.float64, 'd': 'Int64'})
  27. ....:
  28.  
  29. In [14]: df.dtypes
  30. Out[14]:
  31. a int64
  32. b object
  33. c float64
  34. d Int64
  35. dtype: object

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

For instance, you can use the converters argumentof read_csv():

  1. In [15]: data = ("col_1\n"
  2. ....: "1\n"
  3. ....: "2\n"
  4. ....: "'A'\n"
  5. ....: "4.22")
  6. ....:
  7.  
  8. In [16]: df = pd.read_csv(StringIO(data), converters={'col_1': str})
  9.  
  10. In [17]: df
  11. Out[17]:
  12. col_1
  13. 0 1
  14. 1 2
  15. 2 'A'
  16. 3 4.22
  17.  
  18. In [18]: df['col_1'].apply(type).value_counts()
  19. Out[18]:
  20. <class 'str'> 4
  21. Name: col_1, dtype: int64

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

  1. In [19]: df2 = pd.read_csv(StringIO(data))
  2.  
  3. In [20]: df2['col_1'] = pd.to_numeric(df2['col_1'], errors='coerce')
  4.  
  5. In [21]: df2
  6. Out[21]:
  7. col_1
  8. 0 1.00
  9. 1 2.00
  10. 2 NaN
  11. 3 4.22
  12.  
  13. In [22]: df2['col_1'].apply(type).value_counts()
  14. Out[22]:
  15. <class 'float'> 4
  16. Name: col_1, dtype: int64

which will convert all valid parsing to floats, leaving the invalid parsingas NaN.

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

New in version 0.20.0: support for the Python parser.

The dtype option is supported by the ‘python’ engine.

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,

  1. In [23]: col_1 = list(range(500000)) + ['a', 'b'] + list(range(500000))
  2.  
  3. In [24]: df = pd.DataFrame({'col_1': col_1})
  4.  
  5. In [25]: df.to_csv('foo.csv')
  6.  
  7. In [26]: mixed_df = pd.read_csv('foo.csv')
  8.  
  9. In [27]: mixed_df['col_1'].apply(type).value_counts()
  10. Out[27]:
  11. <class 'int'> 737858
  12. <class 'str'> 262144
  13. Name: col_1, dtype: int64
  14.  
  15. In [28]: mixed_df['col_1'].dtype
  16. Out[28]: dtype('O')

will result with mixed_df containing an int dtype for certain chunksof the column, and str 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 a dtype of object, which is used for columns with mixed dtypes.

Specifying categorical dtype

New in version 0.19.0.

Categorical columns can be parsed directly by specifying dtype='category' ordtype=CategoricalDtype(categories, ordered).

  1. In [29]: data = ('col1,col2,col3\n'
  2. ....: 'a,b,1\n'
  3. ....: 'a,b,2\n'
  4. ....: 'c,d,3')
  5. ....:
  6.  
  7. In [30]: pd.read_csv(StringIO(data))
  8. Out[30]:
  9. col1 col2 col3
  10. 0 a b 1
  11. 1 a b 2
  12. 2 c d 3
  13.  
  14. In [31]: pd.read_csv(StringIO(data)).dtypes
  15. Out[31]:
  16. col1 object
  17. col2 object
  18. col3 int64
  19. dtype: object
  20.  
  21. In [32]: pd.read_csv(StringIO(data), dtype='category').dtypes
  22. Out[32]:
  23. col1 category
  24. col2 category
  25. col3 category
  26. dtype: object

Individual columns can be parsed as a Categorical using a dictspecification:

  1. In [33]: pd.read_csv(StringIO(data), dtype={'col1': 'category'}).dtypes
  2. Out[33]:
  3. col1 category
  4. col2 object
  5. col3 int64
  6. dtype: object

New in version 0.21.0.

Specifying dtype='category' will result in an unordered Categoricalwhose categories are the unique values observed in the data. For morecontrol on the categories and order, create aCategoricalDtype ahead of time, and pass that forthat column’s dtype.

  1. In [34]: from pandas.api.types import CategoricalDtype
  2.  
  3. In [35]: dtype = CategoricalDtype(['d', 'c', 'b', 'a'], ordered=True)
  4.  
  5. In [36]: pd.read_csv(StringIO(data), dtype={'col1': dtype}).dtypes
  6. Out[36]:
  7. col1 category
  8. col2 object
  9. col3 int64
  10. dtype: object

When using dtype=CategoricalDtype, “unexpected” values outside ofdtype.categories are treated as missing values.

  1. In [37]: dtype = CategoricalDtype(['a', 'b', 'd']) # No 'c'
  2.  
  3. In [38]: pd.read_csv(StringIO(data), dtype={'col1': dtype}).col1
  4. Out[38]:
  5. 0 a
  6. 1 a
  7. 2 NaN
  8. Name: col1, dtype: category
  9. Categories (3, object): [a, b, d]

This matches the behavior of Categorical.set_categories().

Note

With dtype='category', the resulting categories will always be parsedas strings (object dtype). If the categories are numeric they can beconverted using the to_numeric() function, or as appropriate, anotherconverter such as to_datetime().

When dtype is a CategoricalDtype with homogeneous categories (all numeric, all datetimes, etc.), the conversion is done automatically.

  1. In [39]: df = pd.read_csv(StringIO(data), dtype='category')
  2.  
  3. In [40]: df.dtypes
  4. Out[40]:
  5. col1 category
  6. col2 category
  7. col3 category
  8. dtype: object
  9.  
  10. In [41]: df['col3']
  11. Out[41]:
  12. 0 1
  13. 1 2
  14. 2 3
  15. Name: col3, dtype: category
  16. Categories (3, object): [1, 2, 3]
  17.  
  18. In [42]: df['col3'].cat.categories = pd.to_numeric(df['col3'].cat.categories)
  19.  
  20. In [43]: df['col3']
  21. Out[43]:
  22. 0 1
  23. 1 2
  24. 2 3
  25. Name: col3, dtype: category
  26. Categories (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:

  1. In [44]: data = ('a,b,c\n'
  2. ....: '1,2,3\n'
  3. ....: '4,5,6\n'
  4. ....: '7,8,9')
  5. ....:
  6.  
  7. In [45]: print(data)
  8. a,b,c
  9. 1,2,3
  10. 4,5,6
  11. 7,8,9
  12.  
  13. In [46]: pd.read_csv(StringIO(data))
  14. Out[46]:
  15. a b c
  16. 0 1 2 3
  17. 1 4 5 6
  18. 2 7 8 9

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

  1. In [47]: print(data)
  2. a,b,c
  3. 1,2,3
  4. 4,5,6
  5. 7,8,9
  6.  
  7. In [48]: pd.read_csv(StringIO(data), names=['foo', 'bar', 'baz'], header=0)
  8. Out[48]:
  9. foo bar baz
  10. 0 1 2 3
  11. 1 4 5 6
  12. 2 7 8 9
  13.  
  14. In [49]: pd.read_csv(StringIO(data), names=['foo', 'bar', 'baz'], header=None)
  15. Out[49]:
  16. foo bar baz
  17. 0 a b c
  18. 1 1 2 3
  19. 2 4 5 6
  20. 3 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:

  1. In [50]: data = ('skip this skip it\n'
  2. ....: 'a,b,c\n'
  3. ....: '1,2,3\n'
  4. ....: '4,5,6\n'
  5. ....: '7,8,9')
  6. ....:
  7.  
  8. In [51]: pd.read_csv(StringIO(data), header=1)
  9. Out[51]:
  10. a b c
  11. 0 1 2 3
  12. 1 4 5 6
  13. 2 7 8 9

Note

Default behavior is to infer the column names: if no names arepassed the behavior is identical to header=0 and column namesare inferred from the first non-blank line of the file, if columnnames are passed explicitly then the behavior is identical toheader=None.

Duplicate names parsing

If the file or header contains duplicate names, pandas will by defaultdistinguish between them so as to prevent overwriting data:

  1. In [52]: data = ('a,b,a\n'
  2. ....: '0,1,2\n'
  3. ....: '3,4,5')
  4. ....:
  5.  
  6. In [53]: pd.read_csv(StringIO(data))
  7. Out[53]:
  8. a b a.1
  9. 0 0 1 2
  10. 1 3 4 5

There is no more duplicate data because mangle_dupe_cols=True by default,which modifies a series of duplicate columns ‘X’, …, ‘X’ to become‘X’, ‘X.1’, …, ‘X.N’. If mangle_dupe_cols=False, duplicate data canarise:

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

To prevent users from encountering this problem with duplicate data, a ValueErrorexception is raised if mangle_dupe_cols != True:

  1. In [2]: data = 'a,b,a\n0,1,2\n3,4,5'
  2. In [3]: pd.read_csv(StringIO(data), mangle_dupe_cols=False)
  3. ...
  4. ValueError: Setting mangle_dupe_cols=False is not supported yet

Filtering columns (usecols)

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

New in version 0.20.0: support for callable usecols arguments

  1. In [54]: data = 'a,b,c,d\n1,2,3,foo\n4,5,6,bar\n7,8,9,baz'
  2.  
  3. In [55]: pd.read_csv(StringIO(data))
  4. Out[55]:
  5. a b c d
  6. 0 1 2 3 foo
  7. 1 4 5 6 bar
  8. 2 7 8 9 baz
  9.  
  10. In [56]: pd.read_csv(StringIO(data), usecols=['b', 'd'])
  11. Out[56]:
  12. b d
  13. 0 2 foo
  14. 1 5 bar
  15. 2 8 baz
  16.  
  17. In [57]: pd.read_csv(StringIO(data), usecols=[0, 2, 3])
  18. Out[57]:
  19. a c d
  20. 0 1 3 foo
  21. 1 4 6 bar
  22. 2 7 9 baz
  23.  
  24. In [58]: pd.read_csv(StringIO(data), usecols=lambda x: x.upper() in ['A', 'C'])
  25. Out[58]:
  26. a c
  27. 0 1 3
  28. 1 4 6
  29. 2 7 9

The usecols argument can also be used to specify which columns not touse in the final result:

  1. In [59]: pd.read_csv(StringIO(data), usecols=lambda x: x not in ['a', 'c'])
  2. Out[59]:
  3. b d
  4. 0 2 foo
  5. 1 5 bar
  6. 2 8 baz

In this case, the callable is specifying that we exclude the “a” and “c”columns from the output.

Comments and empty lines

Ignoring line comments and empty lines

If the comment parameter is specified, then completely commented lines willbe ignored. By default, completely blank lines will be ignored as well.

  1. In [60]: data = ('\n'
  2. ....: 'a,b,c\n'
  3. ....: ' \n'
  4. ....: '# commented line\n'
  5. ....: '1,2,3\n'
  6. ....: '\n'
  7. ....: '4,5,6')
  8. ....:
  9.  
  10. In [61]: print(data)
  11.  
  12. a,b,c
  13.  
  14. # commented line
  15. 1,2,3
  16.  
  17. 4,5,6
  18.  
  19. In [62]: pd.read_csv(StringIO(data), comment='#')
  20. Out[62]:
  21. a b c
  22. 0 1 2 3
  23. 1 4 5 6

If skip_blank_lines=False, then read_csv will not ignore blank lines:

  1. In [63]: data = ('a,b,c\n'
  2. ....: '\n'
  3. ....: '1,2,3\n'
  4. ....: '\n'
  5. ....: '\n'
  6. ....: '4,5,6')
  7. ....:
  8.  
  9. In [64]: pd.read_csv(StringIO(data), skip_blank_lines=False)
  10. Out[64]:
  11. a b c
  12. 0 NaN NaN NaN
  13. 1 1.0 2.0 3.0
  14. 2 NaN NaN NaN
  15. 3 NaN NaN NaN
  16. 4 4.0 5.0 6.0

Warning

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

  1. In [65]: data = ('#comment\n'
  2. ....: 'a,b,c\n'
  3. ....: 'A,B,C\n'
  4. ....: '1,2,3')
  5. ....:
  6.  
  7. In [66]: pd.read_csv(StringIO(data), comment='#', header=1)
  8. Out[66]:
  9. A B C
  10. 0 1 2 3
  11.  
  12. In [67]: data = ('A,B,C\n'
  13. ....: '#comment\n'
  14. ....: 'a,b,c\n'
  15. ....: '1,2,3')
  16. ....:
  17.  
  18. In [68]: pd.read_csv(StringIO(data), comment='#', skiprows=2)
  19. Out[68]:
  20. a b c
  21. 0 1 2 3

If both header and skiprows are specified, header will berelative to the end of skiprows. For example:

  1. In [69]: data = ('# empty\n'
  2. ....: '# second empty line\n'
  3. ....: '# third emptyline\n'
  4. ....: 'X,Y,Z\n'
  5. ....: '1,2,3\n'
  6. ....: 'A,B,C\n'
  7. ....: '1,2.,4.\n'
  8. ....: '5.,NaN,10.0\n')
  9. ....:
  10.  
  11. In [70]: print(data)
  12. # empty
  13. # second empty line
  14. # third emptyline
  15. X,Y,Z
  16. 1,2,3
  17. A,B,C
  18. 1,2.,4.
  19. 5.,NaN,10.0
  20.  
  21.  
  22. In [71]: pd.read_csv(StringIO(data), comment='#', skiprows=4, header=1)
  23. Out[71]:
  24. A B C
  25. 0 1.0 2.0 4.0
  26. 1 5.0 NaN 10.0

Comments

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

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

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

  1. In [73]: df = pd.read_csv('tmp.csv')
  2.  
  3. In [74]: df
  4. Out[74]:
  5. ID level category
  6. 0 Patient1 123000 x # really unpleasant
  7. 1 Patient2 23000 y # wouldn't take his medicine
  8. 2 Patient3 1234018 z # awesome

We can suppress the comments using the comment keyword:

  1. In [75]: df = pd.read_csv('tmp.csv', comment='#')
  2.  
  3. In [76]: df
  4. Out[76]:
  5. ID level category
  6. 0 Patient1 123000 x
  7. 1 Patient2 23000 y
  8. 2 Patient3 1234018 z

Dealing with Unicode data

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

  1. In [77]: data = (b'word,length\n'
  2. ....: b'Tr\xc3\xa4umen,7\n'
  3. ....: b'Gr\xc3\xbc\xc3\x9fe,5')
  4. ....:
  5.  
  6. In [78]: data = data.decode('utf8').encode('latin-1')
  7.  
  8. In [79]: df = pd.read_csv(BytesIO(data), encoding='latin-1')
  9.  
  10. In [80]: df
  11. Out[80]:
  12. word length
  13. 0 Träumen 7
  14. 1 Grüße 5
  15.  
  16. In [81]: df['word'][1]
  17. Out[81]: 'Grüße'

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:

  1. In [82]: data = ('a,b,c\n'
  2. ....: '4,apple,bat,5.7\n'
  3. ....: '8,orange,cow,10')
  4. ....:
  5.  
  6. In [83]: pd.read_csv(StringIO(data))
  7. Out[83]:
  8. a b c
  9. 4 apple bat 5.7
  10. 8 orange cow 10.0
  1. In [84]: data = ('index,a,b,c\n'
  2. ....: '4,apple,bat,5.7\n'
  3. ....: '8,orange,cow,10')
  4. ....:
  5.  
  6. In [85]: pd.read_csv(StringIO(data), index_col=0)
  7. Out[85]:
  8. a b c
  9. index
  10. 4 apple bat 5.7
  11. 8 orange cow 10.0

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

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

  1. In [86]: data = ('a,b,c\n'
  2. ....: '4,apple,bat,\n'
  3. ....: '8,orange,cow,')
  4. ....:
  5.  
  6. In [87]: print(data)
  7. a,b,c
  8. 4,apple,bat,
  9. 8,orange,cow,
  10.  
  11. In [88]: pd.read_csv(StringIO(data))
  12. Out[88]:
  13. a b c
  14. 4 apple bat NaN
  15. 8 orange cow NaN
  16.  
  17. In [89]: pd.read_csv(StringIO(data), index_col=False)
  18. Out[89]:
  19. a b c
  20. 0 4 apple bat
  21. 1 8 orange cow

If a subset of data is being parsed using the usecols option, theindex_col specification is based on that subset, not the original data.

  1. In [90]: data = ('a,b,c\n'
  2. ....: '4,apple,bat,\n'
  3. ....: '8,orange,cow,')
  4. ....:
  5.  
  6. In [91]: print(data)
  7. a,b,c
  8. 4,apple,bat,
  9. 8,orange,cow,
  10.  
  11. In [92]: pd.read_csv(StringIO(data), usecols=['b', 'c'])
  12. Out[92]:
  13. b c
  14. 4 bat NaN
  15. 8 cow NaN
  16.  
  17. In [93]: pd.read_csv(StringIO(data), usecols=['b', 'c'], index_col=0)
  18. Out[93]:
  19. b c
  20. 4 bat NaN
  21. 8 cow NaN

Date Handling

Specifying date columns

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

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

  1. # Use a column as an index, and parse it as dates.
  2. In [94]: df = pd.read_csv('foo.csv', index_col=0, parse_dates=True)
  3.  
  4. In [95]: df
  5. Out[95]:
  6. A B C
  7. date
  8. 2009-01-01 a 1 2
  9. 2009-01-02 b 3 4
  10. 2009-01-03 c 4 5
  11.  
  12. # These are Python datetime objects
  13. In [96]: df.index
  14. Out[96]: DatetimeIndex(['2009-01-01', '2009-01-02', '2009-01-03'], dtype='datetime64[ns]', name='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. the parse_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 to parse_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:

  1. In [97]: print(open('tmp.csv').read())
  2. KORD,19990127, 19:00:00, 18:56:00, 0.8100
  3. KORD,19990127, 20:00:00, 19:56:00, 0.0100
  4. KORD,19990127, 21:00:00, 20:56:00, -0.5900
  5. KORD,19990127, 21:00:00, 21:18:00, -0.9900
  6. KORD,19990127, 22:00:00, 21:56:00, -0.5900
  7. KORD,19990127, 23:00:00, 22:56:00, -0.5900
  8.  
  9. In [98]: df = pd.read_csv('tmp.csv', header=None, parse_dates=[[1, 2], [1, 3]])
  10.  
  11. In [99]: df
  12. Out[99]:
  13. 1_2 1_3 0 4
  14. 0 1999-01-27 19:00:00 1999-01-27 18:56:00 KORD 0.81
  15. 1 1999-01-27 20:00:00 1999-01-27 19:56:00 KORD 0.01
  16. 2 1999-01-27 21:00:00 1999-01-27 20:56:00 KORD -0.59
  17. 3 1999-01-27 21:00:00 1999-01-27 21:18:00 KORD -0.99
  18. 4 1999-01-27 22:00:00 1999-01-27 21:56:00 KORD -0.59
  19. 5 1999-01-27 23:00:00 1999-01-27 22:56:00 KORD -0.59

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

  1. In [100]: df = pd.read_csv('tmp.csv', header=None, parse_dates=[[1, 2], [1, 3]],
  2. .....: keep_date_col=True)
  3. .....:
  4.  
  5. In [101]: df
  6. Out[101]:
  7. 1_2 1_3 0 1 2 3 4
  8. 0 1999-01-27 19:00:00 1999-01-27 18:56:00 KORD 19990127 19:00:00 18:56:00 0.81
  9. 1 1999-01-27 20:00:00 1999-01-27 19:56:00 KORD 19990127 20:00:00 19:56:00 0.01
  10. 2 1999-01-27 21:00:00 1999-01-27 20:56:00 KORD 19990127 21:00:00 20:56:00 -0.59
  11. 3 1999-01-27 21:00:00 1999-01-27 21:18:00 KORD 19990127 21:00:00 21:18:00 -0.99
  12. 4 1999-01-27 22:00:00 1999-01-27 21:56:00 KORD 19990127 22:00:00 21:56:00 -0.59
  13. 5 1999-01-27 23:00:00 1999-01-27 22:56:00 KORD 19990127 23:00:00 22:56:00 -0.59

Note that if you wish to combine multiple columns into a single date column, 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 columnswhile parse_dates=[[1, 2]] means the two columns should be parsed into asingle column.

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

  1. In [102]: date_spec = {'nominal': [1, 2], 'actual': [1, 3]}
  2.  
  3. In [103]: df = pd.read_csv('tmp.csv', header=None, parse_dates=date_spec)
  4.  
  5. In [104]: df
  6. Out[104]:
  7. nominal actual 0 4
  8. 0 1999-01-27 19:00:00 1999-01-27 18:56:00 KORD 0.81
  9. 1 1999-01-27 20:00:00 1999-01-27 19:56:00 KORD 0.01
  10. 2 1999-01-27 21:00:00 1999-01-27 20:56:00 KORD -0.59
  11. 3 1999-01-27 21:00:00 1999-01-27 21:18:00 KORD -0.99
  12. 4 1999-01-27 22:00:00 1999-01-27 21:56:00 KORD -0.59
  13. 5 1999-01-27 23:00:00 1999-01-27 22:56:00 KORD -0.59

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

  1. In [105]: date_spec = {'nominal': [1, 2], 'actual': [1, 3]}
  2.  
  3. In [106]: df = pd.read_csv('tmp.csv', header=None, parse_dates=date_spec,
  4. .....: index_col=0) # index is the nominal column
  5. .....:
  6.  
  7. In [107]: df
  8. Out[107]:
  9. actual 0 4
  10. nominal
  11. 1999-01-27 19:00:00 1999-01-27 18:56:00 KORD 0.81
  12. 1999-01-27 20:00:00 1999-01-27 19:56:00 KORD 0.01
  13. 1999-01-27 21:00:00 1999-01-27 20:56:00 KORD -0.59
  14. 1999-01-27 21:00:00 1999-01-27 21:18:00 KORD -0.99
  15. 1999-01-27 22:00:00 1999-01-27 21:56:00 KORD -0.59
  16. 1999-01-27 23:00:00 1999-01-27 22:56:00 KORD -0.59

Note

If a column or index contains an unparsable date, the entire column orindex will be returned unaltered as an object data type. For non-standarddatetime parsing, use to_datetime() after pd.read_csv.

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 the parse_dates argument, the order ofthe columns prepended is not guaranteed, because dict objects do not imposean ordering on their keys. On Python 2.7+ you may use collections.OrderedDict_instead of a regular _dict if this matters to you. Because of this, when using adict for ‘parsedates’ in conjunction with the _index_col argument, it’s best tospecify index_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 custom date_parser function totake full advantage of the flexibility of the date parsing API:

  1. In [108]: df = pd.read_csv('tmp.csv', header=None, parse_dates=date_spec,
  2. .....: date_parser=pd.io.date_converters.parse_date_time)
  3. .....:
  4.  
  5. In [109]: df
  6. Out[109]:
  7. nominal actual 0 4
  8. 0 1999-01-27 19:00:00 1999-01-27 18:56:00 KORD 0.81
  9. 1 1999-01-27 20:00:00 1999-01-27 19:56:00 KORD 0.01
  10. 2 1999-01-27 21:00:00 1999-01-27 20:56:00 KORD -0.59
  11. 3 1999-01-27 21:00:00 1999-01-27 21:18:00 KORD -0.99
  12. 4 1999-01-27 22:00:00 1999-01-27 21:56:00 KORD -0.59
  13. 5 1999-01-27 23:00:00 1999-01-27 22:56:00 KORD -0.59

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

  • dateparser is first called with one or more arrays as arguments,as defined using _parse_dates (e.g., date_parser(['2013', '2013'], ['1', '2'])).
  • If #1 fails, date_parser is called with all the columnsconcatenated row-wise into a single array (e.g., date_parser(['2013 1', '2013 2'])).
  • If #2 fails, dateparser is called once for every row with one or morestring arguments from the columns indicated with _parse_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:

  • Try to infer the format using infer_datetime_format=True (see section below).

  • If you know the format, use pd.to_datetime():date_parser=lambda x: pd.to_datetime(x, format=…).
  • If you have a really non-standard format, use a custom date_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.pyand add your own. We would love to turn this module into a community supportedset of 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.

Parsing a CSV with mixed timezones

Pandas cannot natively represent a column or index with mixed timezones. If your CSVfile contains columns with a mixture of timezones, the default result will bean object-dtype column with strings, even with parse_dates.

  1. In [110]: content = """\
  2. .....: a
  3. .....: 2000-01-01T00:00:00+05:00
  4. .....: 2000-01-01T00:00:00+06:00"""
  5. .....:
  6.  
  7. In [111]: df = pd.read_csv(StringIO(content), parse_dates=['a'])
  8.  
  9. In [112]: df['a']
  10. Out[112]:
  11. 0 2000-01-01 00:00:00+05:00
  12. 1 2000-01-01 00:00:00+06:00
  13. Name: a, dtype: object

To parse the mixed-timezone values as a datetime column, pass a partially-appliedto_datetime() with utc=True as the date_parser.

  1. In [113]: df = pd.read_csv(StringIO(content), parse_dates=['a'],
  2. .....: date_parser=lambda col: pd.to_datetime(col, utc=True))
  3. .....:
  4.  
  5. In [114]: df['a']
  6. Out[114]:
  7. 0 1999-12-31 19:00:00+00:00
  8. 1 1999-12-31 18:00:00+00:00
  9. Name: a, dtype: datetime64[ns, UTC]

Inferring datetime format

If you have parse_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 setting infer_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”

Note that infer_datetime_format is sensitive to dayfirst. 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.

  1. # Try to infer the format for the index column
  2. In [115]: df = pd.read_csv('foo.csv', index_col=0, parse_dates=True,
  3. .....: infer_datetime_format=True)
  4. .....:
  5.  
  6. In [116]: df
  7. Out[116]:
  8. A B C
  9. date
  10. 2009-01-01 a 1 2
  11. 2009-01-02 b 3 4
  12. 2009-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, a dayfirst keyword is provided:

  1. In [117]: print(open('tmp.csv').read())
  2. date,value,cat
  3. 1/6/2000,5,a
  4. 2/6/2000,10,b
  5. 3/6/2000,15,c
  6.  
  7. In [118]: pd.read_csv('tmp.csv', parse_dates=[0])
  8. Out[118]:
  9. date value cat
  10. 0 2000-01-06 5 a
  11. 1 2000-02-06 10 b
  12. 2 2000-03-06 15 c
  13.  
  14. In [119]: pd.read_csv('tmp.csv', dayfirst=True, parse_dates=[0])
  15. Out[119]:
  16. date value cat
  17. 0 2000-06-01 5 a
  18. 1 2000-06-02 10 b
  19. 2 2000-06-03 15 c

Specifying method for floating-point conversion

The parameter float_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:

  1. In [120]: val = '0.3066101993807095471566981359501369297504425048828125'
  2.  
  3. In [121]: data = 'a,b,c\n1,2,{0}'.format(val)
  4.  
  5. In [122]: abs(pd.read_csv(StringIO(data), engine='c',
  6. .....: float_precision=None)['c'][0] - float(val))
  7. .....:
  8. Out[122]: 1.1102230246251565e-16
  9.  
  10. In [123]: abs(pd.read_csv(StringIO(data), engine='c',
  11. .....: float_precision='high')['c'][0] - float(val))
  12. .....:
  13. Out[123]: 5.551115123125783e-17
  14.  
  15. In [124]: abs(pd.read_csv(StringIO(data), engine='c',
  16. .....: float_precision='round_trip')['c'][0] - float(val))
  17. .....:
  18. Out[124]: 0.0

Thousand separators

For large numbers that have been written with a thousands separator, you canset the thousands 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:

  1. In [125]: print(open('tmp.csv').read())
  2. ID|level|category
  3. Patient1|123,000|x
  4. Patient2|23,000|y
  5. Patient3|1,234,018|z
  6.  
  7. In [126]: df = pd.read_csv('tmp.csv', sep='|')
  8.  
  9. In [127]: df
  10. Out[127]:
  11. ID level category
  12. 0 Patient1 123,000 x
  13. 1 Patient2 23,000 y
  14. 2 Patient3 1,234,018 z
  15.  
  16. In [128]: df.level.dtype
  17. Out[128]: dtype('O')

The thousands keyword allows integers to be parsed correctly:

  1. In [129]: print(open('tmp.csv').read())
  2. ID|level|category
  3. Patient1|123,000|x
  4. Patient2|23,000|y
  5. Patient3|1,234,018|z
  6.  
  7. In [130]: df = pd.read_csv('tmp.csv', sep='|', thousands=',')
  8.  
  9. In [131]: df
  10. Out[131]:
  11. ID level category
  12. 0 Patient1 123000 x
  13. 1 Patient2 23000 y
  14. 2 Patient3 1234018 z
  15.  
  16. In [132]: df.level.dtype
  17. Out[132]: dtype('int64')

NA values

To control which values are parsed as missing values (which are signified byNaN), specify a string in na_values. If you specify a list of strings,then all values in it are considered to be missing values. If you specify anumber (a float, like 5.0 or an integer like 5), thecorresponding equivalent values will also imply a missing value (in this caseeffectively [5.0, 5] are recognized as NaN).

To completely override the default values that are recognized as missing, specify keep_default_na=False.

The default NaN recognized values are ['-1.#IND', '1.#QNAN', '1.#IND', '-1.#QNAN', '#N/A N/A', '#N/A', 'N/A','n/a', 'NA', '#NA', 'NULL', 'null', 'NaN', '-NaN', 'nan', '-nan', ''].

Let us consider some examples:

  1. pd.read_csv('path_to_file.csv', na_values=[5])

In the example above 5 and 5.0 will be recognized as NaN, inaddition to the defaults. A string will first be interpreted as a numerical5, then as a NaN.

  1. pd.read_csv('path_to_file.csv', keep_default_na=False, na_values=[""])

Above, only an empty field will be recognized as NaN.

  1. pd.read_csv('path_to_file.csv', keep_default_na=False, na_values=["NA", "0"])

Above, both NA and 0 as strings are NaN.

  1. pd.read_csv('path_to_file.csv', na_values=["Nope"])

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

Infinity

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

Returning Series

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

  1. In [133]: print(open('tmp.csv').read())
  2. level
  3. Patient1,123000
  4. Patient2,23000
  5. Patient3,1234018
  6.  
  7. In [134]: output = pd.read_csv('tmp.csv', squeeze=True)
  8.  
  9. In [135]: output
  10. Out[135]:
  11. Patient1 123000
  12. Patient2 23000
  13. Patient3 1234018
  14. Name: level, dtype: int64
  15.  
  16. In [136]: type(output)
  17. Out[136]: pandas.core.series.Series

Boolean values

The common values True, False, TRUE, and FALSE are allrecognized as boolean. Occasionally you might want to recognize other valuesas being boolean. To do this, use the true_values and false_valuesoptions as follows:

  1. In [137]: data = ('a,b,c\n'
  2. .....: '1,Yes,2\n'
  3. .....: '3,No,4')
  4. .....:
  5.  
  6. In [138]: print(data)
  7. a,b,c
  8. 1,Yes,2
  9. 3,No,4
  10.  
  11. In [139]: pd.read_csv(StringIO(data))
  12. Out[139]:
  13. a b c
  14. 0 1 Yes 2
  15. 1 3 No 4
  16.  
  17. In [140]: pd.read_csv(StringIO(data), true_values=['Yes'], false_values=['No'])
  18. Out[140]:
  19. a b c
  20. 0 1 True 2
  21. 1 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 fields will raise an error by default:

  1. In [141]: data = ('a,b,c\n'
  2. .....: '1,2,3\n'
  3. .....: '4,5,6,7\n'
  4. .....: '8,9,10')
  5. .....:
  6.  
  7. In [142]: pd.read_csv(StringIO(data))
  8. ---------------------------------------------------------------------------
  9. ParserError Traceback (most recent call last)
  10. <ipython-input-142-6388c394e6b8> in <module>
  11. ----> 1 pd.read_csv(StringIO(data))
  12.  
  13. /pandas/pandas/io/parsers.py in parser_f(filepath_or_buffer, sep, delimiter, header, names, index_col, usecols, squeeze, prefix, mangle_dupe_cols, dtype, engine, converters, true_values, false_values, skipinitialspace, skiprows, skipfooter, nrows, na_values, keep_default_na, na_filter, verbose, skip_blank_lines, parse_dates, infer_datetime_format, keep_date_col, date_parser, dayfirst, cache_dates, iterator, chunksize, compression, thousands, decimal, lineterminator, quotechar, quoting, doublequote, escapechar, comment, encoding, dialect, error_bad_lines, warn_bad_lines, delim_whitespace, low_memory, memory_map, float_precision)
  14. 683 )
  15. 684
  16. --> 685 return _read(filepath_or_buffer, kwds)
  17. 686
  18. 687 parser_f.__name__ = name
  19.  
  20. /pandas/pandas/io/parsers.py in _read(filepath_or_buffer, kwds)
  21. 461
  22. 462 try:
  23. --> 463 data = parser.read(nrows)
  24. 464 finally:
  25. 465 parser.close()
  26.  
  27. /pandas/pandas/io/parsers.py in read(self, nrows)
  28. 1152 def read(self, nrows=None):
  29. 1153 nrows = _validate_integer("nrows", nrows)
  30. -> 1154 ret = self._engine.read(nrows)
  31. 1155
  32. 1156 # May alter columns / col_dict
  33.  
  34. /pandas/pandas/io/parsers.py in read(self, nrows)
  35. 2057 def read(self, nrows=None):
  36. 2058 try:
  37. -> 2059 data = self._reader.read(nrows)
  38. 2060 except StopIteration:
  39. 2061 if self._first_chunk:
  40.  
  41. /pandas/pandas/_libs/parsers.pyx in pandas._libs.parsers.TextReader.read()
  42.  
  43. /pandas/pandas/_libs/parsers.pyx in pandas._libs.parsers.TextReader._read_low_memory()
  44.  
  45. /pandas/pandas/_libs/parsers.pyx in pandas._libs.parsers.TextReader._read_rows()
  46.  
  47. /pandas/pandas/_libs/parsers.pyx in pandas._libs.parsers.TextReader._tokenize_rows()
  48.  
  49. /pandas/pandas/_libs/parsers.pyx in pandas._libs.parsers.raise_parser_error()
  50.  
  51. ParserError: Error tokenizing data. C error: Expected 3 fields in line 3, saw 4

You can elect to skip bad lines:

  1. In [29]: pd.read_csv(StringIO(data), error_bad_lines=False)
  2. Skipping line 3: expected 3 fields, saw 4
  3.  
  4. Out[29]:
  5. a b c
  6. 0 1 2 3
  7. 1 8 9 10

You can also use the usecols parameter to eliminate extraneous columndata that appear in some lines but not others:

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

Dialect

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

Suppose you had data with unenclosed quotes:

  1. In [143]: print(data)
  2. label1,label2,label3
  3. index1,"a,c,e
  4. index2,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 using dialect:

  1. In [144]: import csv
  2.  
  3. In [145]: dia = csv.excel()
  4.  
  5. In [146]: dia.quoting = csv.QUOTE_NONE
  6.  
  7. In [147]: pd.read_csv(StringIO(data), dialect=dia)
  8. Out[147]:
  9. label1 label2 label3
  10. index1 "a c e
  11. index2 b d f

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

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

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

  1. In [150]: data = 'a, b, c\n1, 2, 3\n4, 5, 6'
  2.  
  3. In [151]: print(data)
  4. a, b, c
  5. 1, 2, 3
  6. 4, 5, 6
  7.  
  8. In [152]: pd.read_csv(StringIO(data), skipinitialspace=True)
  9. Out[152]:
  10. a b c
  11. 0 1 2 3
  12. 1 4 5 6

The parsers make every attempt to “do the right thing” and not be fragile. Typeinference is a pretty big deal. If a column can be coerced to integer dtypewithout altering the contents, the parser will do so. Any non-numericcolumns will come through as object dtype as with the rest of pandas objects.

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 the escapechar option:

  1. In [153]: data = 'a,b\n"hello, \\"Bob\\", nice to see you",5'
  2.  
  3. In [154]: print(data)
  4. a,b
  5. "hello, \"Bob\", nice to see you",5
  6.  
  7. In [155]: pd.read_csv(StringIO(data), escapechar='\\')
  8. Out[155]:
  9. a b
  10. 0 hello, "Bob", nice to see you 5

Files with fixed width columns

While read_csv() reads delimited data, the read_fwf() function workswith data files that have known and fixed column widths. The function parametersto readfwf are largely the same as _read_csv with two extra parameters, anda different usage of the delimiter parameter:

  • 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. Defaultbehavior, if not specified, is to infer.
  • widths: A list of field widths which can be used instead of ‘colspecs’if the intervals are contiguous.
  • delimiter: Characters to consider as filler characters in the fixed-width file.Can be used to specify the filler character of the fieldsif it is not spaces (e.g., ‘~’).

Consider a typical fixed-width data file:

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

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

  1. # Column specifications are a list of half-intervals
  2. In [157]: colspecs = [(0, 6), (8, 20), (21, 33), (34, 43)]
  3.  
  4. In [158]: df = pd.read_fwf('bar.csv', colspecs=colspecs, header=None, index_col=0)
  5.  
  6. In [159]: df
  7. Out[159]:
  8. 1 2 3
  9. 0
  10. id8141 360.242940 149.910199 11950.7
  11. id1594 444.953632 166.985655 11788.4
  12. id1849 364.136849 183.628767 11806.2
  13. id1230 413.836124 184.375703 11916.8
  14. id1948 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:

  1. # Widths are a list of integers
  2. In [160]: widths = [6, 14, 13, 10]
  3.  
  4. In [161]: df = pd.read_fwf('bar.csv', widths=widths, header=None)
  5.  
  6. In [162]: df
  7. Out[162]:
  8. 0 1 2 3
  9. 0 id8141 360.242940 149.910199 11950.7
  10. 1 id1594 444.953632 166.985655 11788.4
  11. 2 id1849 364.136849 183.628767 11806.2
  12. 3 id1230 413.836124 184.375703 11916.8
  13. 4 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.

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

  1. In [163]: df = pd.read_fwf('bar.csv', header=None, index_col=0)
  2.  
  3. In [164]: df
  4. Out[164]:
  5. 1 2 3
  6. 0
  7. id8141 360.242940 149.910199 11950.7
  8. id1594 444.953632 166.985655 11788.4
  9. id1849 364.136849 183.628767 11806.2
  10. id1230 413.836124 184.375703 11916.8
  11. id1948 502.953953 173.237159 12468.3

New in version 0.20.0.

read_fwf supports the dtype parameter for specifying the types ofparsed columns to be different from the inferred type.

  1. In [165]: pd.read_fwf('bar.csv', header=None, index_col=0).dtypes
  2. Out[165]:
  3. 1 float64
  4. 2 float64
  5. 3 float64
  6. dtype: object
  7.  
  8. In [166]: pd.read_fwf('bar.csv', header=None, dtype={2: 'object'}).dtypes
  9. Out[166]:
  10. 0 object
  11. 1 float64
  12. 2 object
  13. 3 float64
  14. dtype: object

Indexes

Files with an “implicit” index column

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

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

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

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

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

  1. In [169]: df = pd.read_csv('foo.csv', parse_dates=True)
  2.  
  3. In [170]: df.index
  4. Out[170]: DatetimeIndex(['2009-01-01', '2009-01-02', '2009-01-03'], dtype='datetime64[ns]', freq=None)

Reading an index with a MultiIndex

Suppose you have data indexed by two columns:

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

The index_col argument to read_csv can take a list ofcolumn numbers to turn multiple columns into a MultiIndex for the index of thereturned object:

  1. In [172]: df = pd.read_csv("data/mindex_ex.csv", index_col=[0, 1])
  2.  
  3. In [173]: df
  4. Out[173]:
  5. zit xit
  6. year indiv
  7. 1977 A 1.20 0.60
  8. B 1.50 0.50
  9. C 1.70 0.80
  10. 1978 A 0.20 0.06
  11. B 0.70 0.20
  12. C 0.80 0.30
  13. D 0.90 0.50
  14. E 1.40 0.90
  15. 1979 C 0.20 0.15
  16. D 0.14 0.05
  17. E 0.50 0.15
  18. F 1.20 0.50
  19. G 3.40 1.90
  20. H 5.40 2.70
  21. I 6.40 1.20
  22.  
  23. In [174]: df.loc[1978]
  24. Out[174]:
  25. zit xit
  26. indiv
  27. A 0.2 0.06
  28. B 0.7 0.20
  29. C 0.8 0.30
  30. D 0.9 0.50
  31. E 1.4 0.90

Reading columns with a MultiIndex

By specifying list of row locations for the header argument, youcan read in a MultiIndex for the columns. Specifying non-consecutiverows will skip the intervening rows.

  1. In [175]: from pandas.util.testing import makeCustomDataframe as mkdf
  2.  
  3. In [176]: df = mkdf(5, 3, r_idx_nlevels=2, c_idx_nlevels=4)
  4.  
  5. In [177]: df.to_csv('mi.csv')
  6.  
  7. In [178]: print(open('mi.csv').read())
  8. C0,,C_l0_g0,C_l0_g1,C_l0_g2
  9. C1,,C_l1_g0,C_l1_g1,C_l1_g2
  10. C2,,C_l2_g0,C_l2_g1,C_l2_g2
  11. C3,,C_l3_g0,C_l3_g1,C_l3_g2
  12. R0,R1,,,
  13. R_l0_g0,R_l1_g0,R0C0,R0C1,R0C2
  14. R_l0_g1,R_l1_g1,R1C0,R1C1,R1C2
  15. R_l0_g2,R_l1_g2,R2C0,R2C1,R2C2
  16. R_l0_g3,R_l1_g3,R3C0,R3C1,R3C2
  17. R_l0_g4,R_l1_g4,R4C0,R4C1,R4C2
  18.  
  19.  
  20. In [179]: pd.read_csv('mi.csv', header=[0, 1, 2, 3], index_col=[0, 1])
  21. Out[179]:
  22. C0 C_l0_g0 C_l0_g1 C_l0_g2
  23. C1 C_l1_g0 C_l1_g1 C_l1_g2
  24. C2 C_l2_g0 C_l2_g1 C_l2_g2
  25. C3 C_l3_g0 C_l3_g1 C_l3_g2
  26. R0 R1
  27. R_l0_g0 R_l1_g0 R0C0 R0C1 R0C2
  28. R_l0_g1 R_l1_g1 R1C0 R1C1 R1C2
  29. R_l0_g2 R_l1_g2 R2C0 R2C1 R2C2
  30. R_l0_g3 R_l1_g3 R3C0 R3C1 R3C2
  31. R_l0_g4 R_l1_g4 R4C0 R4C1 R4C2

read_csv is also able to interpret a more common formatof multi-columns indices.

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

Note: If an indexcol is not specified (e.g. you don’t have an index, or wrote itwith df.to_csv(…, index=False), then any names on the columns index will be _lost.

Automatically “sniffing” the delimiter

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

  1. In [182]: print(open('tmp2.sv').read())
  2. :0:1:2:3
  3. 0:0.4691122999071863:-0.2828633443286633:-1.5090585031735124:-1.1356323710171934
  4. 1:1.2121120250208506:-0.17321464905330858:0.11920871129693428:-1.0442359662799567
  5. 2:-0.8618489633477999:-2.1045692188948086:-0.4949292740687813:1.071803807037338
  6. 3:0.7215551622443669:-0.7067711336300845:-1.0395749851146963:0.27185988554282986
  7. 4:-0.42497232978883753:0.567020349793672:0.27623201927771873:-1.0874006912859915
  8. 5:-0.6736897080883706:0.1136484096888855:-1.4784265524372235:0.5249876671147047
  9. 6:0.4047052186802365:0.5770459859204836:-1.7150020161146375:-1.0392684835147725
  10. 7:-0.3706468582364464:-1.1578922506419993:-1.344311812731667:0.8448851414248841
  11. 8:1.0757697837155533:-0.10904997528022223:1.6435630703622064:-1.4693879595399115
  12. 9:0.35702056413309086:-0.6746001037299882:-1.776903716971867:-0.9689138124473498
  13.  
  14.  
  15. In [183]: pd.read_csv('tmp2.sv', sep=None, engine='python')
  16. Out[183]:
  17. Unnamed: 0 0 1 2 3
  18. 0 0 0.469112 -0.282863 -1.509059 -1.135632
  19. 1 1 1.212112 -0.173215 0.119209 -1.044236
  20. 2 2 -0.861849 -2.104569 -0.494929 1.071804
  21. 3 3 0.721555 -0.706771 -1.039575 0.271860
  22. 4 4 -0.424972 0.567020 0.276232 -1.087401
  23. 5 5 -0.673690 0.113648 -1.478427 0.524988
  24. 6 6 0.404705 0.577046 -1.715002 -1.039268
  25. 7 7 -0.370647 -1.157892 -1.344312 0.844885
  26. 8 8 1.075770 -0.109050 1.643563 -1.469388
  27. 9 9 0.357021 -0.674600 -1.776904 -0.968914

Reading multiple files to create a single DataFrame

It’s best to use concat() to combine multiple files.See the cookbook for an example.

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:

  1. In [184]: print(open('tmp.sv').read())
  2. |0|1|2|3
  3. 0|0.4691122999071863|-0.2828633443286633|-1.5090585031735124|-1.1356323710171934
  4. 1|1.2121120250208506|-0.17321464905330858|0.11920871129693428|-1.0442359662799567
  5. 2|-0.8618489633477999|-2.1045692188948086|-0.4949292740687813|1.071803807037338
  6. 3|0.7215551622443669|-0.7067711336300845|-1.0395749851146963|0.27185988554282986
  7. 4|-0.42497232978883753|0.567020349793672|0.27623201927771873|-1.0874006912859915
  8. 5|-0.6736897080883706|0.1136484096888855|-1.4784265524372235|0.5249876671147047
  9. 6|0.4047052186802365|0.5770459859204836|-1.7150020161146375|-1.0392684835147725
  10. 7|-0.3706468582364464|-1.1578922506419993|-1.344311812731667|0.8448851414248841
  11. 8|1.0757697837155533|-0.10904997528022223|1.6435630703622064|-1.4693879595399115
  12. 9|0.35702056413309086|-0.6746001037299882|-1.776903716971867|-0.9689138124473498
  13.  
  14.  
  15. In [185]: table = pd.read_csv('tmp.sv', sep='|')
  16.  
  17. In [186]: table
  18. Out[186]:
  19. Unnamed: 0 0 1 2 3
  20. 0 0 0.469112 -0.282863 -1.509059 -1.135632
  21. 1 1 1.212112 -0.173215 0.119209 -1.044236
  22. 2 2 -0.861849 -2.104569 -0.494929 1.071804
  23. 3 3 0.721555 -0.706771 -1.039575 0.271860
  24. 4 4 -0.424972 0.567020 0.276232 -1.087401
  25. 5 5 -0.673690 0.113648 -1.478427 0.524988
  26. 6 6 0.404705 0.577046 -1.715002 -1.039268
  27. 7 7 -0.370647 -1.157892 -1.344312 0.844885
  28. 8 8 1.075770 -0.109050 1.643563 -1.469388
  29. 9 9 0.357021 -0.674600 -1.776904 -0.968914

By specifying a chunksize to read_csv, the returnvalue will be an iterable object of type TextFileReader:

  1. In [187]: reader = pd.read_csv('tmp.sv', sep='|', chunksize=4)
  2.  
  3. In [188]: reader
  4. Out[188]: <pandas.io.parsers.TextFileReader at 0x7f452823aa50>
  5.  
  6. In [189]: for chunk in reader:
  7. .....: print(chunk)
  8. .....:
  9. Unnamed: 0 0 1 2 3
  10. 0 0 0.469112 -0.282863 -1.509059 -1.135632
  11. 1 1 1.212112 -0.173215 0.119209 -1.044236
  12. 2 2 -0.861849 -2.104569 -0.494929 1.071804
  13. 3 3 0.721555 -0.706771 -1.039575 0.271860
  14. Unnamed: 0 0 1 2 3
  15. 4 4 -0.424972 0.567020 0.276232 -1.087401
  16. 5 5 -0.673690 0.113648 -1.478427 0.524988
  17. 6 6 0.404705 0.577046 -1.715002 -1.039268
  18. 7 7 -0.370647 -1.157892 -1.344312 0.844885
  19. Unnamed: 0 0 1 2 3
  20. 8 8 1.075770 -0.10905 1.643563 -1.469388
  21. 9 9 0.357021 -0.67460 -1.776904 -0.968914

Specifying iterator=True will also return the TextFileReader object:

  1. In [190]: reader = pd.read_csv('tmp.sv', sep='|', iterator=True)
  2.  
  3. In [191]: reader.get_chunk(5)
  4. Out[191]:
  5. Unnamed: 0 0 1 2 3
  6. 0 0 0.469112 -0.282863 -1.509059 -1.135632
  7. 1 1 1.212112 -0.173215 0.119209 -1.044236
  8. 2 2 -0.861849 -2.104569 -0.494929 1.071804
  9. 3 3 0.721555 -0.706771 -1.039575 0.271860
  10. 4 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 as engine='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 with delim_whitespace=False

Specifying any of the above options will produce a ParserWarning unless thepython engine is selected explicitly using engine='python'.

Reading remote files

You can pass in a URL to a CSV file:

  1. df = pd.read_csv('https://download.bls.gov/pub/time.series/cu/cu.item',
  2. sep='\t')

S3 URLs are handled as well but require installing the S3Fs library:

  1. df = pd.read_csv('s3://pandas-test/tips.csv')

If your S3 bucket requires credentials you will need to set them as environmentvariables or in the ~/.aws/credentials config file, refer to the S3Fsdocumentation on credentials.

Writing out data

Writing to CSV format

The Series and DataFrame objects have an instance method to_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.

  • pathor_buf: A string path to the file to write or a file object. If a file object it must be opened with _newline=’’
  • 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
  • columns: Columns to write (default None)
  • header: Whether to write out the column names (default True)
  • index: whether to write row (index) names (default True)
  • indexlabel: Column label(s) for index column(s) if desired. If None(default), and _header and index 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
  • lineterminator: Character sequence denoting line end (default _os.linesep)
  • quoting: Set quoting rules as in csv module (default csv.QUOTEMINIMAL). Note that if you have set a _float_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 of quotechar in fields (default True)
  • escapechar: Character used to escape sep and quotechar whenappropriate (default None)
  • chunksize: Number of rows to write at a time
  • date_format: Format string for datetime objects

Writing a formatted string

The DataFrame object has an instance method to_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 default NaN, 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 default left, will print column headers left- orright-justified

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

JSON

Read and write JSON format files and strings.

Writing JSON

A Series or DataFrame can be converted to a valid JSON string. Use to_jsonwith optional parameters:

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

  • orient :

    • Series:
      • default is index
      • allowed values are {split, records, index}
    • DataFrame:
      • default is columns
      • allowed values are {split, records, index, columns, values, table}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 : If records orient, then will write each record per line as json.

Note NaN’s, NaT’s and None will be converted to null and datetime objects will be converted based on the date_format and date_unit parameters.

  1. In [192]: dfj = pd.DataFrame(np.random.randn(5, 2), columns=list('AB'))
  2.  
  3. In [193]: json = dfj.to_json()
  4.  
  5. In [194]: json
  6. Out[194]: '{"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:

  1. In [195]: dfjo = pd.DataFrame(dict(A=range(1, 4), B=range(4, 7), C=range(7, 10)),
  2. .....: columns=list('ABC'), index=list('xyz'))
  3. .....:
  4.  
  5. In [196]: dfjo
  6. Out[196]:
  7. A B C
  8. x 1 4 7
  9. y 2 5 8
  10. z 3 6 9
  11.  
  12. In [197]: sjo = pd.Series(dict(x=15, y=16, z=17), name='D')
  13.  
  14. In [198]: sjo
  15. Out[198]:
  16. x 15
  17. y 16
  18. z 17
  19. Name: D, dtype: int64

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

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

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

  1. In [200]: dfjo.to_json(orient="index")
  2. Out[200]: '{"x":{"A":1,"B":4,"C":7},"y":{"A":2,"B":5,"C":8},"z":{"A":3,"B":6,"C":9}}'
  3.  
  4. In [201]: sjo.to_json(orient="index")
  5. Out[201]: '{"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:

  1. In [202]: dfjo.to_json(orient="records")
  2. Out[202]: '[{"A":1,"B":4,"C":7},{"A":2,"B":5,"C":8},{"A":3,"B":6,"C":9}]'
  3.  
  4. In [203]: sjo.to_json(orient="records")
  5. Out[203]: '[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:

  1. In [204]: dfjo.to_json(orient="values")
  2. Out[204]: '[[1,4,7],[2,5,8],[3,6,9]]'
  3.  
  4. # Not available for Series

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

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

Table oriented serializes to the JSON Table Schema, allowing for thepreservation of metadata including but not limited to dtypes and index names.

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 the split option as it uses ordered containers.

Date handling

Writing in ISO date format:

  1. In [207]: dfd = pd.DataFrame(np.random.randn(5, 2), columns=list('AB'))
  2.  
  3. In [208]: dfd['date'] = pd.Timestamp('20130101')
  4.  
  5. In [209]: dfd = dfd.sort_index(1, ascending=False)
  6.  
  7. In [210]: json = dfd.to_json(date_format='iso')
  8.  
  9. In [211]: json
  10. Out[211]: '{"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:

  1. In [212]: json = dfd.to_json(date_format='iso', date_unit='us')
  2.  
  3. In [213]: json
  4. Out[213]: '{"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:

  1. In [214]: json = dfd.to_json(date_format='epoch', date_unit='s')
  2.  
  3. In [215]: json
  4. Out[215]: '{"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:

  1. In [216]: dfj2 = dfj.copy()
  2.  
  3. In [217]: dfj2['date'] = pd.Timestamp('20130101')
  4.  
  5. In [218]: dfj2['ints'] = list(range(5))
  6.  
  7. In [219]: dfj2['bools'] = True
  8.  
  9. In [220]: dfj2.index = pd.date_range('20130101', periods=5)
  10.  
  11. In [221]: dfj2.to_json('test.json')
  12.  
  13. In [222]: with open('test.json') as fh:
  14. .....: print(fh.read())
  15. .....:
  16. {"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 willfall back in the following manner:

  • if the dtype is unsupported (e.g. np.complex) then the default_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 a toDict method and call it.A toDict method should return a dict which will then be JSON serialized.
  • invoke the default_handler if one was provided.
  • convert the object to a dict by traversing its contents. However this will often failwith an OverflowError or give unexpected results.

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

  1. >>> DataFrame([1.0, 2.0, complex(1.0, 2.0)]).to_json() # raises
  2. RuntimeError: Unhandled numpy dtype 15

can be dealt with by specifying a simple default_handler:

  1. In [223]: pd.DataFrame([1.0, 2.0, complex(1.0, 2.0)]).to_json(default_handler=str)
  2. Out[223]: '{"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 a DataFrame if typ is not supplied oris None. To explicitly force Series parsing, pass typ=series

  • filepath_or_buffer : a VALID 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 is index
      • allowed values are {split, records, index}
    • DataFrame
      • default is columns
      • allowed values are {split, records, index, columns, values, table}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 arraytableadhering to the JSON Table Schema

  • 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 ordering MUST be the same for each term if numpy=True.

  • precise_float : boolean, default False. Set to enable usage of higher precision (strtod) function when decoding string to double values. Default (False) is to use fast but less precise builtin functionality.

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

  • chunksize : when used in combination with lines=True, return a JsonReader which reads in chunksize lines per iteration.

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

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

Data conversion

The default of convert_axes=True, dtype=True, and convert_dates=Truewill try to parse the axes, and all of the data into appropriate types,including dates. If you need to override specific dtypes, pass a dict todtype. convert_axes should only be set to False if you need topreserve string-like numbers (e.g. ‘1’, ‘2’) in an axes.

Note

Large integer values may be converted to dates if convert_dates=True and the data and / or column labels appear ‘date-like’. The exact threshold depends on the date_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 was float data will be converted to integer if it can be done safely, e.g. a column of 1.
  • bool columns will be converted to integer on reconstruction

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

Reading from a JSON string:

  1. In [224]: pd.read_json(json)
  2. Out[224]:
  3. date B A
  4. 0 2013-01-01 2.565646 -1.206412
  5. 1 2013-01-01 1.340309 1.431256
  6. 2 2013-01-01 -0.226169 -1.170299
  7. 3 2013-01-01 0.813850 0.410835
  8. 4 2013-01-01 -0.827317 0.132003

Reading from a file:

  1. In [225]: pd.read_json('test.json')
  2. Out[225]:
  3. A B date ints bools
  4. 2013-01-01 -1.294524 0.413738 2013-01-01 0 True
  5. 2013-01-02 0.276662 -0.472035 2013-01-01 1 True
  6. 2013-01-03 -0.013960 -0.362543 2013-01-01 2 True
  7. 2013-01-04 -0.006154 -0.923061 2013-01-01 3 True
  8. 2013-01-05 0.895717 0.805244 2013-01-01 4 True

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

  1. In [226]: pd.read_json('test.json', dtype=object).dtypes
  2. Out[226]:
  3. A object
  4. B object
  5. date object
  6. ints object
  7. bools object
  8. dtype: object

Specify dtypes for conversion:

  1. In [227]: pd.read_json('test.json', dtype={'A': 'float32', 'bools': 'int8'}).dtypes
  2. Out[227]:
  3. A float32
  4. B float64
  5. date datetime64[ns]
  6. ints int64
  7. bools int8
  8. dtype: object

Preserve string indices:

  1. In [228]: si = pd.DataFrame(np.zeros((4, 4)), columns=list(range(4)),
  2. .....: index=[str(i) for i in range(4)])
  3. .....:
  4.  
  5. In [229]: si
  6. Out[229]:
  7. 0 1 2 3
  8. 0 0.0 0.0 0.0 0.0
  9. 1 0.0 0.0 0.0 0.0
  10. 2 0.0 0.0 0.0 0.0
  11. 3 0.0 0.0 0.0 0.0
  12.  
  13. In [230]: si.index
  14. Out[230]: Index(['0', '1', '2', '3'], dtype='object')
  15.  
  16. In [231]: si.columns
  17. Out[231]: Int64Index([0, 1, 2, 3], dtype='int64')
  18.  
  19. In [232]: json = si.to_json()
  20.  
  21. In [233]: sij = pd.read_json(json, convert_axes=False)
  22.  
  23. In [234]: sij
  24. Out[234]:
  25. 0 1 2 3
  26. 0 0 0 0 0
  27. 1 0 0 0 0
  28. 2 0 0 0 0
  29. 3 0 0 0 0
  30.  
  31. In [235]: sij.index
  32. Out[235]: Index(['0', '1', '2', '3'], dtype='object')
  33.  
  34. In [236]: sij.columns
  35. Out[236]: Index(['0', '1', '2', '3'], dtype='object')

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

  1. In [237]: json = dfj2.to_json(date_unit='ns')
  2.  
  3. # Try to parse timestamps as milliseconds -> Won't Work
  4. In [238]: dfju = pd.read_json(json, date_unit='ms')
  5.  
  6. In [239]: dfju
  7. Out[239]:
  8. A B date ints bools
  9. 1356998400000000000 -1.294524 0.413738 1356998400000000000 0 True
  10. 1357084800000000000 0.276662 -0.472035 1356998400000000000 1 True
  11. 1357171200000000000 -0.013960 -0.362543 1356998400000000000 2 True
  12. 1357257600000000000 -0.006154 -0.923061 1356998400000000000 3 True
  13. 1357344000000000000 0.895717 0.805244 1356998400000000000 4 True
  14.  
  15. # Let pandas detect the correct precision
  16. In [240]: dfju = pd.read_json(json)
  17.  
  18. In [241]: dfju
  19. Out[241]:
  20. A B date ints bools
  21. 2013-01-01 -1.294524 0.413738 2013-01-01 0 True
  22. 2013-01-02 0.276662 -0.472035 2013-01-01 1 True
  23. 2013-01-03 -0.013960 -0.362543 2013-01-01 2 True
  24. 2013-01-04 -0.006154 -0.923061 2013-01-01 3 True
  25. 2013-01-05 0.895717 0.805244 2013-01-01 4 True
  26.  
  27. # Or specify that all timestamps are in nanoseconds
  28. In [242]: dfju = pd.read_json(json, date_unit='ns')
  29.  
  30. In [243]: dfju
  31. Out[243]:
  32. A B date ints bools
  33. 2013-01-01 -1.294524 0.413738 2013-01-01 0 True
  34. 2013-01-02 0.276662 -0.472035 2013-01-01 1 True
  35. 2013-01-03 -0.013960 -0.362543 2013-01-01 2 True
  36. 2013-01-04 -0.006154 -0.923061 2013-01-01 3 True
  37. 2013-01-05 0.895717 0.805244 2013-01-01 4 True

The Numpy parameter

Note

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

If numpy=True is passed to read_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:

  1. In [244]: randfloats = np.random.uniform(-100, 1000, 10000)
  2.  
  3. In [245]: randfloats.shape = (1000, 10)
  4.  
  5. In [246]: dffloats = pd.DataFrame(randfloats, columns=list('ABCDEFGHIJ'))
  6.  
  7. In [247]: jsonfloats = dffloats.to_json()
  1. In [248]: %timeit pd.read_json(jsonfloats)
  2. 13.7 ms +- 656 us per loop (mean +- std. dev. of 7 runs, 100 loops each)
  1. In [249]: %timeit pd.read_json(jsonfloats, numpy=True)
  2. 10.3 ms +- 687 us per loop (mean +- std. dev. of 7 runs, 100 loops each)

The speedup is less noticeable for smaller datasets:

  1. In [250]: jsonfloats = dffloats.head(100).to_json()
  1. In [251]: %timeit pd.read_json(jsonfloats)
  2. 8.29 ms +- 470 us per loop (mean +- std. dev. of 7 runs, 100 loops each)
  1. In [252]: %timeit pd.read_json(jsonfloats, numpy=True)
  2. 7.07 ms +- 298 us per loop (mean +- std. dev. of 7 runs, 100 loops each)

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.A ValueError 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 using to_json but may not be the case if the JSONis from another source.

Normalization

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

  1. In [253]: from pandas.io.json import json_normalize
  2.  
  3. In [254]: data = [{'id': 1, 'name': {'first': 'Coleen', 'last': 'Volk'}},
  4. .....: {'name': {'given': 'Mose', 'family': 'Regner'}},
  5. .....: {'id': 2, 'name': 'Faye Raker'}]
  6. .....:
  7.  
  8. In [255]: json_normalize(data)
  9. Out[255]:
  10. id name.first name.last name.given name.family name
  11. 0 1.0 Coleen Volk NaN NaN NaN
  12. 1 NaN NaN NaN Mose Regner NaN
  13. 2 2.0 NaN NaN NaN NaN Faye Raker
  1. In [256]: data = [{'state': 'Florida',
  2. .....: 'shortname': 'FL',
  3. .....: 'info': {'governor': 'Rick Scott'},
  4. .....: 'counties': [{'name': 'Dade', 'population': 12345},
  5. .....: {'name': 'Broward', 'population': 40000},
  6. .....: {'name': 'Palm Beach', 'population': 60000}]},
  7. .....: {'state': 'Ohio',
  8. .....: 'shortname': 'OH',
  9. .....: 'info': {'governor': 'John Kasich'},
  10. .....: 'counties': [{'name': 'Summit', 'population': 1234},
  11. .....: {'name': 'Cuyahoga', 'population': 1337}]}]
  12. .....:
  13.  
  14. In [257]: json_normalize(data, 'counties', ['state', 'shortname', ['info', 'governor']])
  15. Out[257]:
  16. name population state shortname info.governor
  17. 0 Dade 12345 Florida FL Rick Scott
  18. 1 Broward 40000 Florida FL Rick Scott
  19. 2 Palm Beach 60000 Florida FL Rick Scott
  20. 3 Summit 1234 Ohio OH John Kasich
  21. 4 Cuyahoga 1337 Ohio OH John Kasich

The max_level parameter provides more control over which level to end normalization.With max_level=1 the following snippet normalizes until 1st nesting level of the provided dict.

  1. In [258]: data = [{'CreatedBy': {'Name': 'User001'},
  2. .....: 'Lookup': {'TextField': 'Some text',
  3. .....: 'UserField': {'Id': 'ID001',
  4. .....: 'Name': 'Name001'}},
  5. .....: 'Image': {'a': 'b'}
  6. .....: }]
  7. .....:
  8.  
  9. In [259]: json_normalize(data, max_level=1)
  10. Out[259]:
  11. CreatedBy.Name Lookup.TextField Lookup.UserField Image.a
  12. 0 User001 Some text {'Id': 'ID001', 'Name': 'Name001'} b

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.

New in version 0.21.0.

For line-delimited json files, pandas can also return an iterator which reads in chunksize lines at a time. This can be useful for large files or to read from a stream.

  1. In [260]: jsonl = '''
  2. .....: {"a": 1, "b": 2}
  3. .....: {"a": 3, "b": 4}
  4. .....: '''
  5. .....:
  6.  
  7. In [261]: df = pd.read_json(jsonl, lines=True)
  8.  
  9. In [262]: df
  10. Out[262]:
  11. a b
  12. 0 1 2
  13. 1 3 4
  14.  
  15. In [263]: df.to_json(orient='records', lines=True)
  16. Out[263]: '{"a":1,"b":2}\n{"a":3,"b":4}'
  17.  
  18. # reader is an iterator that returns `chunksize` lines each iteration
  19. In [264]: reader = pd.read_json(StringIO(jsonl), lines=True, chunksize=1)
  20.  
  21. In [265]: reader
  22. Out[265]: <pandas.io.json._json.JsonReader at 0x7f4528782650>
  23.  
  24. In [266]: for chunk in reader:
  25. .....: print(chunk)
  26. .....:
  27. Empty DataFrame
  28. Columns: []
  29. Index: []
  30. a b
  31. 0 1 2
  32. a b
  33. 1 3 4

Table schema

New in version 0.20.0.

Table Schema is a spec for describing tabular datasets as a JSONobject. The JSON includes information on the field names, types, andother attributes. You can use the orient table to builda JSON string with two fields, schema and data.

  1. In [267]: df = pd.DataFrame({'A': [1, 2, 3],
  2. .....: 'B': ['a', 'b', 'c'],
  3. .....: 'C': pd.date_range('2016-01-01', freq='d', periods=3)},
  4. .....: index=pd.Index(range(3), name='idx'))
  5. .....:
  6.  
  7. In [268]: df
  8. Out[268]:
  9. A B C
  10. idx
  11. 0 1 a 2016-01-01
  12. 1 2 b 2016-01-02
  13. 2 3 c 2016-01-03
  14.  
  15. In [269]: df.to_json(orient='table', date_format="iso")
  16. Out[269]: '{"schema": {"fields":[{"name":"idx","type":"integer"},{"name":"A","type":"integer"},{"name":"B","type":"string"},{"name":"C","type":"datetime"}],"primaryKey":["idx"],"pandas_version":"0.20.0"}, "data": [{"idx":0,"A":1,"B":"a","C":"2016-01-01T00:00:00.000Z"},{"idx":1,"A":2,"B":"b","C":"2016-01-02T00:00:00.000Z"},{"idx":2,"A":3,"B":"c","C":"2016-01-03T00:00:00.000Z"}]}'

The schema field contains the fields key, which itself containsa list of column name to type pairs, including the Index or MultiIndex(see below for a list of types).The schema field also contains a primaryKey field if the (Multi)indexis unique.

The second field, data, contains the serialized data with the recordsorient.The index is included, and any datetimes are ISO 8601 formatted, as requiredby the Table Schema spec.

The full list of types supported are described in the Table Schemaspec. This table shows the mapping from pandas types:

Pandas typeTable Schema type
int64integer
float64number
boolboolean
datetime64[ns]datetime
timedelta64[ns]duration
categoricalany
objectstr

A few notes on the generated table schema:

  • The schema object contains a pandas_version field. This containsthe version of pandas’ dialect of the schema, and will be incrementedwith each revision.

  • All dates are converted to UTC when serializing. Even timezone naive values,which are treated as UTC with an offset of 0.

  1. In [270]: from pandas.io.json import build_table_schema
  2.  
  3. In [271]: s = pd.Series(pd.date_range('2016', periods=4))
  4.  
  5. In [272]: build_table_schema(s)
  6. Out[272]:
  7. {'fields': [{'name': 'index', 'type': 'integer'},
  8. {'name': 'values', 'type': 'datetime'}],
  9. 'primaryKey': ['index'],
  10. 'pandas_version': '0.20.0'}
  • datetimes with a timezone (before serializing), include an additional fieldtz with the time zone name (e.g. 'US/Central').
  1. In [273]: s_tz = pd.Series(pd.date_range('2016', periods=12,
  2. .....: tz='US/Central'))
  3. .....:
  4.  
  5. In [274]: build_table_schema(s_tz)
  6. Out[274]:
  7. {'fields': [{'name': 'index', 'type': 'integer'},
  8. {'name': 'values', 'type': 'datetime', 'tz': 'US/Central'}],
  9. 'primaryKey': ['index'],
  10. 'pandas_version': '0.20.0'}
  • Periods are converted to timestamps before serialization, and so have thesame behavior of being converted to UTC. In addition, periods will containand additional field freq with the period’s frequency, e.g. 'A-DEC'.
  1. In [275]: s_per = pd.Series(1, index=pd.period_range('2016', freq='A-DEC',
  2. .....: periods=4))
  3. .....:
  4.  
  5. In [276]: build_table_schema(s_per)
  6. Out[276]:
  7. {'fields': [{'name': 'index', 'type': 'datetime', 'freq': 'A-DEC'},
  8. {'name': 'values', 'type': 'integer'}],
  9. 'primaryKey': ['index'],
  10. 'pandas_version': '0.20.0'}
  • Categoricals use the any type and an enum constraint listingthe set of possible values. Additionally, an ordered field is included:
  1. In [277]: s_cat = pd.Series(pd.Categorical(['a', 'b', 'a']))
  2.  
  3. In [278]: build_table_schema(s_cat)
  4. Out[278]:
  5. {'fields': [{'name': 'index', 'type': 'integer'},
  6. {'name': 'values',
  7. 'type': 'any',
  8. 'constraints': {'enum': ['a', 'b']},
  9. 'ordered': False}],
  10. 'primaryKey': ['index'],
  11. 'pandas_version': '0.20.0'}
  • A primaryKey field, containing an array of labels, is includedif the index is unique:
  1. In [279]: s_dupe = pd.Series([1, 2], index=[1, 1])
  2.  
  3. In [280]: build_table_schema(s_dupe)
  4. Out[280]:
  5. {'fields': [{'name': 'index', 'type': 'integer'},
  6. {'name': 'values', 'type': 'integer'}],
  7. 'pandas_version': '0.20.0'}
  • The primaryKey behavior is the same with MultiIndexes, but in thiscase the primaryKey is an array:
  1. In [281]: s_multi = pd.Series(1, index=pd.MultiIndex.from_product([('a', 'b'),
  2. .....: (0, 1)]))
  3. .....:
  4.  
  5. In [282]: build_table_schema(s_multi)
  6. Out[282]:
  7. {'fields': [{'name': 'level_0', 'type': 'string'},
  8. {'name': 'level_1', 'type': 'integer'},
  9. {'name': 'values', 'type': 'integer'}],
  10. 'primaryKey': FrozenList(['level_0', 'level_1']),
  11. 'pandas_version': '0.20.0'}
  • The default naming roughly follows these rules:
  • For series, the object.name is used. If that’s none, then thename is values
  • For DataFrames, the stringified version of the column name is used
  • For Index (not MultiIndex), index.name is used, with afallback to index if that is None.
  • For MultiIndex, mi.names is used. If any level has no name,then level_<i> is used.

New in version 0.23.0.

read_json also accepts orient='table' as an argument. This allows forthe preservation of metadata such as dtypes and index names in around-trippable manner.

  1. In [283]: df = pd.DataFrame({'foo': [1, 2, 3, 4], …..: 'bar': ['a', 'b', 'c', 'd'], …..: 'baz': pd.date_range('2018-01-01', freq='d', periods=4), …..: 'qux': pd.Categorical(['a', 'b', 'c', 'c']) …..: }, index=pd.Index(range(4), name='idx')) …..:In [284]: dfOut[284]: foo bar baz quxidx0 1 a 2018-01-01 a1 2 b 2018-01-02 b2 3 c 2018-01-03 c3 4 d 2018-01-04 cIn [285]: df.dtypesOut[285]:foo int64bar objectbaz datetime64[ns]qux categorydtype: objectIn [286]: df.to_json('test.json', orient='table')In [287]: new_df = pd.read_json('test.json', orient='table')In [288]: new_dfOut[288]: foo bar baz quxidx0 1 a 2018-01-01 a1 2 b 2018-01-02 b2 3 c 2018-01-03 c3 4 d 2018-01-04 cIn [289]: new_df.dtypesOut[289]:foo int64bar objectbaz datetime64[ns]qux categorydtype: object

Please note that the literal string ‘index’ as the name of an Indexis not round-trippable, nor are any names beginning with 'level_' within aMultiIndex. These are used by default in DataFrame.to_json() toindicate missing values and the subsequent read cannot distinguish the intent.

  1. In [290]: df.index.name = 'index'
  2.  
  3. In [291]: df.to_json('test.json', orient='table')
  4.  
  5. In [292]: new_df = pd.read_json('test.json', orient='table')
  6.  
  7. In [293]: print(new_df.index.name)
  8. None

HTML

Reading HTML content

Warning

We highly encourage you to read the HTML Table Parsing gotchasbelow regarding the issues surrounding the BeautifulSoup4/html5lib/lxml parsers.

The top-level read_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 a list of DataFrame objects, even if there isonly a single table contained in the HTML content.

Read a URL with no options:

  1. In [294]: url = 'https://www.fdic.gov/bank/individual/failed/banklist.html'
  2.  
  3. In [295]: dfs = pd.read_html(url)
  4.  
  5. In [296]: dfs
  6. Out[296]:
  7. [ Bank Name City ST CERT Acquiring Institution Closing Date Updated Date
  8. 0 City National Bank of New Jersey Newark NJ 21111 Industrial Bank November 1, 2019 November 7, 2019
  9. 1 Resolute Bank Maumee OH 58317 Buckeye State Bank October 25, 2019 November 7, 2019
  10. 2 Louisa Community Bank Louisa KY 58112 Kentucky Farmers Bank Corporation October 25, 2019 November 7, 2019
  11. 3 The Enloe State Bank Cooper TX 10716 Legend Bank, N. A. May 31, 2019 August 22, 2019
  12. 4 Washington Federal Bank for Savings Chicago IL 30570 Royal Savings Bank December 15, 2017 July 24, 2019
  13. .. ... ... .. ... ... ... ...
  14. 554 Superior Bank, FSB Hinsdale IL 32646 Superior Federal, FSB July 27, 2001 August 19, 2014
  15. 555 Malta National Bank Malta OH 6629 North Valley Bank May 3, 2001 November 18, 2002
  16. 556 First Alliance Bank & Trust Co. Manchester NH 34264 Southern New Hampshire Bank & Trust February 2, 2001 February 18, 2003
  17. 557 National State Bank of Metropolis Metropolis IL 3815 Banterra Bank of Marion December 14, 2000 March 17, 2005
  18. 558 Bank of Honolulu Honolulu HI 21029 Bank of the Orient October 13, 2000 March 17, 2005
  19.  
  20. [559 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 to read_htmlas a string:

  1. In [297]: with open(file_path, 'r') as f:
  2. .....: dfs = pd.read_html(f.read())
  3. .....:
  4.  
  5. In [298]: dfs
  6. Out[298]:
  7. [ Bank Name City ST CERT Acquiring Institution Closing Date Updated Date
  8. 0 Banks of Wisconsin d/b/a Bank of Kenosha Kenosha WI 35386 North Shore Bank, FSB May 31, 2013 May 31, 2013
  9. 1 Central Arizona Bank Scottsdale AZ 34527 Western State Bank May 14, 2013 May 20, 2013
  10. 2 Sunrise Bank Valdosta GA 58185 Synovus Bank May 10, 2013 May 21, 2013
  11. 3 Pisgah Community Bank Asheville NC 58701 Capital Bank, N.A. May 10, 2013 May 14, 2013
  12. 4 Douglas County Bank Douglasville GA 21649 Hamilton State Bank April 26, 2013 May 16, 2013
  13. .. ... ... .. ... ... ... ...
  14. 500 Superior Bank, FSB Hinsdale IL 32646 Superior Federal, FSB July 27, 2001 June 5, 2012
  15. 501 Malta National Bank Malta OH 6629 North Valley Bank May 3, 2001 November 18, 2002
  16. 502 First Alliance Bank & Trust Co. Manchester NH 34264 Southern New Hampshire Bank & Trust February 2, 2001 February 18, 2003
  17. 503 National State Bank of Metropolis Metropolis IL 3815 Banterra Bank of Marion December 14, 2000 March 17, 2005
  18. 504 Bank of Honolulu Honolulu HI 21029 Bank of the Orient October 13, 2000 March 17, 2005
  19.  
  20. [505 rows x 7 columns]]

You can even pass in an instance of StringIO if you so desire:

  1. In [299]: with open(file_path, 'r') as f:
  2. .....: sio = StringIO(f.read())
  3. .....:
  4.  
  5. In [300]: dfs = pd.read_html(sio)
  6.  
  7. In [301]: dfs
  8. Out[301]:
  9. [ Bank Name City ST CERT Acquiring Institution Closing Date Updated Date
  10. 0 Banks of Wisconsin d/b/a Bank of Kenosha Kenosha WI 35386 North Shore Bank, FSB May 31, 2013 May 31, 2013
  11. 1 Central Arizona Bank Scottsdale AZ 34527 Western State Bank May 14, 2013 May 20, 2013
  12. 2 Sunrise Bank Valdosta GA 58185 Synovus Bank May 10, 2013 May 21, 2013
  13. 3 Pisgah Community Bank Asheville NC 58701 Capital Bank, N.A. May 10, 2013 May 14, 2013
  14. 4 Douglas County Bank Douglasville GA 21649 Hamilton State Bank April 26, 2013 May 16, 2013
  15. .. ... ... .. ... ... ... ...
  16. 500 Superior Bank, FSB Hinsdale IL 32646 Superior Federal, FSB July 27, 2001 June 5, 2012
  17. 501 Malta National Bank Malta OH 6629 North Valley Bank May 3, 2001 November 18, 2002
  18. 502 First Alliance Bank & Trust Co. Manchester NH 34264 Southern New Hampshire Bank & Trust February 2, 2001 February 18, 2003
  19. 503 National State Bank of Metropolis Metropolis IL 3815 Banterra Bank of Marion December 14, 2000 March 17, 2005
  20. 504 Bank of Honolulu Honolulu HI 21029 Bank of the Orient October 13, 2000 March 17, 2005
  21.  
  22. [505 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 on pandas GitHub issues page.

Read a URL and match a table that contains specific text:

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

Specify a header row (by default <th> or <td> elements located within a<thead> are used to form the column index, if multiple rows are contained within<thead> then a MultiIndex is created); if specified, the header row is takenfrom the data minus the parsed header elements (<th> elements).

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

Specify an index column:

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

Specify a number of rows to skip:

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

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

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

Specify an HTML attribute:

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

Specify values that should be converted to NaN:

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

New in version 0.19.

Specify whether to keep the default set of NaN values:

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

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

New in version 0.19.

Use some combination of the above:

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

Read in pandas to_html output (with some loss of floating point precision):

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

The lxml 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. You may use:

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

Or you could pass flavor='lxml' without a list:

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

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

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

Writing to HTML files

DataFrame objects have an instance method to_html which renders thecontents of the DataFrame as an HTML table. The function arguments are asin the method to_string described above.

Note

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

  1. In [302]: df = pd.DataFrame(np.random.randn(2, 2))
  2.  
  3. In [303]: df
  4. Out[303]:
  5. 0 1
  6. 0 -0.184744 0.496971
  7. 1 -0.856240 1.857977
  8.  
  9. In [304]: print(df.to_html()) # raw html
  10. <table border="1" class="dataframe">
  11. <thead>
  12. <tr style="text-align: right;">
  13. <th></th>
  14. <th>0</th>
  15. <th>1</th>
  16. </tr>
  17. </thead>
  18. <tbody>
  19. <tr>
  20. <th>0</th>
  21. <td>-0.184744</td>
  22. <td>0.496971</td>
  23. </tr>
  24. <tr>
  25. <th>1</th>
  26. <td>-0.856240</td>
  27. <td>1.857977</td>
  28. </tr>
  29. </tbody>
  30. </table>

HTML:

01
0-0.1847440.496971
1-0.8562401.857977

The columns argument will limit the columns shown:

  1. In [305]: print(df.to_html(columns=[0]))
  2. <table border="1" class="dataframe">
  3. <thead>
  4. <tr style="text-align: right;">
  5. <th></th>
  6. <th>0</th>
  7. </tr>
  8. </thead>
  9. <tbody>
  10. <tr>
  11. <th>0</th>
  12. <td>-0.184744</td>
  13. </tr>
  14. <tr>
  15. <th>1</th>
  16. <td>-0.856240</td>
  17. </tr>
  18. </tbody>
  19. </table>

HTML:

0
0-0.184744
1-0.856240

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

  1. In [306]: print(df.to_html(float_format='{0:.10f}'.format))
  2. <table border="1" class="dataframe">
  3. <thead>
  4. <tr style="text-align: right;">
  5. <th></th>
  6. <th>0</th>
  7. <th>1</th>
  8. </tr>
  9. </thead>
  10. <tbody>
  11. <tr>
  12. <th>0</th>
  13. <td>-0.1847438576</td>
  14. <td>0.4969711327</td>
  15. </tr>
  16. <tr>
  17. <th>1</th>
  18. <td>-0.8562396763</td>
  19. <td>1.8579766508</td>
  20. </tr>
  21. </tbody>
  22. </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:

  1. In [307]: print(df.to_html(bold_rows=False))
  2. <table border="1" class="dataframe">
  3. <thead>
  4. <tr style="text-align: right;">
  5. <th></th>
  6. <th>0</th>
  7. <th>1</th>
  8. </tr>
  9. </thead>
  10. <tbody>
  11. <tr>
  12. <td>0</td>
  13. <td>-0.184744</td>
  14. <td>0.496971</td>
  15. </tr>
  16. <tr>
  17. <td>1</td>
  18. <td>-0.856240</td>
  19. <td>1.857977</td>
  20. </tr>
  21. </tbody>
  22. </table>
01
0-0.1847440.496971
1-0.8562401.857977

The classes argument provides the ability to give the resulting HTMLtable CSS classes. Note that these classes are appended to the existing'dataframe' class.

  1. In [308]: print(df.to_html(classes=['awesome_table_class', 'even_more_awesome_class']))
  2. <table border="1" class="dataframe awesome_table_class even_more_awesome_class">
  3. <thead>
  4. <tr style="text-align: right;">
  5. <th></th>
  6. <th>0</th>
  7. <th>1</th>
  8. </tr>
  9. </thead>
  10. <tbody>
  11. <tr>
  12. <th>0</th>
  13. <td>-0.184744</td>
  14. <td>0.496971</td>
  15. </tr>
  16. <tr>
  17. <th>1</th>
  18. <td>-0.856240</td>
  19. <td>1.857977</td>
  20. </tr>
  21. </tbody>
  22. </table>

The render_links argument provides the ability to add hyperlinks to cellsthat contain URLs.

New in version 0.24.

  1. In [309]: url_df = pd.DataFrame({
  2. .....: 'name': ['Python', 'Pandas'],
  3. .....: 'url': ['https://www.python.org/', 'http://pandas.pydata.org']})
  4. .....:
  5.  
  6. In [310]: print(url_df.to_html(render_links=True))
  7. <table border="1" class="dataframe">
  8. <thead>
  9. <tr style="text-align: right;">
  10. <th></th>
  11. <th>name</th>
  12. <th>url</th>
  13. </tr>
  14. </thead>
  15. <tbody>
  16. <tr>
  17. <th>0</th>
  18. <td>Python</td>
  19. <td><a href="https://www.python.org/" target="_blank">https://www.python.org/</a></td>
  20. </tr>
  21. <tr>
  22. <th>1</th>
  23. <td>Pandas</td>
  24. <td><a href="http://pandas.pydata.org" target="_blank">http://pandas.pydata.org</a></td>
  25. </tr>
  26. </tbody>
  27. </table>

HTML:

nameurl
0Pythonhttps://www.python.org/
1Pandashttp://pandas.pydata.org

Finally, the escape 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 pass escape=False

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

Escaped:

  1. In [312]: print(df.to_html())
  2. <table border="1" class="dataframe">
  3. <thead>
  4. <tr style="text-align: right;">
  5. <th></th>
  6. <th>a</th>
  7. <th>b</th>
  8. </tr>
  9. </thead>
  10. <tbody>
  11. <tr>
  12. <th>0</th>
  13. <td>&amp;</td>
  14. <td>-0.474063</td>
  15. </tr>
  16. <tr>
  17. <th>1</th>
  18. <td>&lt;</td>
  19. <td>-0.230305</td>
  20. </tr>
  21. <tr>
  22. <th>2</th>
  23. <td>&gt;</td>
  24. <td>-0.400654</td>
  25. </tr>
  26. </tbody>
  27. </table>
ab
0&-0.474063
1<-0.230305
2>-0.400654

Not escaped:

  1. In [313]: print(df.to_html(escape=False))
  2. <table border="1" class="dataframe">
  3. <thead>
  4. <tr style="text-align: right;">
  5. <th></th>
  6. <th>a</th>
  7. <th>b</th>
  8. </tr>
  9. </thead>
  10. <tbody>
  11. <tr>
  12. <th>0</th>
  13. <td>&</td>
  14. <td>-0.474063</td>
  15. </tr>
  16. <tr>
  17. <th>1</th>
  18. <td><</td>
  19. <td>-0.230305</td>
  20. </tr>
  21. <tr>
  22. <th>2</th>
  23. <td>></td>
  24. <td>-0.400654</td>
  25. </tr>
  26. </tbody>
  27. </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.

HTML Table Parsing Gotchas

There are some versioning issues surrounding the libraries that are used toparse HTML tables in the top-level pandas io function read_html.

Issues withlxml

  • Benefits
  • lxml is very fast.
  • lxml requires Cython to install correctly.
  • Drawbacks
  • lxml does not make any guarantees about the results of its parseunless it is given strictly valid markup.
  • In light of the above, we have chosen to allow you, the user, to use thelxml backend, but this backend will use html5lib if lxmlfails to parse
  • It is therefore highly recommended that you install bothBeautifulSoup4 and html5lib, so that you will still get a validresult (provided everything else is valid) even if lxml fails.

Issues withBeautifulSoup4usinglxmlas a backend

  • The above issues hold here as well since BeautifulSoup4 is essentiallyjust a wrapper around a parser backend.

Issues withBeautifulSoup4usinghtml5libas a backend

  • Benefits
  • html5lib is far more lenient than lxml and consequently dealswith real-life markup in a much saner way rather than just, e.g.,dropping an element without notifying you.
  • html5lib generates valid HTML5 markup from invalid markupautomatically. This is extremely important for parsing HTML tables,since it guarantees a valid document. However, that does NOT mean thatit is “correct”, since the process of fixing markup does not have asingle definition.
  • html5lib is pure Python and requires no additional build steps beyondits own installation.
  • Drawbacks
  • The biggest drawback to using html5lib is that it is slow asmolasses. However consider the fact that many tables on the web are notbig enough for the parsing algorithm runtime to matter. It is morelikely that the bottleneck will be in the process of reading the rawtext from the URL over the web, i.e., IO (input-output). For very largetables, this might not be true.

Excel files

The read_excel() method can read Excel 2003 (.xls)files using the xlrd Python module. Excel 2007+ (.xlsx) filescan be read using either xlrd or openpyxl.The to_excel() instance method is used forsaving a DataFrame to Excel. Generally the semantics aresimilar to working with csv data.See the cookbook for some advanced strategies.

Reading Excel files

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

  1. # Returns a DataFrame
  2. pd.read_excel('path_to_file.xls', sheet_name='Sheet1')

ExcelFile class

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

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

The ExcelFile class can also be used as a context manager.

  1. with pd.ExcelFile('path_to_file.xls') as xls:
  2. df1 = pd.read_excel(xls, 'Sheet1')
  3. df2 = pd.read_excel(xls, 'Sheet2')

The sheet_names property will generatea list of the sheet names in the file.

The primary use-case for an ExcelFile is parsing multiple sheets withdifferent parameters:

  1. data = {}
  2. # For when Sheet1's format differs from Sheet2
  3. with pd.ExcelFile('path_to_file.xls') as xls:
  4. data['Sheet1'] = pd.read_excel(xls, 'Sheet1', index_col=None,
  5. na_values=['NA'])
  6. 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 to read_excel with no loss in performance.

  1. # using the ExcelFile class
  2. data = {}
  3. with pd.ExcelFile('path_to_file.xls') as xls:
  4. data['Sheet1'] = pd.read_excel(xls, 'Sheet1', index_col=None,
  5. na_values=['NA'])
  6. data['Sheet2'] = pd.read_excel(xls, 'Sheet2', index_col=None,
  7. na_values=['NA'])
  8.  
  9. # equivalent using the read_excel function
  10. data = pd.read_excel('path_to_file.xls', ['Sheet1', 'Sheet2'],
  11. index_col=None, na_values=['NA'])

ExcelFile can also be called with a xlrd.book.Book objectas a parameter. This allows the user to control how the excel file is read.For example, sheets can be loaded on demand by calling xlrd.open_workbook()with on_demand=True.

  1. import xlrd
  2. xlrd_book = xlrd.open_workbook('path_to_file.xls', on_demand=True)
  3. with pd.ExcelFile(xlrd_book) as xls:
  4. df1 = pd.read_excel(xls, 'Sheet1')
  5. df2 = pd.read_excel(xls, 'Sheet2')

Specifying sheets

Note

The second argument is sheet_name, not to be confused with ExcelFile.sheet_names.

Note

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

  • The arguments sheet_name allows specifying the sheet or sheets to read.
  • The default value for sheet_name 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 a None to return a dictionary of all available sheets.
  1. # Returns a DataFrame
  2. pd.read_excel('path_to_file.xls', 'Sheet1', index_col=None, na_values=['NA'])

Using the sheet index:

  1. # Returns a DataFrame
  2. pd.read_excel('path_to_file.xls', 0, index_col=None, na_values=['NA'])

Using all default values:

  1. # Returns a DataFrame
  2. pd.read_excel('path_to_file.xls')

Using None to get all sheets:

  1. # Returns a dictionary of DataFrames
  2. pd.read_excel('path_to_file.xls', sheet_name=None)

Using a list to get multiple sheets:

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

read_excel can read more than one sheet, by setting sheet_name to eithera list of sheet names, a list of sheet positions, or None to read all sheets.Sheets can be specified by sheet index or sheet name, using an integer or string,respectively.

Reading a MultiIndex

read_excel can read a MultiIndex index, by passing a list of columns to index_coland a MultiIndex column by passing a list of rows to header. If either the indexor columns 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 a MultiIndex index without names:

  1. In [314]: df = pd.DataFrame({'a': [1, 2, 3, 4], 'b': [5, 6, 7, 8]},
  2. .....: index=pd.MultiIndex.from_product([['a', 'b'], ['c', 'd']]))
  3. .....:
  4.  
  5. In [315]: df.to_excel('path_to_file.xlsx')
  6.  
  7. In [316]: df = pd.read_excel('path_to_file.xlsx', index_col=[0, 1])
  8.  
  9. In [317]: df
  10. Out[317]:
  11. a b
  12. a c 1 5
  13. d 2 6
  14. b c 3 7
  15. d 4 8

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

  1. In [318]: df.index = df.index.set_names(['lvl1', 'lvl2'])
  2.  
  3. In [319]: df.to_excel('path_to_file.xlsx')
  4.  
  5. In [320]: df = pd.read_excel('path_to_file.xlsx', index_col=[0, 1])
  6.  
  7. In [321]: df
  8. Out[321]:
  9. a b
  10. lvl1 lvl2
  11. a c 1 5
  12. d 2 6
  13. b c 3 7
  14. d 4 8

If the source file has both MultiIndex index and columns, lists specifying eachshould be passed to index_col and header:

  1. In [322]: df.columns = pd.MultiIndex.from_product([['a'], ['b', 'd']],
  2. .....: names=['c1', 'c2'])
  3. .....:
  4.  
  5. In [323]: df.to_excel('path_to_file.xlsx')
  6.  
  7. In [324]: df = pd.read_excel('path_to_file.xlsx', index_col=[0, 1], header=[0, 1])
  8.  
  9. In [325]: df
  10. Out[325]:
  11. c1 a
  12. c2 b d
  13. lvl1 lvl2
  14. a c 1 5
  15. d 2 6
  16. b c 3 7
  17. d 4 8

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 takesa usecols keyword to allow you to specify a subset of columns to parse.

Deprecated since version 0.24.0.

Passing in an integer for usecols has been deprecated. Please pass in a listof ints from 0 to usecols inclusive instead.

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

  1. pd.read_excel('path_to_file.xls', 'Sheet1', usecols=2)

You can also specify a comma-delimited set of Excel columns and ranges as a string:

  1. pd.read_excel('path_to_file.xls', 'Sheet1', usecols='A,C:E')

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

  1. pd.read_excel('path_to_file.xls', 'Sheet1', usecols=[0, 2, 3])

Element order is ignored, so usecols=[0, 1] is the same as [1, 0].

New in version 0.24.

If usecols is a list of strings, it is assumed that each string correspondsto a column name provided either by the user in names or inferred from thedocument header row(s). Those strings define which columns will be parsed:

  1. pd.read_excel('path_to_file.xls', 'Sheet1', usecols=['foo', 'bar'])

Element order is ignored, so usecols=['baz', 'joe'] is the same as ['joe', 'baz'].

New in version 0.24.

If usecols is callable, the callable function will be evaluated againstthe column names, returning names where the callable function evaluates to True.

  1. pd.read_excel('path_to_file.xls', 'Sheet1', usecols=lambda x: x.isalpha())

Parsing dates

Datetime-like values are normally automatically converted to the appropriatedtype when reading the excel file. But if you have a column of strings thatlook like dates (but are not actually formatted as dates in excel), you canuse the parse_dates keyword to parse those strings to datetimes:

  1. pd.read_excel('path_to_file.xls', 'Sheet1', parse_dates=['date_strings'])

Cell converters

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

  1. pd.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:

  1. def cfun(x):
  2. return int(x) if x else -1
  3.  
  4.  
  5. pd.read_excel('path_to_file.xls', 'Sheet1', converters={'MyInts': cfun})

Dtype specifications

New in version 0.20.

As an alternative to converters, the type for an entire column canbe specified using the dtype keyword, which takes a dictionarymapping column names to types. To interpret data withno type inference, use the type str or object.

  1. pd.read_excel('path_to_file.xls', dtype={'MyInts': 'int64', 'MyText': str})

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 as to_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:

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

Files with a .xls extension will be written using xlwt and those with a.xlsx extension will be written using xlsxwriter (if available) oropenpyxl.

The DataFrame will be written in a way that tries to mimic the REPL output.The index_label will be placed in the secondrow instead of the first. You can place it in the first row by setting themerge_cells option in to_excel() to False:

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

In order to write separate DataFrames to separate sheets in a single Excel file,one can pass an ExcelWriter.

  1. with pd.ExcelWriter('path_to_file.xlsx') as writer:
  2. df1.to_excel(writer, sheet_name='Sheet1')
  3. df2.to_excel(writer, sheet_name='Sheet2')

Note

Wringing a little more performance out of read_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 pass convert_float=False to disable this behavior, whichmay give a slight performance improvement.

Writing Excel files to memory

Pandas supports writing Excel files to buffer-like objects such as StringIO orBytesIO using ExcelWriter.

  1. # Safe import for either Python 2.x or 3.x
  2. try:
  3. from io import BytesIO
  4. except ImportError:
  5. from cStringIO import StringIO as BytesIO
  6.  
  7. bio = BytesIO()
  8.  
  9. # By setting the 'engine' in the ExcelWriter constructor.
  10. writer = pd.ExcelWriter(bio, engine='xlsxwriter')
  11. df.to_excel(writer, sheet_name='Sheet1')
  12.  
  13. # Save the workbook
  14. writer.save()
  15.  
  16. # Seek to the beginning and read to copy the workbook to a variable in memory
  17. bio.seek(0)
  18. workbook = bio.read()

Note

engine is optional but recommended. Setting the engine determinesthe version of workbook produced. Setting engine='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

Pandas chooses an Excel writer via two methods:

  • the engine keyword argument
  • the filename extension (via the default specified in config options)By default, pandas uses the XlsxWriter for .xlsx, openpyxlfor .xlsm, and xlwt for .xls files. If you have multipleengines installed, you can set the default engine through setting theconfig options io.excel.xlsx.writer andio.excel.xls.writer. pandas will fall back on openpyxl for .xlsxfiles if Xlsxwriter is not available.

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

  • openpyxl: version 2.4 or higher is required
  • xlsxwriter
  • xlwt
  1. # By setting the 'engine' in the DataFrame 'to_excel()' methods.
  2. df.to_excel('path_to_file.xlsx', sheet_name='Sheet1', engine='xlsxwriter')
  3.  
  4. # By setting the 'engine' in the ExcelWriter constructor.
  5. writer = pd.ExcelWriter('path_to_file.xlsx', engine='xlsxwriter')
  6.  
  7. # Or via pandas configuration.
  8. from pandas import options # noqa: E402
  9. options.io.excel.xlsx.writer = 'xlsxwriter'
  10.  
  11. df.to_excel('path_to_file.xlsx', sheet_name='Sheet1')

Style and formatting

The look and feel of Excel worksheets created from pandas can be modified using the following parameters on the DataFrame’s to_excel method.

  • float_format : Format string for floating point numbers (default None).
  • freeze_panes : A tuple of two integers representing the bottommost row and rightmost column to freeze. Each of these parameters is one-based, so (1, 1) will freeze the first row and first column (default None).

Using the Xlsxwriter engine provides many options for controlling theformat of an Excel worksheet created with the to_excel method. Excellent examples can be found in theXlsxwriter documentation here: https://xlsxwriter.readthedocs.io/working_with_pandas.html

OpenDocument Spreadsheets

New in version 0.25.

The read_excel() method can also read OpenDocument spreadsheetsusing the odfpy module. The semantics and features for readingOpenDocument spreadsheets match what can be done for Excel files usingengine='odf'.

  1. # Returns a DataFrame
  2. pd.read_excel('path_to_file.ods', engine='odf')

Note

Currently pandas only supports reading OpenDocument spreadsheets. Writingis not implemented.

Clipboard

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

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

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

  1. >>> clipdf = pd.read_clipboard()
  2. >>> clipdf
  3. A B C
  4. x 1 4 p
  5. y 2 5 q
  6. z 3 6 r

The to_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.

  1. >>> df = pd.DataFrame({'A': [1, 2, 3],
  2. ... 'B': [4, 5, 6],
  3. ... 'C': ['p', 'q', 'r']},
  4. ... index=['x', 'y', 'z'])
  5. >>> df
  6. A B C
  7. x 1 4 p
  8. y 2 5 q
  9. z 3 6 r
  10. >>> df.to_clipboard()
  11. >>> pd.read_clipboard()
  12. A B C
  13. x 1 4 p
  14. y 2 5 q
  15. z 3 6 r

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 PyQt5, PyQt4 or qtpy) on Linux to use these methods.

Pickling

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

  1. In [326]: df
  2. Out[326]:
  3. c1 a
  4. c2 b d
  5. lvl1 lvl2
  6. a c 1 5
  7. d 2 6
  8. b c 3 7
  9. d 4 8
  10.  
  11. In [327]: df.to_pickle('foo.pkl')

The read_pickle function in the pandas namespace can be used to loadany pickled pandas object (or any other pickled object) from file:

  1. In [328]: pd.read_pickle('foo.pkl')
  2. Out[328]:
  3. c1 a
  4. c2 b d
  5. lvl1 lvl2
  6. a c 1 5
  7. d 2 6
  8. b c 3 7
  9. d 4 8

Warning

Loading pickled data received from untrusted sources can be unsafe.

See: https://docs.python.org/3/library/pickle.html

Warning

read_pickle() is only guaranteed backwards compatible back to pandas version 0.20.3

Compressed pickle files

New in version 0.20.0.

read_pickle(), DataFrame.to_pickle() and Series.to_pickle() can readand write compressed pickle files. The compression types of gzip, bz2, xz are supported for reading and writing.The zip file format only supports reading and must contain only one data fileto be read.

The compression type can be an explicit parameter or be inferred from the file extension.If ‘infer’, then use gzip, bz2, zip, or xz if filename ends in '.gz', '.bz2', '.zip', or'.xz', respectively.

  1. In [329]: df = pd.DataFrame({
  2. .....: 'A': np.random.randn(1000),
  3. .....: 'B': 'foo',
  4. .....: 'C': pd.date_range('20130101', periods=1000, freq='s')})
  5. .....:
  6.  
  7. In [330]: df
  8. Out[330]:
  9. A B C
  10. 0 -0.288267 foo 2013-01-01 00:00:00
  11. 1 -0.084905 foo 2013-01-01 00:00:01
  12. 2 0.004772 foo 2013-01-01 00:00:02
  13. 3 1.382989 foo 2013-01-01 00:00:03
  14. 4 0.343635 foo 2013-01-01 00:00:04
  15. .. ... ... ...
  16. 995 -0.220893 foo 2013-01-01 00:16:35
  17. 996 0.492996 foo 2013-01-01 00:16:36
  18. 997 -0.461625 foo 2013-01-01 00:16:37
  19. 998 1.361779 foo 2013-01-01 00:16:38
  20. 999 -1.197988 foo 2013-01-01 00:16:39
  21.  
  22. [1000 rows x 3 columns]

Using an explicit compression type:

  1. In [331]: df.to_pickle("data.pkl.compress", compression="gzip")
  2.  
  3. In [332]: rt = pd.read_pickle("data.pkl.compress", compression="gzip")
  4.  
  5. In [333]: rt
  6. Out[333]:
  7. A B C
  8. 0 -0.288267 foo 2013-01-01 00:00:00
  9. 1 -0.084905 foo 2013-01-01 00:00:01
  10. 2 0.004772 foo 2013-01-01 00:00:02
  11. 3 1.382989 foo 2013-01-01 00:00:03
  12. 4 0.343635 foo 2013-01-01 00:00:04
  13. .. ... ... ...
  14. 995 -0.220893 foo 2013-01-01 00:16:35
  15. 996 0.492996 foo 2013-01-01 00:16:36
  16. 997 -0.461625 foo 2013-01-01 00:16:37
  17. 998 1.361779 foo 2013-01-01 00:16:38
  18. 999 -1.197988 foo 2013-01-01 00:16:39
  19.  
  20. [1000 rows x 3 columns]

Inferring compression type from the extension:

  1. In [334]: df.to_pickle("data.pkl.xz", compression="infer")
  2.  
  3. In [335]: rt = pd.read_pickle("data.pkl.xz", compression="infer")
  4.  
  5. In [336]: rt
  6. Out[336]:
  7. A B C
  8. 0 -0.288267 foo 2013-01-01 00:00:00
  9. 1 -0.084905 foo 2013-01-01 00:00:01
  10. 2 0.004772 foo 2013-01-01 00:00:02
  11. 3 1.382989 foo 2013-01-01 00:00:03
  12. 4 0.343635 foo 2013-01-01 00:00:04
  13. .. ... ... ...
  14. 995 -0.220893 foo 2013-01-01 00:16:35
  15. 996 0.492996 foo 2013-01-01 00:16:36
  16. 997 -0.461625 foo 2013-01-01 00:16:37
  17. 998 1.361779 foo 2013-01-01 00:16:38
  18. 999 -1.197988 foo 2013-01-01 00:16:39
  19.  
  20. [1000 rows x 3 columns]

The default is to ‘infer’:

  1. In [337]: df.to_pickle("data.pkl.gz")
  2.  
  3. In [338]: rt = pd.read_pickle("data.pkl.gz")
  4.  
  5. In [339]: rt
  6. Out[339]:
  7. A B C
  8. 0 -0.288267 foo 2013-01-01 00:00:00
  9. 1 -0.084905 foo 2013-01-01 00:00:01
  10. 2 0.004772 foo 2013-01-01 00:00:02
  11. 3 1.382989 foo 2013-01-01 00:00:03
  12. 4 0.343635 foo 2013-01-01 00:00:04
  13. .. ... ... ...
  14. 995 -0.220893 foo 2013-01-01 00:16:35
  15. 996 0.492996 foo 2013-01-01 00:16:36
  16. 997 -0.461625 foo 2013-01-01 00:16:37
  17. 998 1.361779 foo 2013-01-01 00:16:38
  18. 999 -1.197988 foo 2013-01-01 00:16:39
  19.  
  20. [1000 rows x 3 columns]
  21.  
  22. In [340]: df["A"].to_pickle("s1.pkl.bz2")
  23.  
  24. In [341]: rt = pd.read_pickle("s1.pkl.bz2")
  25.  
  26. In [342]: rt
  27. Out[342]:
  28. 0 -0.288267
  29. 1 -0.084905
  30. 2 0.004772
  31. 3 1.382989
  32. 4 0.343635
  33. ...
  34. 995 -0.220893
  35. 996 0.492996
  36. 997 -0.461625
  37. 998 1.361779
  38. 999 -1.197988
  39. Name: A, Length: 1000, dtype: float64

msgpack

pandas supports the msgpack 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

The msgpack format is deprecated as of 0.25 and will be removed in a future version.It is recommended to use pyarrow for on-the-wire transmission of pandas objects.

Warning

read_msgpack() is only guaranteed backwards compatible back to pandas version 0.20.3

  1. In [343]: df = pd.DataFrame(np.random.rand(5, 2), columns=list('AB'))
  2.  
  3. In [344]: df.to_msgpack('foo.msg')
  4.  
  5. In [345]: pd.read_msgpack('foo.msg')
  6. Out[345]:
  7. A B
  8. 0 0.275432 0.293583
  9. 1 0.842639 0.165381
  10. 2 0.608925 0.778891
  11. 3 0.136543 0.029703
  12. 4 0.318083 0.604870
  13.  
  14. In [346]: 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.

  1. In [347]: pd.to_msgpack('foo.msg', df, 'foo', np.array([1, 2, 3]), s)
  2.  
  3. In [348]: pd.read_msgpack('foo.msg')
  4. Out[348]:
  5. [ A B
  6. 0 0.275432 0.293583
  7. 1 0.842639 0.165381
  8. 2 0.608925 0.778891
  9. 3 0.136543 0.029703
  10. 4 0.318083 0.604870, 'foo', array([1, 2, 3]), 2013-01-01 0.330824
  11. 2013-01-02 0.790825
  12. 2013-01-03 0.308468
  13. 2013-01-04 0.092397
  14. 2013-01-05 0.703091
  15. Freq: D, dtype: float64]

You can pass iterator=True to iterate over the unpacked results:

  1. In [349]: for o in pd.read_msgpack('foo.msg', iterator=True):
  2. .....: print(o)
  3. .....:
  4. A B
  5. 0 0.275432 0.293583
  6. 1 0.842639 0.165381
  7. 2 0.608925 0.778891
  8. 3 0.136543 0.029703
  9. 4 0.318083 0.604870
  10. foo
  11. [1 2 3]
  12. 2013-01-01 0.330824
  13. 2013-01-02 0.790825
  14. 2013-01-03 0.308468
  15. 2013-01-04 0.092397
  16. 2013-01-05 0.703091
  17. Freq: D, dtype: float64

You can pass append=True to the writer to append to an existing pack:

  1. In [350]: df.to_msgpack('foo.msg', append=True)
  2.  
  3. In [351]: pd.read_msgpack('foo.msg')
  4. Out[351]:
  5. [ A B
  6. 0 0.275432 0.293583
  7. 1 0.842639 0.165381
  8. 2 0.608925 0.778891
  9. 3 0.136543 0.029703
  10. 4 0.318083 0.604870, 'foo', array([1, 2, 3]), 2013-01-01 0.330824
  11. 2013-01-02 0.790825
  12. 2013-01-03 0.308468
  13. 2013-01-04 0.092397
  14. 2013-01-05 0.703091
  15. Freq: D, dtype: float64, A B
  16. 0 0.275432 0.293583
  17. 1 0.842639 0.165381
  18. 2 0.608925 0.778891
  19. 3 0.136543 0.029703
  20. 4 0.318083 0.604870]

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

  1. In [352]: pd.to_msgpack('foo2.msg', {'dict': [{'df': df}, {'string': 'foo'},
  2. .....: {'scalar': 1.}, {'s': s}]})
  3. .....:
  4.  
  5. In [353]: pd.read_msgpack('foo2.msg')
  6. Out[353]:
  7. {'dict': ({'df': A B
  8. 0 0.275432 0.293583
  9. 1 0.842639 0.165381
  10. 2 0.608925 0.778891
  11. 3 0.136543 0.029703
  12. 4 0.318083 0.604870},
  13. {'string': 'foo'},
  14. {'scalar': 1.0},
  15. {'s': 2013-01-01 0.330824
  16. 2013-01-02 0.790825
  17. 2013-01-03 0.308468
  18. 2013-01-04 0.092397
  19. 2013-01-05 0.703091
  20. Freq: D, dtype: float64})}

Read/write API

Msgpacks can also be read from and written to strings.

  1. In [354]: df.to_msgpack()
  2. Out[354]: b'\x84\xa3typ\xadblock_manager\xa5klass\xa9DataFrame\xa4axes\x92\x86\xa3typ\xa5index\xa5klass\xa5Index\xa4name\xc0\xa5dtype\xa6object\xa4data\x92\xa1A\xa1B\xa8compress\xc0\x86\xa3typ\xabrange_index\xa5klass\xaaRangeIndex\xa4name\xc0\xa5start\x00\xa4stop\x05\xa4step\x01\xa6blocks\x91\x86\xa4locs\x86\xa3typ\xa7ndarray\xa5shape\x91\x02\xa4ndim\x01\xa5dtype\xa5int64\xa4data\xd8\x00\x00\x00\x00\x00\x00\x00\x00\x00\x01\x00\x00\x00\x00\x00\x00\x00\xa8compress\xc0\xa6values\xc7P\x00\xc84 \x84\xac\xa0\xd1?\x0f\xa4.\xb5\xe6\xf6\xea?\xb9\x85\x9aLO|\xe3?\xac\xf0\xd7\x81>z\xc1?\\\xca\x97\ty[\xd4?\x9c\x9b\x8a:\x11\xca\xd2?\x14zX\xd01+\xc5?4=\x19b\xad\xec\xe8?\xc0!\xe9\xf4\x8ej\x9e?\xa7>_\xac\x17[\xe3?\xa5shape\x92\x02\x05\xa5dtype\xa7float64\xa5klass\xaaFloatBlock\xa8compress\xc0'

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

  1. In [355]: pd.read_msgpack(df.to_msgpack() + s.to_msgpack())
  2. Out[355]:
  3. [ A B
  4. 0 0.275432 0.293583
  5. 1 0.842639 0.165381
  6. 2 0.608925 0.778891
  7. 3 0.136543 0.029703
  8. 4 0.318083 0.604870, 2013-01-01 0.330824
  9. 2013-01-02 0.790825
  10. 2013-01-03 0.308468
  11. 2013-01-04 0.092397
  12. 2013-01-05 0.703091
  13. Freq: D, dtype: float64]

HDF5 (PyTables)

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

Warning

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

  1. In [356]: store = pd.HDFStore('store.h5')
  2.  
  3. In [357]: print(store)
  4. <class 'pandas.io.pytables.HDFStore'>
  5. File path: store.h5

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

  1. In [358]: index = pd.date_range('1/1/2000', periods=8)
  2.  
  3. In [359]: s = pd.Series(np.random.randn(5), index=['a', 'b', 'c', 'd', 'e'])
  4.  
  5. In [360]: df = pd.DataFrame(np.random.randn(8, 3), index=index,
  6. .....: columns=['A', 'B', 'C'])
  7. .....:
  8.  
  9. # store.put('s', s) is an equivalent method
  10. In [361]: store['s'] = s
  11.  
  12. In [362]: store['df'] = df
  13.  
  14. In [363]: store
  15. Out[363]:
  16. <class 'pandas.io.pytables.HDFStore'>
  17. File path: store.h5

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

  1. # store.get('df') is an equivalent method
  2. In [364]: store['df']
  3. Out[364]:
  4. A B C
  5. 2000-01-01 -0.426936 -1.780784 0.322691
  6. 2000-01-02 1.638174 -2.184251 0.049673
  7. 2000-01-03 -1.022803 0.889445 2.827717
  8. 2000-01-04 1.767446 -1.305266 -0.378355
  9. 2000-01-05 0.486743 0.954551 0.859671
  10. 2000-01-06 -1.170458 -1.211386 -0.852728
  11. 2000-01-07 -0.450781 1.064650 1.014927
  12. 2000-01-08 -0.810399 0.254343 -0.875526
  13.  
  14. # dotted (attribute) access provides get as well
  15. In [365]: store.df
  16. Out[365]:
  17. A B C
  18. 2000-01-01 -0.426936 -1.780784 0.322691
  19. 2000-01-02 1.638174 -2.184251 0.049673
  20. 2000-01-03 -1.022803 0.889445 2.827717
  21. 2000-01-04 1.767446 -1.305266 -0.378355
  22. 2000-01-05 0.486743 0.954551 0.859671
  23. 2000-01-06 -1.170458 -1.211386 -0.852728
  24. 2000-01-07 -0.450781 1.064650 1.014927
  25. 2000-01-08 -0.810399 0.254343 -0.875526

Deletion of the object specified by the key:

  1. # store.remove('df') is an equivalent method
  2. In [366]: del store['df']
  3.  
  4. In [367]: store
  5. Out[367]:
  6. <class 'pandas.io.pytables.HDFStore'>
  7. File path: store.h5

Closing a Store and using a context manager:

  1. In [368]: store.close()
  2.  
  3. In [369]: store
  4. Out[369]:
  5. <class 'pandas.io.pytables.HDFStore'>
  6. File path: store.h5
  7.  
  8. In [370]: store.is_open
  9. Out[370]: False
  10.  
  11. # Working with, and automatically closing the store using a context manager
  12. In [371]: with pd.HDFStore('store.h5') as store:
  13. .....: store.keys()
  14. .....:

Read/write API

HDFStore supports an top-level API using read_hdf for reading and to_hdf for writing,similar to how read_csv and to_csv work.

  1. In [372]: df_tl = pd.DataFrame({'A': list(range(5)), 'B': list(range(5))})
  2.  
  3. In [373]: df_tl.to_hdf('store_tl.h5', 'table', append=True)
  4.  
  5. In [374]: pd.read_hdf('store_tl.h5', 'table', where=['index>2'])
  6. Out[374]:
  7. A B
  8. 3 3 3
  9. 4 4 4

HDFStore will by default not drop rows that are all missing. This behavior can be changed by setting dropna=True.

  1. In [375]: df_with_missing = pd.DataFrame({'col1': [0, np.nan, 2],
  2. .....: 'col2': [1, np.nan, np.nan]})
  3. .....:
  4.  
  5. In [376]: df_with_missing
  6. Out[376]:
  7. col1 col2
  8. 0 0.0 1.0
  9. 1 NaN NaN
  10. 2 2.0 NaN
  11.  
  12. In [377]: df_with_missing.to_hdf('file.h5', 'df_with_missing',
  13. .....: format='table', mode='w')
  14. .....:
  15.  
  16. In [378]: pd.read_hdf('file.h5', 'df_with_missing')
  17. Out[378]:
  18. col1 col2
  19. 0 0.0 1.0
  20. 1 NaN NaN
  21. 2 2.0 NaN
  22.  
  23. In [379]: df_with_missing.to_hdf('file.h5', 'df_with_missing',
  24. .....: format='table', mode='w', dropna=True)
  25. .....:
  26.  
  27. In [380]: pd.read_hdf('file.h5', 'df_with_missing')
  28. Out[380]:
  29. col1 col2
  30. 0 0.0 1.0
  31. 2 2.0 NaN

Fixed format

The examples above show storing using put, which write the HDF5 to PyTables in a fixed array format, calledthe fixed format. These types of stores are not appendable once written (though you can simplyremove them and rewrite). Nor are they queryable; they must beretrieved in their entirety. They also do not support dataframes with non-unique column names.The fixed format stores offer very fast writing and slightly faster reading than table stores.This format is specified by default when using put or to_hdf or by format='fixed' or format='f'.

Warning

A fixed format will raise a TypeError if you try to retrieve using a where:

  1. >>> pd.DataFrame(np.random.randn(10, 2)).to_hdf('test_fixed.h5', 'df')
  2. >>> pd.read_hdf('test_fixed.h5', 'df', where='index>5')
  3. TypeError: cannot pass a where specification when reading a fixed format.
  4. this store must be selected in its entirety

Table format

HDFStore supports another PyTables format on disk, the tableformat. Conceptually a table is shaped very much like a DataFrame,with rows and columns. A table may be appended to in the same orother sessions. In addition, delete and query type operations aresupported. This format is specified by format='table' or format='t'to append or put or to_hdf.

This format can be set as an option as well pd.set_option('io.hdf.default_format','table') toenable put/append/to_hdf to by default store in the table format.

  1. In [381]: store = pd.HDFStore('store.h5')
  2.  
  3. In [382]: df1 = df[0:4]
  4.  
  5. In [383]: df2 = df[4:]
  6.  
  7. # append data (creates a table automatically)
  8. In [384]: store.append('df', df1)
  9.  
  10. In [385]: store.append('df', df2)
  11.  
  12. In [386]: store
  13. Out[386]:
  14. <class 'pandas.io.pytables.HDFStore'>
  15. File path: store.h5
  16.  
  17. # select the entire object
  18. In [387]: store.select('df')
  19. Out[387]:
  20. A B C
  21. 2000-01-01 -0.426936 -1.780784 0.322691
  22. 2000-01-02 1.638174 -2.184251 0.049673
  23. 2000-01-03 -1.022803 0.889445 2.827717
  24. 2000-01-04 1.767446 -1.305266 -0.378355
  25. 2000-01-05 0.486743 0.954551 0.859671
  26. 2000-01-06 -1.170458 -1.211386 -0.852728
  27. 2000-01-07 -0.450781 1.064650 1.014927
  28. 2000-01-08 -0.810399 0.254343 -0.875526
  29.  
  30. # the type of stored data
  31. In [388]: store.root.df._v_attrs.pandas_type
  32. Out[388]: 'frame_table'

Note

You can also create a table by passing format='table' or format='t' to a put 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 (or Groups 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 be careful.

  1. In [389]: store.put('foo/bar/bah', df)
  2.  
  3. In [390]: store.append('food/orange', df)
  4.  
  5. In [391]: store.append('food/apple', df)
  6.  
  7. In [392]: store
  8. Out[392]:
  9. <class 'pandas.io.pytables.HDFStore'>
  10. File path: store.h5
  11.  
  12. # a list of keys are returned
  13. In [393]: store.keys()
  14. Out[393]: ['/df', '/food/apple', '/food/orange', '/foo/bar/bah']
  15.  
  16. # remove all nodes under this level
  17. In [394]: store.remove('food')
  18.  
  19. In [395]: store
  20. Out[395]:
  21. <class 'pandas.io.pytables.HDFStore'>
  22. File path: store.h5

You can walk through the group hierarchy using the walk method whichwill yield a tuple for each group key along with the relative keys of its contents.

New in version 0.24.0.

  1. In [396]: for (path, subgroups, subkeys) in store.walk():
  2. .....: for subgroup in subgroups:
  3. .....: print('GROUP: {}/{}'.format(path, subgroup))
  4. .....: for subkey in subkeys:
  5. .....: key = '/'.join([path, subkey])
  6. .....: print('KEY: {}'.format(key))
  7. .....: print(store.get(key))
  8. .....:
  9. GROUP: /foo
  10. KEY: /df
  11. A B C
  12. 2000-01-01 -0.426936 -1.780784 0.322691
  13. 2000-01-02 1.638174 -2.184251 0.049673
  14. 2000-01-03 -1.022803 0.889445 2.827717
  15. 2000-01-04 1.767446 -1.305266 -0.378355
  16. 2000-01-05 0.486743 0.954551 0.859671
  17. 2000-01-06 -1.170458 -1.211386 -0.852728
  18. 2000-01-07 -0.450781 1.064650 1.014927
  19. 2000-01-08 -0.810399 0.254343 -0.875526
  20. GROUP: /foo/bar
  21. KEY: /foo/bar/bah
  22. A B C
  23. 2000-01-01 -0.426936 -1.780784 0.322691
  24. 2000-01-02 1.638174 -2.184251 0.049673
  25. 2000-01-03 -1.022803 0.889445 2.827717
  26. 2000-01-04 1.767446 -1.305266 -0.378355
  27. 2000-01-05 0.486743 0.954551 0.859671
  28. 2000-01-06 -1.170458 -1.211386 -0.852728
  29. 2000-01-07 -0.450781 1.064650 1.014927
  30. 2000-01-08 -0.810399 0.254343 -0.875526

Warning

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

  1. In [8]: store.foo.bar.bah
  2. AttributeError: 'HDFStore' object has no attribute 'foo'
  3.  
  4. # you can directly access the actual PyTables node but using the root node
  5. In [9]: store.root.foo.bar.bah
  6. Out[9]:
  7. /foo/bar/bah (Group) ''
  8. children := ['block0_items' (Array), 'block0_values' (Array), 'axis0' (Array), 'axis1' (Array)]

Instead, use explicit string based keys:

  1. In [397]: store['foo/bar/bah']
  2. Out[397]:
  3. A B C
  4. 2000-01-01 -0.426936 -1.780784 0.322691
  5. 2000-01-02 1.638174 -2.184251 0.049673
  6. 2000-01-03 -1.022803 0.889445 2.827717
  7. 2000-01-04 1.767446 -1.305266 -0.378355
  8. 2000-01-05 0.486743 0.954551 0.859671
  9. 2000-01-06 -1.170458 -1.211386 -0.852728
  10. 2000-01-07 -0.450781 1.064650 1.014927
  11. 2000-01-08 -0.810399 0.254343 -0.875526

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 a ValueError.

Passing minitemsize={values: size} as a parameter to appendwill set a larger minimum for the string columns. Storing floats,strings, ints, bools, datetime64 are currently supported. For stringcolumns, passing nan_rep = 'nan' to append will change the defaultnan representation on disk (which converts to/from _np.nan), thisdefaults to nan.

  1. In [398]: df_mixed = pd.DataFrame({'A': np.random.randn(8),
  2. .....: 'B': np.random.randn(8),
  3. .....: 'C': np.array(np.random.randn(8), dtype='float32'),
  4. .....: 'string': 'string',
  5. .....: 'int': 1,
  6. .....: 'bool': True,
  7. .....: 'datetime64': pd.Timestamp('20010102')},
  8. .....: index=list(range(8)))
  9. .....:
  10.  
  11. In [399]: df_mixed.loc[df_mixed.index[3:5],
  12. .....: ['A', 'B', 'string', 'datetime64']] = np.nan
  13. .....:
  14.  
  15. In [400]: store.append('df_mixed', df_mixed, min_itemsize={'values': 50})
  16.  
  17. In [401]: df_mixed1 = store.select('df_mixed')
  18.  
  19. In [402]: df_mixed1
  20. Out[402]:
  21. A B C string int bool datetime64
  22. 0 -0.980856 0.298656 0.151508 string 1 True 2001-01-02
  23. 1 -0.906920 -1.294022 0.587939 string 1 True 2001-01-02
  24. 2 0.988185 -0.618845 0.043096 string 1 True 2001-01-02
  25. 3 NaN NaN 0.362451 NaN 1 True NaT
  26. 4 NaN NaN 1.356269 NaN 1 True NaT
  27. 5 -0.772889 -0.340872 1.798994 string 1 True 2001-01-02
  28. 6 -0.043509 -0.303900 0.567265 string 1 True 2001-01-02
  29. 7 0.768606 -0.871948 -0.044348 string 1 True 2001-01-02
  30.  
  31. In [403]: df_mixed1.dtypes.value_counts()
  32. Out[403]:
  33. float64 2
  34. datetime64[ns] 1
  35. int64 1
  36. object 1
  37. bool 1
  38. float32 1
  39. dtype: int64
  40.  
  41. # we have provided a minimum string column size
  42. In [404]: store.root.df_mixed.table
  43. Out[404]:
  44. /df_mixed/table (Table(8,)) ''
  45. description := {
  46. "index": Int64Col(shape=(), dflt=0, pos=0),
  47. "values_block_0": Float64Col(shape=(2,), dflt=0.0, pos=1),
  48. "values_block_1": Float32Col(shape=(1,), dflt=0.0, pos=2),
  49. "values_block_2": Int64Col(shape=(1,), dflt=0, pos=3),
  50. "values_block_3": Int64Col(shape=(1,), dflt=0, pos=4),
  51. "values_block_4": BoolCol(shape=(1,), dflt=False, pos=5),
  52. "values_block_5": StringCol(itemsize=50, shape=(1,), dflt=b'', pos=6)}
  53. byteorder := 'little'
  54. chunkshape := (689,)
  55. autoindex := True
  56. colindexes := {
  57. "index": Index(6, medium, shuffle, zlib(1)).is_csi=False}

Storing MultiIndex DataFrames

Storing MultiIndex DataFrames as tables is very similar tostoring/selecting from homogeneous index DataFrames.

  1. In [405]: index = pd.MultiIndex(levels=[['foo', 'bar', 'baz', 'qux'],
  2. .....: ['one', 'two', 'three']],
  3. .....: codes=[[0, 0, 0, 1, 1, 2, 2, 3, 3, 3],
  4. .....: [0, 1, 2, 0, 1, 1, 2, 0, 1, 2]],
  5. .....: names=['foo', 'bar'])
  6. .....:
  7.  
  8. In [406]: df_mi = pd.DataFrame(np.random.randn(10, 3), index=index,
  9. .....: columns=['A', 'B', 'C'])
  10. .....:
  11.  
  12. In [407]: df_mi
  13. Out[407]:
  14. A B C
  15. foo bar
  16. foo one 0.031885 0.641045 0.479460
  17. two -0.630652 -0.182400 -0.789979
  18. three -0.282700 -0.813404 1.252998
  19. bar one 0.758552 0.384775 -1.133177
  20. two -1.002973 -1.644393 -0.311536
  21. baz two -0.615506 -0.084551 -1.318575
  22. three 0.923929 -0.105981 0.429424
  23. qux one -1.034590 0.542245 -0.384429
  24. two 0.170697 -0.200289 1.220322
  25. three -1.001273 0.162172 0.376816
  26.  
  27. In [408]: store.append('df_mi', df_mi)
  28.  
  29. In [409]: store.select('df_mi')
  30. Out[409]:
  31. A B C
  32. foo bar
  33. foo one 0.031885 0.641045 0.479460
  34. two -0.630652 -0.182400 -0.789979
  35. three -0.282700 -0.813404 1.252998
  36. bar one 0.758552 0.384775 -1.133177
  37. two -1.002973 -1.644393 -0.311536
  38. baz two -0.615506 -0.084551 -1.318575
  39. three 0.923929 -0.105981 0.429424
  40. qux one -1.034590 0.542245 -0.384429
  41. two 0.170697 -0.200289 1.220322
  42. three -1.001273 0.162172 0.376816
  43.  
  44. # the levels are automatically included as data columns
  45. In [410]: store.select('df_mi', 'foo=bar')
  46. Out[410]:
  47. A B C
  48. foo bar
  49. bar one 0.758552 0.384775 -1.133177
  50. two -1.002973 -1.644393 -0.311536

Querying

Querying a table

select and delete 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 the Term class under the hood, as a boolean expression.

  • index and columns are supported indexers of a DataFrames.
  • if data_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']"
  • "columns in ['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"

The indexers 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

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

instead of this

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

The latter will not work and will raise a SyntaxError.Note thatthere’s a single quote followed by a double quote in the stringvariable.

If you must interpolate, use the '%r' format specifier

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

which will quote string.

Here are some examples:

  1. In [411]: dfq = pd.DataFrame(np.random.randn(10, 4), columns=list('ABCD'),
  2. .....: index=pd.date_range('20130101', periods=10))
  3. .....:
  4.  
  5. In [412]: store.append('dfq', dfq, format='table', data_columns=True)

Use boolean expressions, with in-line function evaluation.

  1. In [413]: store.select('dfq', "index>pd.Timestamp('20130104') & columns=['A', 'B']")
  2. Out[413]:
  3. A B
  4. 2013-01-05 0.450263 0.755221
  5. 2013-01-06 0.019915 0.300003
  6. 2013-01-07 1.878479 -0.026513
  7. 2013-01-08 3.272320 0.077044
  8. 2013-01-09 -0.398346 0.507286
  9. 2013-01-10 0.516017 -0.501550

Use and inline column reference

  1. In [414]: store.select('dfq', where="A>0 or C>0")
  2. Out[414]:
  3. A B C D
  4. 2013-01-01 -0.161614 -1.636805 0.835417 0.864817
  5. 2013-01-02 0.843452 -0.122918 -0.026122 -1.507533
  6. 2013-01-03 0.335303 -1.340566 -1.024989 1.125351
  7. 2013-01-05 0.450263 0.755221 -1.506656 0.808794
  8. 2013-01-06 0.019915 0.300003 -0.727093 -1.119363
  9. 2013-01-07 1.878479 -0.026513 0.573793 0.154237
  10. 2013-01-08 3.272320 0.077044 0.397034 -0.613983
  11. 2013-01-10 0.516017 -0.501550 0.138212 0.218366

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

  1. In [415]: store.select('df', "columns=['A', 'B']")
  2. Out[415]:
  3. A B
  4. 2000-01-01 -0.426936 -1.780784
  5. 2000-01-02 1.638174 -2.184251
  6. 2000-01-03 -1.022803 0.889445
  7. 2000-01-04 1.767446 -1.305266
  8. 2000-01-05 0.486743 0.954551
  9. 2000-01-06 -1.170458 -1.211386
  10. 2000-01-07 -0.450781 1.064650
  11. 2000-01-08 -0.810399 0.254343

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

Note

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

select will raise a SyntaxError if the query expression is not valid.

Using timedelta64[ns]

You can store and query using the timedelta64[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:

  1. In [416]: from datetime import timedelta
  2.  
  3. In [417]: dftd = pd.DataFrame({'A': pd.Timestamp('20130101'),
  4. .....: 'B': [pd.Timestamp('20130101') + timedelta(days=i,
  5. .....: seconds=10)
  6. .....: for i in range(10)]})
  7. .....:
  8.  
  9. In [418]: dftd['C'] = dftd['A'] - dftd['B']
  10.  
  11. In [419]: dftd
  12. Out[419]:
  13. A B C
  14. 0 2013-01-01 2013-01-01 00:00:10 -1 days +23:59:50
  15. 1 2013-01-01 2013-01-02 00:00:10 -2 days +23:59:50
  16. 2 2013-01-01 2013-01-03 00:00:10 -3 days +23:59:50
  17. 3 2013-01-01 2013-01-04 00:00:10 -4 days +23:59:50
  18. 4 2013-01-01 2013-01-05 00:00:10 -5 days +23:59:50
  19. 5 2013-01-01 2013-01-06 00:00:10 -6 days +23:59:50
  20. 6 2013-01-01 2013-01-07 00:00:10 -7 days +23:59:50
  21. 7 2013-01-01 2013-01-08 00:00:10 -8 days +23:59:50
  22. 8 2013-01-01 2013-01-09 00:00:10 -9 days +23:59:50
  23. 9 2013-01-01 2013-01-10 00:00:10 -10 days +23:59:50
  24.  
  25. In [420]: store.append('dftd', dftd, data_columns=True)
  26.  
  27. In [421]: store.select('dftd', "C<'-3.5D'")
  28. Out[421]:
  29. A B C
  30. 4 2013-01-01 2013-01-05 00:00:10 -5 days +23:59:50
  31. 5 2013-01-01 2013-01-06 00:00:10 -6 days +23:59:50
  32. 6 2013-01-01 2013-01-07 00:00:10 -7 days +23:59:50
  33. 7 2013-01-01 2013-01-08 00:00:10 -8 days +23:59:50
  34. 8 2013-01-01 2013-01-09 00:00:10 -9 days +23:59:50
  35. 9 2013-01-01 2013-01-10 00:00:10 -10 days +23:59:50

Indexing

You can create/modify an index for a table with create_table_indexafter data is already in the table (after and append/putoperation). Creating a table index is highly encouraged. This willspeed your queries a great deal when you use a select with theindexed dimension as the where.

Note

Indexes are automagically created on the indexablesand any data columns you specify. This behavior can be turned off by passingindex=False to append.

  1. # we have automagically already created an index (in the first section)
  2. In [422]: i = store.root.df.table.cols.index.index
  3.  
  4. In [423]: i.optlevel, i.kind
  5. Out[423]: (6, 'medium')
  6.  
  7. # change an index by passing new parameters
  8. In [424]: store.create_table_index('df', optlevel=9, kind='full')
  9.  
  10. In [425]: i = store.root.df.table.cols.index.index
  11.  
  12. In [426]: i.optlevel, i.kind
  13. Out[426]: (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.

  1. In [427]: df_1 = pd.DataFrame(np.random.randn(10, 2), columns=list('AB'))
  2.  
  3. In [428]: df_2 = pd.DataFrame(np.random.randn(10, 2), columns=list('AB'))
  4.  
  5. In [429]: st = pd.HDFStore('appends.h5', mode='w')
  6.  
  7. In [430]: st.append('df', df_1, data_columns=['B'], index=False)
  8.  
  9. In [431]: st.append('df', df_2, data_columns=['B'], index=False)
  10.  
  11. In [432]: st.get_storer('df').table
  12. Out[432]:
  13. /df/table (Table(20,)) ''
  14. description := {
  15. "index": Int64Col(shape=(), dflt=0, pos=0),
  16. "values_block_0": Float64Col(shape=(1,), dflt=0.0, pos=1),
  17. "B": Float64Col(shape=(), dflt=0.0, pos=2)}
  18. byteorder := 'little'
  19. chunkshape := (2730,)

Then create the index when finished appending.

  1. In [433]: st.create_table_index('df', columns=['B'], optlevel=9, kind='full')
  2.  
  3. In [434]: st.get_storer('df').table
  4. Out[434]:
  5. /df/table (Table(20,)) ''
  6. description := {
  7. "index": Int64Col(shape=(), dflt=0, pos=0),
  8. "values_block_0": Float64Col(shape=(1,), dflt=0.0, pos=1),
  9. "B": Float64Col(shape=(), dflt=0.0, pos=2)}
  10. byteorder := 'little'
  11. chunkshape := (2730,)
  12. autoindex := True
  13. colindexes := {
  14. "B": Index(9, full, shuffle, zlib(1)).is_csi=True}
  15.  
  16. In [435]: st.close()

See here 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 the indexable 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 specify data_columns = True to force all columns tobe data_columns.

  1. In [436]: df_dc = df.copy()
  2.  
  3. In [437]: df_dc['string'] = 'foo'
  4.  
  5. In [438]: df_dc.loc[df_dc.index[4:6], 'string'] = np.nan
  6.  
  7. In [439]: df_dc.loc[df_dc.index[7:9], 'string'] = 'bar'
  8.  
  9. In [440]: df_dc['string2'] = 'cool'
  10.  
  11. In [441]: df_dc.loc[df_dc.index[1:3], ['B', 'C']] = 1.0
  12.  
  13. In [442]: df_dc
  14. Out[442]:
  15. A B C string string2
  16. 2000-01-01 -0.426936 -1.780784 0.322691 foo cool
  17. 2000-01-02 1.638174 1.000000 1.000000 foo cool
  18. 2000-01-03 -1.022803 1.000000 1.000000 foo cool
  19. 2000-01-04 1.767446 -1.305266 -0.378355 foo cool
  20. 2000-01-05 0.486743 0.954551 0.859671 NaN cool
  21. 2000-01-06 -1.170458 -1.211386 -0.852728 NaN cool
  22. 2000-01-07 -0.450781 1.064650 1.014927 foo cool
  23. 2000-01-08 -0.810399 0.254343 -0.875526 bar cool
  24.  
  25. # on-disk operations
  26. In [443]: store.append('df_dc', df_dc, data_columns=['B', 'C', 'string', 'string2'])
  27.  
  28. In [444]: store.select('df_dc', where='B > 0')
  29. Out[444]:
  30. A B C string string2
  31. 2000-01-02 1.638174 1.000000 1.000000 foo cool
  32. 2000-01-03 -1.022803 1.000000 1.000000 foo cool
  33. 2000-01-05 0.486743 0.954551 0.859671 NaN cool
  34. 2000-01-07 -0.450781 1.064650 1.014927 foo cool
  35. 2000-01-08 -0.810399 0.254343 -0.875526 bar cool
  36.  
  37. # getting creative
  38. In [445]: store.select('df_dc', 'B > 0 & C > 0 & string == foo')
  39. Out[445]:
  40. A B C string string2
  41. 2000-01-02 1.638174 1.00000 1.000000 foo cool
  42. 2000-01-03 -1.022803 1.00000 1.000000 foo cool
  43. 2000-01-07 -0.450781 1.06465 1.014927 foo cool
  44.  
  45. # this is in-memory version of this type of selection
  46. In [446]: df_dc[(df_dc.B > 0) & (df_dc.C > 0) & (df_dc.string == 'foo')]
  47. Out[446]:
  48. A B C string string2
  49. 2000-01-02 1.638174 1.00000 1.000000 foo cool
  50. 2000-01-03 -1.022803 1.00000 1.000000 foo cool
  51. 2000-01-07 -0.450781 1.06465 1.014927 foo cool
  52.  
  53. # we have automagically created this index and the B/C/string/string2
  54. # columns are stored separately as ``PyTables`` columns
  55. In [447]: store.root.df_dc.table
  56. Out[447]:
  57. /df_dc/table (Table(8,)) ''
  58. description := {
  59. "index": Int64Col(shape=(), dflt=0, pos=0),
  60. "values_block_0": Float64Col(shape=(1,), dflt=0.0, pos=1),
  61. "B": Float64Col(shape=(), dflt=0.0, pos=2),
  62. "C": Float64Col(shape=(), dflt=0.0, pos=3),
  63. "string": StringCol(itemsize=3, shape=(), dflt=b'', pos=4),
  64. "string2": StringCol(itemsize=4, shape=(), dflt=b'', pos=5)}
  65. byteorder := 'little'
  66. chunkshape := (1680,)
  67. autoindex := True
  68. colindexes := {
  69. "index": Index(6, medium, shuffle, zlib(1)).is_csi=False,
  70. "B": Index(6, medium, shuffle, zlib(1)).is_csi=False,
  71. "C": Index(6, medium, shuffle, zlib(1)).is_csi=False,
  72. "string": Index(6, medium, shuffle, zlib(1)).is_csi=False,
  73. "string2": 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

You can pass iterator=True or chunksize=number_in_a_chunkto select and select_as_multiple to return an iterator on the results.The default is 50,000 rows returned in a chunk.

  1. In [448]: for df in store.select('df', chunksize=3):
  2. .....: print(df)
  3. .....:
  4. A B C
  5. 2000-01-01 -0.426936 -1.780784 0.322691
  6. 2000-01-02 1.638174 -2.184251 0.049673
  7. 2000-01-03 -1.022803 0.889445 2.827717
  8. A B C
  9. 2000-01-04 1.767446 -1.305266 -0.378355
  10. 2000-01-05 0.486743 0.954551 0.859671
  11. 2000-01-06 -1.170458 -1.211386 -0.852728
  12. A B C
  13. 2000-01-07 -0.450781 1.064650 1.014927
  14. 2000-01-08 -0.810399 0.254343 -0.875526

Note

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

  1. for df in pd.read_hdf('store.h5', 'df', chunksize=3):
  2. print(df)

Note, that the chunksize keyword applies to the source 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.

  1. In [449]: dfeq = pd.DataFrame({'number': np.arange(1, 11)})
  2.  
  3. In [450]: dfeq
  4. Out[450]:
  5. number
  6. 0 1
  7. 1 2
  8. 2 3
  9. 3 4
  10. 4 5
  11. 5 6
  12. 6 7
  13. 7 8
  14. 8 9
  15. 9 10
  16.  
  17. In [451]: store.append('dfeq', dfeq, data_columns=['number'])
  18.  
  19. In [452]: def chunks(l, n):
  20. .....: return [l[i:i + n] for i in range(0, len(l), n)]
  21. .....:
  22.  
  23. In [453]: evens = [2, 4, 6, 8, 10]
  24.  
  25. In [454]: coordinates = store.select_as_coordinates('dfeq', 'number=evens')
  26.  
  27. In [455]: for c in chunks(coordinates, 2):
  28. .....: print(store.select('dfeq', where=c))
  29. .....:
  30. number
  31. 1 2
  32. 3 4
  33. number
  34. 5 6
  35. 7 8
  36. number
  37. 9 10

Advanced queries

Select a single column

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

  1. In [456]: store.select_column('df_dc', 'index')
  2. Out[456]:
  3. 0 2000-01-01
  4. 1 2000-01-02
  5. 2 2000-01-03
  6. 3 2000-01-04
  7. 4 2000-01-05
  8. 5 2000-01-06
  9. 6 2000-01-07
  10. 7 2000-01-08
  11. Name: index, dtype: datetime64[ns]
  12.  
  13. In [457]: store.select_column('df_dc', 'string')
  14. Out[457]:
  15. 0 foo
  16. 1 foo
  17. 2 foo
  18. 3 foo
  19. 4 NaN
  20. 5 NaN
  21. 6 foo
  22. 7 bar
  23. Name: 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.

  1. In [458]: df_coord = pd.DataFrame(np.random.randn(1000, 2),
  2. .....: index=pd.date_range('20000101', periods=1000))
  3. .....:
  4.  
  5. In [459]: store.append('df_coord', df_coord)
  6.  
  7. In [460]: c = store.select_as_coordinates('df_coord', 'index > 20020101')
  8.  
  9. In [461]: c
  10. Out[461]:
  11. Int64Index([732, 733, 734, 735, 736, 737, 738, 739, 740, 741,
  12. ...
  13. 990, 991, 992, 993, 994, 995, 996, 997, 998, 999],
  14. dtype='int64', length=268)
  15.  
  16. In [462]: store.select('df_coord', where=c)
  17. Out[462]:
  18. 0 1
  19. 2002-01-02 0.440865 -0.151651
  20. 2002-01-03 -1.195089 0.285093
  21. 2002-01-04 -0.925046 0.386081
  22. 2002-01-05 -1.942756 0.277699
  23. 2002-01-06 0.811776 0.528965
  24. ... ... ...
  25. 2002-09-22 1.061729 0.618085
  26. 2002-09-23 -0.209744 0.677197
  27. 2002-09-24 -1.808184 0.185667
  28. 2002-09-25 -0.208629 0.928603
  29. 2002-09-26 1.579717 -1.259530
  30.  
  31. [268 rows x 2 columns]
Selecting using a where mask

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

  1. In [463]: df_mask = pd.DataFrame(np.random.randn(1000, 2),
  2. .....: index=pd.date_range('20000101', periods=1000))
  3. .....:
  4.  
  5. In [464]: store.append('df_mask', df_mask)
  6.  
  7. In [465]: c = store.select_column('df_mask', 'index')
  8.  
  9. In [466]: where = c[pd.DatetimeIndex(c).month == 5].index
  10.  
  11. In [467]: store.select('df_mask', where=where)
  12. Out[467]:
  13. 0 1
  14. 2000-05-01 -1.199892 1.073701
  15. 2000-05-02 -1.058552 0.658487
  16. 2000-05-03 -0.015418 0.452879
  17. 2000-05-04 1.737818 0.426356
  18. 2000-05-05 -0.711668 -0.021266
  19. ... ... ...
  20. 2002-05-27 0.656196 0.993383
  21. 2002-05-28 -0.035399 -0.269286
  22. 2002-05-29 0.704503 2.574402
  23. 2002-05-30 -1.301443 2.770770
  24. 2002-05-31 -0.807599 0.420431
  25.  
  26. [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.

  1. In [468]: store.get_storer('df_dc').nrows
  2. Out[468]: 8

Multiple table queries

The methods append_to_multiple andselect_as_multiple 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.

The append_to_multiple method splits a given single DataFrameinto multiple tables according to d, a dictionary that maps thetable names to a list of ‘columns’ you want in that table. If _None_is used in place of a list, that table will have the remainingunspecified columns of the given DataFrame. The argument selectordefines which table is the selector table (which you can make queries from).The argument dropna 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 entirely np.NaN, that row will be dropped from all tables.

If dropna is False, THE USER IS RESPONSIBLE FOR SYNCHRONIZING THE TABLES.Remember that entirely np.Nan rows are not written to the HDFStore, so ifyou choose to call dropna=False, some tables may have more rows than others,and therefore select_as_multiple may not work or it may return unexpectedresults.

  1. In [469]: df_mt = pd.DataFrame(np.random.randn(8, 6),
  2. .....: index=pd.date_range('1/1/2000', periods=8),
  3. .....: columns=['A', 'B', 'C', 'D', 'E', 'F'])
  4. .....:
  5.  
  6. In [470]: df_mt['foo'] = 'bar'
  7.  
  8. In [471]: df_mt.loc[df_mt.index[1], ('A', 'B')] = np.nan
  9.  
  10. # you can also create the tables individually
  11. In [472]: store.append_to_multiple({'df1_mt': ['A', 'B'], 'df2_mt': None},
  12. .....: df_mt, selector='df1_mt')
  13. .....:
  14.  
  15. In [473]: store
  16. Out[473]:
  17. <class 'pandas.io.pytables.HDFStore'>
  18. File path: store.h5
  19.  
  20. # individual tables were created
  21. In [474]: store.select('df1_mt')
  22. Out[474]:
  23. A B
  24. 2000-01-01 0.475158 0.427905
  25. 2000-01-02 NaN NaN
  26. 2000-01-03 -0.201829 0.651656
  27. 2000-01-04 -0.766427 -1.852010
  28. 2000-01-05 1.642910 -0.055583
  29. 2000-01-06 0.187880 1.536245
  30. 2000-01-07 -1.801014 0.244721
  31. 2000-01-08 3.055033 -0.683085
  32.  
  33. In [475]: store.select('df2_mt')
  34. Out[475]:
  35. C D E F foo
  36. 2000-01-01 1.846285 -0.044826 0.074867 0.156213 bar
  37. 2000-01-02 0.446978 -0.323516 0.311549 -0.661368 bar
  38. 2000-01-03 -2.657254 0.649636 1.520717 1.604905 bar
  39. 2000-01-04 -0.201100 -2.107934 -0.450691 -0.748581 bar
  40. 2000-01-05 0.543779 0.111444 0.616259 -0.679614 bar
  41. 2000-01-06 0.831475 -0.566063 1.130163 -1.004539 bar
  42. 2000-01-07 0.745984 1.532560 0.229376 0.526671 bar
  43. 2000-01-08 -0.922301 2.760888 0.515474 -0.129319 bar
  44.  
  45. # as a multiple
  46. In [476]: store.select_as_multiple(['df1_mt', 'df2_mt'], where=['A>0', 'B>0'],
  47. .....: selector='df1_mt')
  48. .....:
  49. Out[476]:
  50. A B C D E F foo
  51. 2000-01-01 0.475158 0.427905 1.846285 -0.044826 0.074867 0.156213 bar
  52. 2000-01-06 0.187880 1.536245 0.831475 -0.566063 1.130163 -1.004539 bar

Delete from a table

You can delete from a table selectively by specifying a where. Indeleting rows, it is important to understand the PyTables deletesrows by erasing the rows, then moving the following data. Thusdeleting can potentially be a very expensive operation depending on theorientation of your data. 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 the indexables. Here’s asimple use case. You store panel-type data, with dates in themajor_axis and ids in the minor_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 the major_axis will befairly quick, as one chunk is removed, then the following data moved. Onthe other hand a delete operation on the minor_axis will be veryexpensive. In this case it would almost certainly be faster to rewritethe table using a where that selects all but the missing data.

Warning

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

To repack and clean the file, use ptrepack.

Notes & caveats

Compression

PyTables allows the stored data to be compressed. This applies toall kinds of stores, not just tables. Two parameters are used tocontrol compression: complevel and complib.

  • complevel specifies if and how hard data is to be compressed.
  • complevel=0 and complevel=None disablescompression and 0<complevel<10 enables compression.
  • complib specifies which compression library to use. If nothing is
  • specified the default library zlib is used. Acompression library usually optimizes for either goodcompression rates or speed and the results will depend onthe type of data. Which type ofcompression to choose depends on your specific needs anddata. The list of supported compression libraries:
  • zlib: The default compression library. A classic in terms of compression, achieves good compression rates but is somewhat slow.
  • lzo: Fast compression and decompression.
  • bzip2: Good compression rates.
  • blosc: Fast compression and decompression.

New in version 0.20.2: Support for alternative blosc compressors:

  • blosc:blosclz This is thedefault compressor for blosc
  • blosc:lz4:A compact, very popular and fast compressor.
  • blosc:lz4hc:A tweaked version of LZ4, produces bettercompression ratios at the expense of speed.
  • blosc:snappy:A popular compressor used in many places.
  • blosc:zlib: A classic;somewhat slower than the previous ones, butachieving better compression ratios.
  • blosc:zstd: Anextremely well balanced codec; it provides the bestcompression ratios among the others above, and atreasonably fast speed.

If complib is defined as something other than thelisted libraries a ValueError exception is issued.

Note

If the library specified with the complib option is missing on your platform,compression defaults to zlib without further ado.

Enable compression for all objects within the file:

  1. store_compressed = pd.HDFStore('store_compressed.h5', complevel=9,
  2. complib='blosc:blosclz')

Or on-the-fly compression (this only applies to tables) in stores where compression is not enabled:

  1. 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 supplied PyTables utilityptrepack. In addition, ptrepack can change compression levelsafter the fact.

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

Furthermore ptrepack in.h5 out.h5 will repack the file to allowyou to reuse previously deleted space. Alternatively, one can simplyremove the file and write again, or use the copy method.

Caveats

Warning

HDFStore is not-threadsafe for writing. The underlyingPyTables only supports concurrent reads (via threading orprocesses). If you need reading and writing at 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 use fsync() before releasing write locks. Forconvenience you can use store.flush(fsync=True) to do this for you.
  • Once a table is created 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 use tz_convert withthe updated timezone definition.

Warning

PyTables will show a NaturalNameWarning 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 a where clauseand are generally a bad idea.

DataTypes

HDFStore will map an object dtype to the PyTables 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, and WILL FAIL.

Categorical data

You can write data that contains category dtypes to a HDFStore.Queries work the same as if it was an object array. However, the category dtyped data isstored in a more efficient manner.

  1. In [477]: dfcat = pd.DataFrame({'A': pd.Series(list('aabbcdba')).astype('category'),
  2. .....: 'B': np.random.randn(8)})
  3. .....:
  4.  
  5. In [478]: dfcat
  6. Out[478]:
  7. A B
  8. 0 a 1.706605
  9. 1 a 1.373485
  10. 2 b -0.758424
  11. 3 b -0.116984
  12. 4 c -0.959461
  13. 5 d -1.517439
  14. 6 b -0.453150
  15. 7 a -0.827739
  16.  
  17. In [479]: dfcat.dtypes
  18. Out[479]:
  19. A category
  20. B float64
  21. dtype: object
  22.  
  23. In [480]: cstore = pd.HDFStore('cats.h5', mode='w')
  24.  
  25. In [481]: cstore.append('dfcat', dfcat, format='table', data_columns=['A'])
  26.  
  27. In [482]: result = cstore.select('dfcat', where="A in ['b', 'c']")
  28.  
  29. In [483]: result
  30. Out[483]:
  31. A B
  32. 2 b -0.758424
  33. 3 b -0.116984
  34. 4 c -0.959461
  35. 6 b -0.453150
  36.  
  37. In [484]: result.dtypes
  38. Out[484]:
  39. A category
  40. B float64
  41. dtype: object

String columns

min_itemsize

The underlying implementation of HDFStore 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 the HDFStore, in the first append. Subsequent appends,may introduce a string for a column larger than the column can hold, an Exception will be raised (otherwise 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.

Pass minitemsize 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 pass values as a key toallow all _indexables or data_columns to have this min_itemsize.

Passing a minitemsize dict will cause all passed columns to be created as _data_columns automatically.

Note

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

  1. In [485]: dfs = pd.DataFrame({'A': 'foo', 'B': 'bar'}, index=list(range(5)))
  2.  
  3. In [486]: dfs
  4. Out[486]:
  5. A B
  6. 0 foo bar
  7. 1 foo bar
  8. 2 foo bar
  9. 3 foo bar
  10. 4 foo bar
  11.  
  12. # A and B have a size of 30
  13. In [487]: store.append('dfs', dfs, min_itemsize=30)
  14.  
  15. In [488]: store.get_storer('dfs').table
  16. Out[488]:
  17. /dfs/table (Table(5,)) ''
  18. description := {
  19. "index": Int64Col(shape=(), dflt=0, pos=0),
  20. "values_block_0": StringCol(itemsize=30, shape=(2,), dflt=b'', pos=1)}
  21. byteorder := 'little'
  22. chunkshape := (963,)
  23. autoindex := True
  24. colindexes := {
  25. "index": Index(6, medium, shuffle, zlib(1)).is_csi=False}
  26.  
  27. # A is created as a data_column with a size of 30
  28. # B is size is calculated
  29. In [489]: store.append('dfs2', dfs, min_itemsize={'A': 30})
  30.  
  31. In [490]: store.get_storer('dfs2').table
  32. Out[490]:
  33. /dfs2/table (Table(5,)) ''
  34. description := {
  35. "index": Int64Col(shape=(), dflt=0, pos=0),
  36. "values_block_0": StringCol(itemsize=3, shape=(1,), dflt=b'', pos=1),
  37. "A": StringCol(itemsize=30, shape=(), dflt=b'', pos=2)}
  38. byteorder := 'little'
  39. chunkshape := (1598,)
  40. autoindex := True
  41. colindexes := {
  42. "index": Index(6, medium, shuffle, zlib(1)).is_csi=False,
  43. "A": Index(6, medium, shuffle, zlib(1)).is_csi=False}

nan_rep

String columns will serialize a np.nan (a missing value) with the nan_rep string representation. This defaults to the string value nan.You could inadvertently turn an actual nan value into a missing value.

  1. In [491]: dfss = pd.DataFrame({'A': ['foo', 'bar', 'nan']})
  2.  
  3. In [492]: dfss
  4. Out[492]:
  5. A
  6. 0 foo
  7. 1 bar
  8. 2 nan
  9.  
  10. In [493]: store.append('dfss', dfss)
  11.  
  12. In [494]: store.select('dfss')
  13. Out[494]:
  14. A
  15. 0 foo
  16. 1 bar
  17. 2 NaN
  18.  
  19. # here you need to specify a different nan rep
  20. In [495]: store.append('dfss2', dfss, nan_rep='_nan_')
  21.  
  22. In [496]: store.select('dfss2')
  23. Out[496]:
  24. A
  25. 0 foo
  26. 1 bar
  27. 2 nan

External compatibility

HDFStore writes table format objects in specific formats suitable forproducing loss-less round trips to pandas objects. For externalcompatibility, HDFStore can read native PyTables formattables.

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

  1. In [497]: df_for_r = pd.DataFrame({"first": np.random.rand(100),
  2. .....: "second": np.random.rand(100),
  3. .....: "class": np.random.randint(0, 2, (100, ))},
  4. .....: index=range(100))
  5. .....:
  6.  
  7. In [498]: df_for_r.head()
  8. Out[498]:
  9. first second class
  10. 0 0.366979 0.794525 0
  11. 1 0.296639 0.635178 1
  12. 2 0.395751 0.359693 0
  13. 3 0.484648 0.970016 1
  14. 4 0.810047 0.332303 0
  15.  
  16. In [499]: store_export = pd.HDFStore('export.h5')
  17.  
  18. In [500]: store_export.append('df_for_r', df_for_r, data_columns=df_dc.columns)
  19.  
  20. In [501]: store_export
  21. Out[501]:
  22. <class 'pandas.io.pytables.HDFStore'>
  23. File path: export.h5

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

  1. # Load values and column names for all datasets from corresponding nodes and
  2. # insert them into one data.frame object.
  3.  
  4. library(rhdf5)
  5.  
  6. loadhdf5data <- function(h5File) {
  7.  
  8. listing <- h5ls(h5File)
  9. # Find all data nodes, values are stored in *_values and corresponding column
  10. # titles in *_items
  11. data_nodes <- grep("_values", listing$name)
  12. name_nodes <- grep("_items", listing$name)
  13. data_paths = paste(listing$group[data_nodes], listing$name[data_nodes], sep = "/")
  14. name_paths = paste(listing$group[name_nodes], listing$name[name_nodes], sep = "/")
  15. columns = list()
  16. for (idx in seq(data_paths)) {
  17. # NOTE: matrices returned by h5read have to be transposed to obtain
  18. # required Fortran order!
  19. data <- data.frame(t(h5read(h5File, data_paths[idx])))
  20. names <- t(h5read(h5File, name_paths[idx]))
  21. entry <- data.frame(data)
  22. colnames(entry) <- names
  23. columns <- append(columns, entry)
  24. }
  25.  
  26. data <- data.frame(columns)
  27.  
  28. return(data)
  29. }

Now you can import the DataFrame into R:

  1. > data = loadhdf5data("transfer.hdf5")
  2. > head(data)
  3. first second class
  4. 1 0.4170220047 0.3266449 0
  5. 2 0.7203244934 0.5270581 0
  6. 3 0.0001143748 0.8859421 1
  7. 4 0.3023325726 0.3572698 1
  8. 5 0.1467558908 0.9085352 1
  9. 6 0.0923385948 0.6233601 1

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 multiple DataFrame objects to asingle HDF5 file.

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 pass chunksize=<int> to append, specifying thewrite chunksize (default is 50000). This will significantly loweryour memory usage on writing.
  • You can pass expectedrows=<int> to the first append,to set the TOTAL number of expected rows that PyTables 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)
  • A PerformanceWarning 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.

Feather

New in version 0.20.0.

Feather provides binary columnar serialization for data frames. It is designed to make reading and writing dataframes efficient, and to make sharing data across data analysis languages easy.

Feather is designed to faithfully serialize and de-serialize DataFrames, supporting all of the pandasdtypes, including extension dtypes such as categorical and datetime with tz.

Several caveats.

  • This is a newer library, and the format, though stable, is not guaranteed to be backward compatibleto the earlier versions.
  • The format will NOT write an Index, or MultiIndex for theDataFrame and will raise an error if a non-default one is provided. Youcan .reset_index() to store the index or .reset_index(drop=True) toignore it.
  • Duplicate column names and non-string columns names are not supported
  • Non supported types include Period and actual Python object types. These will raise a helpful error messageon an attempt at serialization.

See the Full Documentation.

  1. In [502]: df = pd.DataFrame({'a': list('abc'),
  2. .....: 'b': list(range(1, 4)),
  3. .....: 'c': np.arange(3, 6).astype('u1'),
  4. .....: 'd': np.arange(4.0, 7.0, dtype='float64'),
  5. .....: 'e': [True, False, True],
  6. .....: 'f': pd.Categorical(list('abc')),
  7. .....: 'g': pd.date_range('20130101', periods=3),
  8. .....: 'h': pd.date_range('20130101', periods=3, tz='US/Eastern'),
  9. .....: 'i': pd.date_range('20130101', periods=3, freq='ns')})
  10. .....:
  11.  
  12. In [503]: df
  13. Out[503]:
  14. a b c d e f g h i
  15. 0 a 1 3 4.0 True a 2013-01-01 2013-01-01 00:00:00-05:00 2013-01-01 00:00:00.000000000
  16. 1 b 2 4 5.0 False b 2013-01-02 2013-01-02 00:00:00-05:00 2013-01-01 00:00:00.000000001
  17. 2 c 3 5 6.0 True c 2013-01-03 2013-01-03 00:00:00-05:00 2013-01-01 00:00:00.000000002
  18.  
  19. In [504]: df.dtypes
  20. Out[504]:
  21. a object
  22. b int64
  23. c uint8
  24. d float64
  25. e bool
  26. f category
  27. g datetime64[ns]
  28. h datetime64[ns, US/Eastern]
  29. i datetime64[ns]
  30. dtype: object

Write to a feather file.

  1. In [505]: df.to_feather('example.feather')

Read from a feather file.

  1. In [506]: result = pd.read_feather('example.feather')
  2.  
  3. In [507]: result
  4. Out[507]:
  5. a b c d e f g h i
  6. 0 a 1 3 4.0 True a 2013-01-01 2013-01-01 00:00:00-05:00 2013-01-01 00:00:00.000000000
  7. 1 b 2 4 5.0 False b 2013-01-02 2013-01-02 00:00:00-05:00 2013-01-01 00:00:00.000000001
  8. 2 c 3 5 6.0 True c 2013-01-03 2013-01-03 00:00:00-05:00 2013-01-01 00:00:00.000000002
  9.  
  10. # we preserve dtypes
  11. In [508]: result.dtypes
  12. Out[508]:
  13. a object
  14. b int64
  15. c uint8
  16. d float64
  17. e bool
  18. f category
  19. g datetime64[ns]
  20. h datetime64[ns, US/Eastern]
  21. i datetime64[ns]
  22. dtype: object

Parquet

New in version 0.21.0.

Apache Parquet provides a partitioned binary columnar serialization for data frames. It is designed tomake reading and writing data frames efficient, and to make sharing data across data analysislanguages easy. Parquet can use a variety of compression techniques to shrink the file size as much as possiblewhile still maintaining good read performance.

Parquet is designed to faithfully serialize and de-serialize DataFrame s, supporting all of the pandasdtypes, including extension dtypes such as datetime with tz.

Several caveats.

  • Duplicate column names and non-string columns names are not supported.
  • The pyarrow engine always writes the index to the output, but fastparquet only writes non-defaultindexes. This extra column can cause problems for non-Pandas consumers that are not expecting it. You canforce including or omitting indexes with the index argument, regardless of the underlying engine.
  • Index level names, if specified, must be strings.
  • Categorical dtypes can be serialized to parquet, but will de-serialize as object dtype.
  • Non supported types include Period and actual Python object types. These will raise a helpful error messageon an attempt at serialization.

You can specify an engine to direct the serialization. This can be one of pyarrow, or fastparquet, or auto.If the engine is NOT specified, then the pd.options.io.parquet.engine option is checked; if this is also auto,then pyarrow is tried, and falling back to fastparquet.

See the documentation for pyarrow and fastparquet.

Note

These engines are very similar and should read/write nearly identical parquet format files.Currently pyarrow does not support timedelta data, fastparquet>=0.1.4 supports timezone aware datetimes.These libraries differ by having different underlying dependencies (fastparquet by using numba, while pyarrow uses a c-library).

  1. In [509]: df = pd.DataFrame({'a': list('abc'),
  2. .....: 'b': list(range(1, 4)),
  3. .....: 'c': np.arange(3, 6).astype('u1'),
  4. .....: 'd': np.arange(4.0, 7.0, dtype='float64'),
  5. .....: 'e': [True, False, True],
  6. .....: 'f': pd.date_range('20130101', periods=3),
  7. .....: 'g': pd.date_range('20130101', periods=3, tz='US/Eastern')})
  8. .....:
  9.  
  10. In [510]: df
  11. Out[510]:
  12. a b c d e f g
  13. 0 a 1 3 4.0 True 2013-01-01 2013-01-01 00:00:00-05:00
  14. 1 b 2 4 5.0 False 2013-01-02 2013-01-02 00:00:00-05:00
  15. 2 c 3 5 6.0 True 2013-01-03 2013-01-03 00:00:00-05:00
  16.  
  17. In [511]: df.dtypes
  18. Out[511]:
  19. a object
  20. b int64
  21. c uint8
  22. d float64
  23. e bool
  24. f datetime64[ns]
  25. g datetime64[ns, US/Eastern]
  26. dtype: object

Write to a parquet file.

  1. In [512]: df.to_parquet('example_pa.parquet', engine='pyarrow')
  2.  
  3. In [513]: df.to_parquet('example_fp.parquet', engine='fastparquet')

Read from a parquet file.

  1. In [514]: result = pd.read_parquet('example_fp.parquet', engine='fastparquet')
  2.  
  3. In [515]: result = pd.read_parquet('example_pa.parquet', engine='pyarrow')
  4.  
  5. In [516]: result.dtypes
  6. Out[516]:
  7. a object
  8. b int64
  9. c uint8
  10. d float64
  11. e bool
  12. f datetime64[ns]
  13. g datetime64[ns, US/Eastern]
  14. dtype: object

Read only certain columns of a parquet file.

  1. In [517]: result = pd.read_parquet('example_fp.parquet',
  2. .....: engine='fastparquet', columns=['a', 'b'])
  3. .....:
  4.  
  5. In [518]: result = pd.read_parquet('example_pa.parquet',
  6. .....: engine='pyarrow', columns=['a', 'b'])
  7. .....:
  8.  
  9. In [519]: result.dtypes
  10. Out[519]:
  11. a object
  12. b int64
  13. dtype: object

Handling indexes

Serializing a DataFrame to parquet may include the implicit index as one ormore columns in the output file. Thus, this code:

  1. In [520]: df = pd.DataFrame({'a': [1, 2], 'b': [3, 4]})
  2.  
  3. In [521]: df.to_parquet('test.parquet', engine='pyarrow')

creates a parquet file with three columns if you use pyarrow for serialization:a, b, and index_level_0. If you’re using fastparquet, theindex may or may notbe written to the file.

This unexpected extra column causes some databases like Amazon Redshift to rejectthe file, because that column doesn’t exist in the target table.

If you want to omit a dataframe’s indexes when writing, pass index=False toto_parquet():

  1. In [522]: df.to_parquet('test.parquet', index=False)

This creates a parquet file with just the two expected columns, a and b.If your DataFrame has a custom index, you won’t get it back when you loadthis file into a DataFrame.

Passing index=True will always write the index, even if that’s not theunderlying engine’s default behavior.

Partitioning Parquet files

New in version 0.24.0.

Parquet supports partitioning of data based on the values of one or more columns.

  1. In [523]: df = pd.DataFrame({'a': [0, 0, 1, 1], 'b': [0, 1, 0, 1]})
  2.  
  3. In [524]: df.to_parquet(fname='test', engine='pyarrow',
  4. .....: partition_cols=['a'], compression=None)
  5. .....:

The fname specifies the parent directory to which data will be saved.The partition_cols are the column names by which the dataset will be partitioned.Columns are partitioned in the order they are given. The partition splits aredetermined by the unique values in the partition columns.The above example creates a partitioned dataset that may look like:

  1. test
  2. ├── a=0
  3. ├── 0bac803e32dc42ae83fddfd029cbdebc.parquet
  4. └── ...
  5. └── a=1
  6. ├── e6ab24a4f45147b49b54a662f0c412a3.parquet
  7. └── ...

SQL queries

The pandas.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 are psycopg2for PostgreSQL or pymysql for MySQL.For SQLite this isincluded in Python’s standard library by default.You can find an overview of supported drivers for each SQL dialect in theSQLAlchemy docs.

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 the PythonDB-API.

See also some cookbook 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(self, name, con[, schema, …])Write records stored in a DataFrame to a SQL database.

Note

The function read_sql() is a convenience wrapper aroundread_sql_table() and read_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 the SQlite SQL databaseengine. You can use a temporary SQLite database where data are stored in“memory”.

To connect with SQLAlchemy you use the create_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 on create_engine() and the URI formatting, see the examplesbelow and the SQLAlchemy documentation

  1. In [525]: from sqlalchemy import create_engine
  2.  
  3. # Create your engine.
  4. In [526]: engine = create_engine('sqlite:///:memory:')

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

  1. with engine.connect() as conn, conn.begin():
  2. data = pd.read_sql_table('data', conn)

Writing DataFrames

Assuming the following data is in a DataFrame data, we can insert it intothe database using to_sql().

idDateCol_1Col_2Col_3
262012-10-18X25.7True
422012-10-19Y-12.4False
632012-10-20Z5.73True
  1. In [527]: data
  2. Out[527]:
  3. id Date Col_1 Col_2 Col_3
  4. 0 26 2010-10-18 X 27.50 True
  5. 1 42 2010-10-19 Y -12.50 False
  6. 2 63 2010-10-20 Z 5.73 True
  7.  
  8. In [528]: 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 calling to_sql. For example, the followingwrites data to the database in batches of 1000 rows at a time:

  1. In [529]: 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 the dtype argument. This argument needs adictionary mapping column names to SQLAlchemy types (or strings for the sqlite3fallback mode).For example, specifying to use the sqlalchemy String type instead of thedefault Text type for string columns:

  1. In [530]: from sqlalchemy.types import String
  2.  
  3. In [531]: 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 type timedelta64 will be written as integervalues as nanoseconds to the database and a warning will be raised.

Note

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

Datetime data types

Using SQLAlchemy, to_sql() is capable of writingdatetime data that is timezone naive or timezone aware. However, the resultingdata stored in the database ultimately depends on the supported data typefor datetime data of the database system being used.

The following table lists supported data types for datetime data for somecommon databases. Other database dialects may have different data types fordatetime data.

DatabaseSQL Datetime TypesTimezone Support
SQLiteTEXTNo
MySQLTIMESTAMP or DATETIMENo
PostgreSQLTIMESTAMP or TIMESTAMP WITH TIME ZONEYes

When writing timezone aware data to databases that do not support timezones,the data will be written as timezone naive timestamps that are in local timewith respect to the timezone.

read_sql_table() is also capable of reading datetime data that istimezone aware or naive. When reading TIMESTAMP WITH TIME ZONE types, pandaswill convert the data to UTC.

Insertion method

New in version 0.24.0.

The parameter method controls the SQL insertion clause used.Possible values are:

  • None: Uses standard SQL INSERT clause (one per row).
  • 'multi': Pass multiple values in a single INSERT clause.It uses a special SQL syntax not supported by all backends.This usually provides better performance for analytic databaseslike Presto and Redshift, but has worse performance fortraditional SQL backend if the table contains many columns.For more information check the SQLAlchemy documention.
  • callable with signature (pd_table, conn, keys, data_iter):This can be used to implement a more performant insertion method based onspecific backend dialect features.

Example of a callable using PostgreSQL COPY clause:

  1. # Alternative to_sql() *method* for DBs that support COPY FROM
  2. import csv
  3. from io import StringIO
  4.  
  5. def psql_insert_copy(table, conn, keys, data_iter):
  6. # gets a DBAPI connection that can provide a cursor
  7. dbapi_conn = conn.connection
  8. with dbapi_conn.cursor() as cur:
  9. s_buf = StringIO()
  10. writer = csv.writer(s_buf)
  11. writer.writerows(data_iter)
  12. s_buf.seek(0)
  13.  
  14. columns = ', '.join('"{}"'.format(k) for k in keys)
  15. if table.schema:
  16. table_name = '{}.{}'.format(table.schema, table.name)
  17. else:
  18. table_name = table.name
  19.  
  20. sql = 'COPY {} ({}) FROM STDIN WITH CSV'.format(
  21. table_name, columns)
  22. cur.copy_expert(sql=sql, file=s_buf)

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 use read_sql_table(), you must have theSQLAlchemy optional dependency installed.

  1. In [532]: pd.read_sql_table('data', engine)
  2. Out[532]:
  3. index id Date Col_1 Col_2 Col_3
  4. 0 0 26 2010-10-18 X 27.50 True
  5. 1 1 42 2010-10-19 Y -12.50 False
  6. 2 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.

  1. In [533]: pd.read_sql_table('data', engine, index_col='id')
  2. Out[533]:
  3. index Date Col_1 Col_2 Col_3
  4. id
  5. 26 0 2010-10-18 X 27.50 True
  6. 42 1 2010-10-19 Y -12.50 False
  7. 63 2 2010-10-20 Z 5.73 True
  8.  
  9. In [534]: pd.read_sql_table('data', engine, columns=['Col_1', 'Col_2'])
  10. Out[534]:
  11. Col_1 Col_2
  12. 0 X 27.50
  13. 1 Y -12.50
  14. 2 Z 5.73

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

  1. In [535]: pd.read_sql_table('data', engine, parse_dates=['Date'])
  2. Out[535]:
  3. index id Date Col_1 Col_2 Col_3
  4. 0 0 26 2010-10-18 X 27.50 True
  5. 1 1 42 2010-10-19 Y -12.50 False
  6. 2 2 63 2010-10-20 Z 5.73 True

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

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

You can check if a table exists using has_table()

Schema support

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

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

Querying

You can query using raw SQL in the read_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.

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

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

  1. In [537]: pd.read_sql_query("SELECT id, Col_1, Col_2 FROM data WHERE id = 42;", engine)
  2. Out[537]:
  3. id Col_1 Col_2
  4. 0 42 Y -12.5

The read_sql_query() function supports a chunksize argument.Specifying this will return an iterator through chunks of the query result:

  1. In [538]: df = pd.DataFrame(np.random.randn(20, 3), columns=list('abc'))
  2.  
  3. In [539]: df.to_sql('data_chunks', engine, index=False)
  1. In [540]: for chunk in pd.read_sql_query("SELECT * FROM data_chunks",
  2. .....: engine, chunksize=5):
  3. .....: print(chunk)
  4. .....:
  5. a b c
  6. 0 -0.900850 -0.323746 0.037100
  7. 1 0.057533 -0.032842 0.550902
  8. 2 1.026623 1.035455 -0.965140
  9. 3 -0.252405 -1.255987 0.639156
  10. 4 1.076701 -0.309155 -0.800182
  11. a b c
  12. 0 -0.206623 0.496077 -0.219935
  13. 1 0.631362 -1.166743 1.808368
  14. 2 0.023531 0.987573 0.471400
  15. 3 -0.982250 -0.192482 1.195452
  16. 4 -1.758855 0.477551 1.412567
  17. a b c
  18. 0 -1.120570 1.232764 0.417814
  19. 1 1.688089 -0.037645 -0.269582
  20. 2 0.646823 -0.603366 1.592966
  21. 3 0.724019 -0.515606 -0.180920
  22. 4 0.038244 -2.292866 -0.114634
  23. a b c
  24. 0 -0.970230 -0.963257 -0.128304
  25. 1 0.498621 -1.496506 0.701471
  26. 2 -0.272608 -0.119424 -0.882023
  27. 3 -0.253477 0.714395 0.664179
  28. 4 0.897140 0.455791 1.549590

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 calling execute on theSQLAlchemy engine or db connection object. Again, you must use the SQL syntaxvariant appropriate for your database.

  1. from pandas.io import sql
  2. sql.execute('SELECT * FROM table_name', engine)
  3. sql.execute('INSERT INTO table_name VALUES(?, ?, ?)', engine,
  4. params=[('id', 1, 12.2, True)])

Engine connection examples

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

  1. from sqlalchemy import create_engine
  2.  
  3. engine = create_engine('postgresql://scott:[email protected]:5432/mydatabase')
  4.  
  5. engine = create_engine('mysql+mysqldb://scott:[email protected]/foo')
  6.  
  7. engine = create_engine('oracle://scott:[email protected]:1521/sidname')
  8.  
  9. engine = create_engine('mssql+pyodbc://mydsn')
  10.  
  11. # sqlite://<nohostname>/<path>
  12. # where <path> is relative:
  13. engine = create_engine('sqlite:///foo.db')
  14.  
  15. # or absolute, starting with a slash:
  16. engine = create_engine('sqlite:////absolute/path/to/foo.db')

For more information see the examples the SQLAlchemy documentation

Advanced SQLAlchemy queries

You can use SQLAlchemy constructs to describe your query.

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

  1. In [541]: import sqlalchemy as sa
  2.  
  3. In [542]: pd.read_sql(sa.text('SELECT * FROM data where Col_1=:col1'),
  4. .....: engine, params={'col1': 'X'})
  5. .....:
  6. Out[542]:
  7. index id Date Col_1 Col_2 Col_3
  8. 0 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

  1. In [543]: metadata = sa.MetaData()
  2.  
  3. In [544]: data_table = sa.Table('data', metadata,
  4. .....: sa.Column('index', sa.Integer),
  5. .....: sa.Column('Date', sa.DateTime),
  6. .....: sa.Column('Col_1', sa.String),
  7. .....: sa.Column('Col_2', sa.Float),
  8. .....: sa.Column('Col_3', sa.Boolean),
  9. .....: )
  10. .....:
  11.  
  12. In [545]: pd.read_sql(sa.select([data_table]).where(data_table.c.Col_3 is True), engine)
  13. Out[545]:
  14. Empty DataFrame
  15. Columns: [index, Date, Col_1, Col_2, Col_3]
  16. Index: []

You can combine SQLAlchemy expressions with parameters passed to read_sql() using sqlalchemy.bindparam()

  1. In [546]: import datetime as dt
  2.  
  3. In [547]: expr = sa.select([data_table]).where(data_table.c.Date > sa.bindparam('date'))
  4.  
  5. In [548]: pd.read_sql(expr, engine, params={'date': dt.datetime(2010, 10, 18)})
  6. Out[548]:
  7. index Date Col_1 Col_2 Col_3
  8. 0 1 2010-10-19 Y -12.50 False
  9. 1 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 the PythonDB-API.

You can create connections like so:

  1. import sqlite3
  2. con = sqlite3.connect(':memory:')

And then issue the following queries:

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

Google BigQuery

Warning

Starting in 0.20.0, pandas has split off Google BigQuery support into theseparate package pandas-gbq. You can pip install pandas-gbq to get it.

The pandas-gbq package provides functionality to read/write from Google BigQuery.

pandas integrates with this external package. if pandas-gbq is installed, you canuse the pandas methods pd.read_gbq and DataFrame.to_gbq, which will call therespective functions from pandas-gbq.

Full documentation can be found here.

Stata format

Writing to stata format

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

  1. In [549]: df = pd.DataFrame(np.random.randn(10, 2), columns=list('AB'))
  2.  
  3. In [550]: df.to_stata('stata.dta')

Stata data files have limited data type support; only strings with244 or fewer characters, int8, int16, int32, float32and float64 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 to int16. nan values in floating points datatypes are stored as the basic missing data type (. in Stata).

Note

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

The Stata writer gracefully handles other data types including int64,bool, uint8, uint16, uint32 by casting tothe smallest supported type that can represent the data. For example, datawith a type of uint8 will be cast to int8 if all values are less than100 (the upper bound for non-missing int8 data in Stata), or, if values areoutside of this range, the variable is cast to int16.

Warning

Conversion from int64 to float64 may result in a loss of precisionif int64 values are larger than 2**53.

Warning

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

Reading from Stata format

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

  1. In [551]: pd.read_stata('stata.dta')
  2. Out[551]:
  3. index A B
  4. 0 0 1.031231 0.196447
  5. 1 1 0.190188 0.619078
  6. 2 2 0.036658 -0.100501
  7. 3 3 0.201772 1.763002
  8. 4 4 0.454977 -1.958922
  9. 5 5 -0.628529 0.133171
  10. 6 6 -1.274374 2.518925
  11. 7 7 -0.517547 -0.360773
  12. 8 8 0.877961 -1.881598
  13. 9 9 -0.699067 -1.566913

Specifying a chunksize yields aStataReader instance that can be used toread chunksize lines from the file at a time. The StataReaderobject can be used as an iterator.

  1. In [552]: reader = pd.read_stata('stata.dta', chunksize=3)
  2.  
  3. In [553]: for df in reader:
  4. .....: print(df.shape)
  5. .....:
  6. (3, 3)
  7. (3, 3)
  8. (3, 3)
  9. (1, 3)

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

  1. In [554]: reader = pd.read_stata('stata.dta', iterator=True)
  2.  
  3. In [555]: chunk1 = reader.read(5)
  4.  
  5. In [556]: chunk2 = reader.read(5)

Currently the index is retrieved as a column.

The parameter convert_categoricals indicates whether value labels should beread and used to create a Categorical variable from them. Value labels canalso be retrieved by the function value_labels, which requires read()to be called before use.

The parameter convert_missing indicates whether missing valuerepresentations in Stata should be preserved. If False (the default),missing values are represented as np.nan. If True, missing values arerepresented using StataMissingValue objects, and columns containing missingvalues will have object data type.

Note

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

Note

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

Categorical data

Categorical data can be exported to Stata 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 a Categorical and information about whether the variable is orderedis lost when exporting.

Warning

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

Labeled data can similarly be imported from Stata data files as Categoricalvariables using the keyword argument convert_categoricals (True by default).The keyword argument order_categoricals (True by default) determineswhether imported Categorical variables are ordered.

Note

When importing categorical data, the values of the variables in the Stata_data file are not preserved since Categorical variables alwaysuse integer data types between -1 and n-1 where n is the numberof categories. If the original values in the _Stata data file are required,these can be imported by setting convertcategoricals=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 original _Stata data values and the category codes of importedCategorical variables: missing values are assigned code -1, and thesmallest original value is assigned 0, the second smallest is assigned1 and so on until the largest original value is assigned the code n-1.

Note

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

SAS formats

The top-level function read_sas() can read (but not write) SASxport (.XPT) and (since v0.18.0) SAS7BDAT (.sas7bdat) format files.

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 a DataFrame.

Specify a chunksize or use iterator=True to obtain readerobjects (XportReader or SAS7BDATReader) for incrementallyreading the file. The reader objects also have attributes thatcontain additional information about the file and its variables.

Read a SAS7BDAT file:

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

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

  1. def do_something(chunk):
  2. pass
  3.  
  4. rdr = pd.read_sas('sas_xport.xpt', chunk=100000)
  5. for chunk in rdr:
  6. do_something(chunk)

The specification 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 pandas0.20.3. Timings are machine dependent and small differences should beignored.

  1. In [1]: sz = 1000000
  2. In [2]: df = pd.DataFrame({'A': np.random.randn(sz), 'B': [1] * sz})
  3.  
  4. In [3]: df.info()
  5. <class 'pandas.core.frame.DataFrame'>
  6. RangeIndex: 1000000 entries, 0 to 999999
  7. Data columns (total 2 columns):
  8. A 1000000 non-null float64
  9. B 1000000 non-null int64
  10. dtypes: float64(1), int64(1)
  11. memory usage: 15.3 MB

Given the next test set:

  1. from numpy.random import randn
  2.  
  3. sz = 1000000
  4. df = pd.DataFrame({'A': randn(sz), 'B': [1] * sz})
  5.  
  6.  
  7. def test_sql_write(df):
  8. if os.path.exists('test.sql'):
  9. os.remove('test.sql')
  10. sql_db = sqlite3.connect('test.sql')
  11. df.to_sql(name='test_table', con=sql_db)
  12. sql_db.close()
  13.  
  14.  
  15. def test_sql_read():
  16. sql_db = sqlite3.connect('test.sql')
  17. pd.read_sql_query("select * from test_table", sql_db)
  18. sql_db.close()
  19.  
  20.  
  21. def test_hdf_fixed_write(df):
  22. df.to_hdf('test_fixed.hdf', 'test', mode='w')
  23.  
  24.  
  25. def test_hdf_fixed_read():
  26. pd.read_hdf('test_fixed.hdf', 'test')
  27.  
  28.  
  29. def test_hdf_fixed_write_compress(df):
  30. df.to_hdf('test_fixed_compress.hdf', 'test', mode='w', complib='blosc')
  31.  
  32.  
  33. def test_hdf_fixed_read_compress():
  34. pd.read_hdf('test_fixed_compress.hdf', 'test')
  35.  
  36.  
  37. def test_hdf_table_write(df):
  38. df.to_hdf('test_table.hdf', 'test', mode='w', format='table')
  39.  
  40.  
  41. def test_hdf_table_read():
  42. pd.read_hdf('test_table.hdf', 'test')
  43.  
  44.  
  45. def test_hdf_table_write_compress(df):
  46. df.to_hdf('test_table_compress.hdf', 'test', mode='w',
  47. complib='blosc', format='table')
  48.  
  49.  
  50. def test_hdf_table_read_compress():
  51. pd.read_hdf('test_table_compress.hdf', 'test')
  52.  
  53.  
  54. def test_csv_write(df):
  55. df.to_csv('test.csv', mode='w')
  56.  
  57.  
  58. def test_csv_read():
  59. pd.read_csv('test.csv', index_col=0)
  60.  
  61.  
  62. def test_feather_write(df):
  63. df.to_feather('test.feather')
  64.  
  65.  
  66. def test_feather_read():
  67. pd.read_feather('test.feather')
  68.  
  69.  
  70. def test_pickle_write(df):
  71. df.to_pickle('test.pkl')
  72.  
  73.  
  74. def test_pickle_read():
  75. pd.read_pickle('test.pkl')
  76.  
  77.  
  78. def test_pickle_write_compress(df):
  79. df.to_pickle('test.pkl.compress', compression='xz')
  80.  
  81.  
  82. def test_pickle_read_compress():
  83. pd.read_pickle('test.pkl.compress', compression='xz')

When writing, the top-three functions in terms of speed are aretest_pickle_write, test_feather_write and test_hdf_fixed_write_compress.

  1. In [14]: %timeit test_sql_write(df)
  2. 2.37 s ± 36.6 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
  3.  
  4. In [15]: %timeit test_hdf_fixed_write(df)
  5. 194 ms ± 65.9 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)
  6.  
  7. In [26]: %timeit test_hdf_fixed_write_compress(df)
  8. 119 ms ± 2.15 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)
  9.  
  10. In [16]: %timeit test_hdf_table_write(df)
  11. 623 ms ± 125 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
  12.  
  13. In [27]: %timeit test_hdf_table_write_compress(df)
  14. 563 ms ± 23.7 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
  15.  
  16. In [17]: %timeit test_csv_write(df)
  17. 3.13 s ± 49.9 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
  18.  
  19. In [30]: %timeit test_feather_write(df)
  20. 103 ms ± 5.88 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)
  21.  
  22. In [31]: %timeit test_pickle_write(df)
  23. 109 ms ± 3.72 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)
  24.  
  25. In [32]: %timeit test_pickle_write_compress(df)
  26. 3.33 s ± 55.2 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)

When reading, the top three are test_feather_read, test_pickle_read andtest_hdf_fixed_read.

  1. In [18]: %timeit test_sql_read()
  2. 1.35 s ± 14.7 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
  3.  
  4. In [19]: %timeit test_hdf_fixed_read()
  5. 14.3 ms ± 438 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
  6.  
  7. In [28]: %timeit test_hdf_fixed_read_compress()
  8. 23.5 ms ± 672 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)
  9.  
  10. In [20]: %timeit test_hdf_table_read()
  11. 35.4 ms ± 314 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)
  12.  
  13. In [29]: %timeit test_hdf_table_read_compress()
  14. 42.6 ms ± 2.1 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)
  15.  
  16. In [22]: %timeit test_csv_read()
  17. 516 ms ± 27.1 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
  18.  
  19. In [33]: %timeit test_feather_read()
  20. 4.06 ms ± 115 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
  21.  
  22. In [34]: %timeit test_pickle_read()
  23. 6.5 ms ± 172 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
  24.  
  25. In [35]: %timeit test_pickle_read_compress()
  26. 588 ms ± 3.57 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)

Space on disk (in bytes)

  1. 34816000 Aug 21 18:00 test.sql
  2. 24009240 Aug 21 18:00 test_fixed.hdf
  3. 7919610 Aug 21 18:00 test_fixed_compress.hdf
  4. 24458892 Aug 21 18:00 test_table.hdf
  5. 8657116 Aug 21 18:00 test_table_compress.hdf
  6. 28520770 Aug 21 18:00 test.csv
  7. 16000248 Aug 21 18:00 test.feather
  8. 16000848 Aug 21 18:00 test.pkl
  9. 7554108 Aug 21 18:00 test.pkl.compress