IO tools (text, CSV, …)
The pandas I/O API is a set of top level reader functions accessed like pandas.read_csv() that generally return a pandas object. The corresponding writer functions are object methods that are accessed like DataFrame.to_csv(). Below is a table containing available readers and writers.
Format Type
Data Description
Reader
Writer
Here is an informal performance comparison for some of these IO methods.
Note
For examples that use the StringIO class, make sure you import it according to your Python version, i.e. from StringIO import StringIO for Python 2 and from io import StringIO for Python 3.
CSV & text files
The workhorse function for reading text files (a.k.a. flat files) is read_csv(). See the cookbook for some advanced strategies.
Parsing options
read_csv() accepts the following common arguments:
Basic
filepath_or_buffervarious
Either a path to a file (a str, pathlib.Path, or py._path.local.LocalPath), URL (including http, ftp, and S3 locations), or any object with a read() method (such as an open file or StringIO).sepstr, defaults to ',' for read_csv(), \t for read_table()
Delimiter to use. If sep is None, the C engine cannot automatically detect the separator, but the Python parsing engine can, meaning the latter will be used and automatically detect the separator by Python’s builtin sniffer tool, csv.Sniffer. In addition, separators longer than 1 character and different from '\s+' will be interpreted as regular expressions and will also force the use of the Python parsing engine. Note that regex delimiters are prone to ignoring quoted data. Regex example: '\\r\\t'.delimiterstr, default None
Alternative argument name for sep.delim_whitespaceboolean, 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 the delimiter parameter.
Column and index locations and names
headerint or list of ints, default 'infer'
Row number(s) to use as the column names, and the start of the data. Default behavior is to infer the column names: if no names are passed the behavior is identical to header=0 and column names are inferred from the first line of the file, if column names are passed explicitly then the behavior is identical to header=None. Explicitly pass header=0 to be able to replace existing names.
The header can be a list of ints that specify row locations for a MultiIndex on the columns e.g. [0,1,3]. Intervening rows that are not specified will be skipped (e.g. 2 in this example is skipped). Note that this parameter ignores commented lines and empty lines if skip_blank_lines=True, so header=0 denotes the first line of data rather than the first line of the file.namesarray-like, default None
List of column names to use. If file contains no header row, then you should explicitly pass header=None. Duplicates in this list are not allowed.index_colint, str, sequence of int / str, or False, default None
Column(s) to use as the row labels of the DataFrame, either given as string name or column index. If a sequence of int / str is given, a MultiIndex is used.
Note: index_col=False can be used to force pandas to not use the first column as the index, e.g. when you have a malformed file with delimiters at the end of each line.usecolslist-like or callable, default None
Return a subset of the columns. If list-like, all elements must either be positional (i.e. integer indices into the document columns) or strings that correspond to column names provided either by the user in names or inferred from the document header row(s). For example, a valid list-like usecols parameter would be [0, 1, 2] or ['foo', 'bar', 'baz'].
Element order is ignored, so usecols=[0, 1] is the same as [1, 0]. To instantiate a DataFrame from data with element order preserved use pd.read_csv(data, usecols=['foo', 'bar'])[['foo', 'bar']] for columns in ['foo', 'bar'] order or pd.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:
Using this parameter results in much faster parsing time and lower memory usage.squeezeboolean, default False
If the parsed data only contains one column then return a Series.prefixstr, default None
Prefix to add to column numbers when no header, e.g. ‘X’ for X0, X1, …mangle_dupe_colsboolean, 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 duplicate names in the columns.
General parsing configuration
dtypeType 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 together with suitable na_values settings to preserve and not interpret dtype.engine{'c', 'python'}
Parser engine to use. The C engine is faster while the Python engine is currently more feature-complete.convertersdict, default None
Dict of functions for converting values in certain columns. Keys can either be integers or column labels.true_valueslist, default None
Values to consider as True.false_valueslist, default None
Values to consider as False.skipinitialspaceboolean, default False
Skip spaces after delimiter.skiprowslist-like or integer, default None
Line numbers to skip (0-indexed) or number of lines to skip (int) at the start of the file.
If callable, the callable function will be evaluated against the row indices, returning True if the row should be skipped and False otherwise:
skipfooterint, default 0
Number of lines at bottom of file to skip (unsupported with engine=’c’).nrowsint, default None
Number of rows of file to read. Useful for reading pieces of large files.low_memoryboolean, default True
Internally process the file in chunks, resulting in lower memory use while parsing, but possibly mixed type inference. To ensure no mixed types 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_mapboolean, default False
If a filepath is provided for filepath_or_buffer, map the file object directly onto memory and access the data directly from there. Using this option can improve performance because there is no longer any I/O overhead.
NA and missing data handling
na_valuesscalar, str, list-like, or dict, default None
Additional strings to recognize as NA/NaN. If dict passed, specific per-column NA values. See na values const below for a list of the values interpreted as NaN by default.keep_default_naboolean, 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, only the default NaN values are used for parsing.If keep_default_na is
False, and na_values are specified, only the NaN values specified na_values are used for parsing.If keep_default_na is
False, and na_values are not specified, no strings will be parsed as NaN.
Note that if na_filter is passed in as False, the keep_default_na and na_values parameters will be ignored.na_filterboolean, default True
Detect missing value markers (empty strings and the value of na_values). In data without any NAs, passing na_filter=False can improve the performance of reading a large file.verboseboolean, default False
Indicate number of NA values placed in non-numeric columns.skip_blank_linesboolean, default True
If True, skip over blank lines rather than interpreting as NaN values.
Datetime handling
parse_datesboolean 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 date column.If
[[1, 3]]-> combine columns 1 and 3 and parse as a single date column.If
{'foo': [1, 3]}-> parse columns 1, 3 as date and call result ‘foo’. A fast-path exists for iso8601-formatted dates.
infer_datetime_formatboolean, default False
If True and parse_dates is enabled for a column, attempt to infer the datetime format to speed up the processing.keep_date_colboolean, default False
If True and parse_dates specifies combining multiple columns then keep the original columns.date_parserfunction, default None
Function to use for converting a sequence of string columns to an array of datetime instances. The default uses dateutil.parser.parser to do the conversion. 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 (as defined by parse_dates) as arguments; 2) concatenate (row-wise) the string values from the columns defined by parse_dates into a single array and pass that; and 3) call date_parser once for each row using one or more strings (corresponding to the columns defined by parse_dates) as arguments.dayfirstboolean, default False
DD/MM format dates, international and European format.cache_datesboolean, default True
If True, use a cache of unique, converted dates to apply the datetime conversion. May produce significant speed-up when parsing duplicate date strings, especially ones with timezone offsets.
New in version 0.25.0.
Iteration
iteratorboolean, default False
Return TextFileReader object for iteration or getting chunks with get_chunk().chunksizeint, 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.
Changed in version 0.24.0: ‘infer’ option added and set to default.thousandsstr, default None
Thousands separator.decimalstr, default '.'
Character to recognize as decimal point. E.g. use ',' for European data.float_precisionstring, default None
Specifies which converter the C engine should use for floating-point values. The options are None for the ordinary converter, high for the high-precision converter, and round_trip for the round-trip converter.lineterminatorstr (length 1), default None
Character to break file into lines. Only valid with C parser.quotecharstr (length 1)
The character used to denote the start and end of a quoted item. Quoted items can include the delimiter and it will be ignored.quotingint or csv.QUOTE_* instance, default 0
Control field quoting behavior per csv.QUOTE_* constants. Use one of QUOTE_MINIMAL (0), QUOTE_ALL (1), QUOTE_NONNUMERIC (2) or QUOTE_NONE (3).doublequoteboolean, default True
When quotechar is specified and quoting is not QUOTE_NONE, indicate whether or not to interpret two consecutive quotechar elements inside a field as a single quotechar element.escapecharstr (length 1), default None
One-character string used to escape delimiter when quoting is QUOTE_NONE.commentstr, default None
Indicates remainder of line should not be parsed. If found at the beginning of a line, the line will be ignored altogether. This parameter must be a single character. Like empty lines (as long as skip_blank_lines=True), fully commented lines are ignored by the parameter header but not by skiprows. For example, if comment='#', parsing ‘#empty\na,b,c\n1,2,3’ with header=0 will result in ‘a,b,c’ being treated as the header.encodingstr, default None
Encoding to use for UTF when reading/writing (e.g. 'utf-8'). List of Python standard encodings.dialectstr or csv.Dialect instance, default None
If provided, this parameter will override values (default or not) for the following parameters: delimiter, doublequote, escapechar, skipinitialspace, quotechar, and quoting. If it is necessary to override values, a ParserWarning will be issued. See csv.Dialect documentation for more details.
Error handling
error_bad_linesboolean, default True
Lines with too many fields (e.g. a csv line with too many commas) will by default cause an exception to be raised, and no DataFrame will be returned. If False, then these “bad lines” will dropped from the DataFrame that is returned. See bad lines below.warn_bad_linesboolean, default True
If error_bad_lines is False, and warn_bad_lines is True, a warning for each “bad line” will be output.
Specifying column data types
You can indicate the data type for the whole DataFrame or individual columns:
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 can see here to learn more about dtypes, and here to learn more about object conversion in pandas.
For instance, you can use the converters argument of read_csv():
Or you can use the to_numeric() function to coerce the dtypes after reading in the data,
which will convert all valid parsing to floats, leaving the invalid parsing as NaN.
Ultimately, how you deal with reading in columns containing mixed dtypes depends on your specific needs. In the case above, if you wanted to NaN out the 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, then using the converters argument of read_csv() would certainly be worth trying.
Note
In some cases, reading in abnormal data with columns containing mixed dtypes will result in an inconsistent dataset. If you rely on pandas to infer the dtypes of your columns, the parsing engine will go and infer the dtypes for different chunks of the data, rather than the whole dataset at once. Consequently, you can end up with column(s) with mixed dtypes. For example,
will result with mixed_df containing an int dtype for certain chunks of the column, and str for others due to the mixed dtypes from the data that was read in. It is important to note that the overall column will be marked with a dtype of object, which is used for columns with mixed dtypes.
Specifying categorical dtype
Categorical columns can be parsed directly by specifying dtype='category' or dtype=CategoricalDtype(categories, ordered).
Individual columns can be parsed as a Categorical using a dict specification:
New in version 0.21.0.
Specifying dtype='category' will result in an unordered Categorical whose categories are the unique values observed in the data. For more control on the categories and order, create a CategoricalDtype ahead of time, and pass that for that column’s dtype.
When using dtype=CategoricalDtype, “unexpected” values outside of dtype.categories are treated as missing values.
This matches the behavior of Categorical.set_categories().
Note
With dtype='category', the resulting categories will always be parsed as strings (object dtype). If the categories are numeric they can be converted using the to_numeric() function, or as appropriate, another converter such as to_datetime().
When dtype is a CategoricalDtype with homogeneous categories ( all numeric, all datetimes, etc.), the conversion is done automatically.
Naming and using columns
Handling column names
A file may or may not have a header row. pandas assumes the first row should be used as the column names:
By specifying the names argument in conjunction with header you can indicate other names to use and whether or not to throw away the header row (if any):
If the header is in a row other than the first, pass the row number to header. This will skip the preceding rows:
Note
Default behavior is to infer the column names: if no names are passed the behavior is identical to header=0 and column names are inferred from the first non-blank line of the file, if column names are passed explicitly then the behavior is identical to header=None.
Duplicate names parsing
If the file or header contains duplicate names, pandas will by default distinguish between them so as to prevent overwriting data:
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 can arise:
To prevent users from encountering this problem with duplicate data, a ValueError exception is raised if mangle_dupe_cols != True:
Filtering columns (usecols)
The usecols argument allows you to select any subset of the columns in a file, either using the column names, position numbers or a callable:
The usecols argument can also be used to specify which columns not to use in the final result:
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 will be ignored. By default, completely blank lines will be ignored as well.
If skip_blank_lines=False, then read_csv will not ignore blank lines:
Warning
The presence of ignored lines might create ambiguities involving line numbers; the parameter header uses row numbers (ignoring commented/empty lines), while skiprows uses line numbers (including commented/empty lines):
If both header and skiprows are specified, header will be relative to the end of skiprows. For example:
Comments
Sometimes comments or meta data may be included in a file:
By default, the parser includes the comments in the output:
We can suppress the comments using the comment keyword:
Dealing with Unicode data
The encoding argument should be used for encoded unicode data, which will result in byte strings being decoded to unicode in the result:
Some formats which encode all characters as multiple bytes, like UTF-16, won’t parse correctly at all without specifying the encoding. Full list of Python standard encodings.
Index columns and trailing delimiters
If a file has one more column of data than the number of column names, the first column will be used as the DataFrame’s row names:
Ordinarily, you can achieve this behavior using the index_col option.
There are some exception cases when a file has been prepared with delimiters at the end of each data line, confusing the parser. To explicitly disable the index column inference and discard the last column, pass index_col=False:
If a subset of data is being parsed using the usecols option, the index_col specification is based on that subset, not the original data.
Date Handling
Specifying date columns
To better facilitate working with datetime data, read_csv() uses the keyword arguments parse_dates and date_parser to allow users to specify a variety of columns and date/time formats to turn the input text data into datetime objects.
The simplest case is to just pass in parse_dates=True:
It is often the case that we may want to store date and time data separately, or store various date fields separately. the parse_dates keyword can be used to specify a combination of columns to parse the dates and/or times from.
You can specify a list of column lists to parse_dates, the resulting date columns will be prepended to the output (so as to not affect the existing column order) and the new column names will be the concatenation of the component column names:
By default the parser removes the component date columns, but you can choose to retain them via the keep_date_col keyword:
Note that if you wish to combine multiple columns into a single date column, a nested list must be used. In other words, parse_dates=[1, 2] indicates that the second and third columns should each be parsed as separate date columns while parse_dates=[[1, 2]] means the two columns should be parsed into a single column.
You can also use a dict to specify custom name columns:
It is important to remember that if multiple text columns are to be parsed into a single date column, then a new column is prepended to the data. The index_col specification is based off of this new set of columns rather than the original data columns:
Note
If a column or index contains an unparsable date, the entire column or index will be returned unaltered as an object data type. For non-standard datetime 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 arrange for your data to store datetimes in this format, load times will be significantly faster, ~20x has been observed.
Note
When passing a dict as the parse_dates argument, the order of the columns prepended is not guaranteed, because dict objects do not impose an ordering on their keys. On Python 2.7+ you may use collections.OrderedDict instead of a regular dict if this matters to you. Because of this, when using a dict for ‘parse_dates’ in conjunction with the index_col argument, it’s best to specify index_col as a column label rather then as an index on the resulting frame.
Date parsing functions
Finally, the parser allows you to specify a custom date_parser function to take full advantage of the flexibility of the date parsing API:
Pandas will try to call the date_parser function in three different ways. If an exception is raised, the next one is tried:
date_parseris 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_parseris called with all the columns concatenated row-wise into a single array (e.g.,date_parser(['2013 1', '2013 2'])).If #2 fails,
date_parseris called once for every row with one or more string 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_parserfunction. For optimal performance, this should be vectorized, i.e., it should accept arrays as arguments.
You can explore the date parsing functionality in date_converters.py and add your own. We would love to turn this module into a community supported set of date/time parsers. To get you started, date_converters.py contains functions to parse dual date and time columns, year/month/day columns, and year/month/day/hour/minute/second columns. It also contains a generic_parser function so you can curry it with a function that deals with a single date rather than the entire array.
Parsing a CSV with mixed timezones
Pandas cannot natively represent a column or index with mixed timezones. If your CSV file contains columns with a mixture of timezones, the default result will be an object-dtype column with strings, even with parse_dates.
To parse the mixed-timezone values as a datetime column, pass a partially-applied to_datetime() with utc=True as the date_parser.
Inferring datetime format
If you have parse_dates enabled for some or all of your columns, and your datetime strings are all formatted the same way, you may get a large speed up by setting infer_datetime_format=True. If set, pandas will attempt to guess the format of your datetime strings, and then use a faster means of parsing the strings. 5-10x parsing speeds have been observed. pandas will fallback to the usual parsing if either the format cannot be guessed or the format that was guessed cannot properly parse the entire column of strings. So in general, infer_datetime_format should not have any negative consequences if enabled.
Here are some examples of datetime strings that can be guessed (All representing 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. With dayfirst=True, it will guess “01/12/2011” to be December 1st. With dayfirst=False (default) it will guess “01/12/2011” to be January 12th.
International date formats
While US date formats tend to be MM/DD/YYYY, many international formats use DD/MM/YYYY instead. For convenience, a dayfirst keyword is provided:
Specifying method for floating-point conversion
The parameter float_precision can be specified in order to use a specific floating-point converter during parsing with the C engine. The options are the ordinary converter, the high-precision converter, and the round-trip converter (which is guaranteed to round-trip values after writing to a file). For example:
Thousand separators
For large numbers that have been written with a thousands separator, you can set the thousands keyword to a string of length 1 so that integers will be parsed correctly:
By default, numbers with a thousands separator will be parsed as strings:
The thousands keyword allows integers to be parsed correctly:
NA values
To control which values are parsed as missing values (which are signified by NaN), 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 a number (a float, like 5.0 or an integer like 5), the corresponding equivalent values will also imply a missing value (in this case effectively [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>', '#NA', 'NULL', 'null', 'NaN', '-NaN', 'nan', '-nan', ''].
Let us consider some examples:
In the example above 5 and 5.0 will be recognized as NaN, in addition to the defaults. A string will first be interpreted as a numerical 5, then as a NaN.
Above, only an empty field will be recognized as NaN.
Above, both NA and 0 as strings are NaN.
The default values, in addition to the string "Nope" are recognized as NaN.
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 column as a Series:
Boolean values
The common values True, False, TRUE, and FALSE are all recognized as boolean. Occasionally you might want to recognize other values as being boolean. To do this, use the true_values and false_values options as follows:
Handling “bad” lines
Some files may have malformed lines with too few fields or too many. Lines with too few fields will have NA values filled in the trailing fields. Lines with too many fields will raise an error by default:
You can elect to skip bad lines:
You can also use the usecols parameter to eliminate extraneous column data that appear in some lines but not others:
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 name or a csv.Dialect instance.
Suppose you had data with unenclosed quotes:
By default, read_csv uses the Excel dialect and treats the double quote as the quote character, which causes it to fail when it finds a newline before it finds the closing double quote.
We can get around this using dialect:
All of the dialect options can be specified separately by keyword arguments:
Another common dialect option is skipinitialspace, to skip any whitespace after a delimiter:
The parsers make every attempt to “do the right thing” and not be fragile. Type inference is a pretty big deal. If a column can be coerced to integer dtype without altering the contents, the parser will do so. Any non-numeric columns 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 any number of ways. One way is to use backslashes; to properly parse this data, you should pass the escapechar option:
Files with fixed width columns
While read_csv() reads delimited data, the read_fwf() function works with data files that have known and fixed column widths. The function parameters to read_fwf are largely the same as read_csv with two extra parameters, and a different usage of the delimiter parameter:
colspecs: A list of pairs (tuples) giving the extents of the fixed-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 detecting the column specifications from the first 100 rows of the data. Default behavior, 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 fields if it is not spaces (e.g., ‘~’).
Consider a typical fixed-width data file:
In order to parse this file into a DataFrame, we simply need to supply the column specifications to the read_fwf function along with the file name:
Note how the parser automatically picks column names X.<column number> when header=None argument is specified. Alternatively, you can supply just the column widths for contiguous columns:
The parser will take care of extra white spaces around the columns so it’s ok to have extra separation between the columns in the file.
By default, read_fwf will try to infer the file’s colspecs by using the first 100 rows of the file. It can do it only in cases when the columns are aligned and correctly separated by the provided delimiter (default delimiter is whitespace).
read_fwf supports the dtype parameter for specifying the types of parsed columns to be different from the inferred type.
Indexes
Files with an “implicit” index column
Consider a file with one less entry in the header than the number of data column:
In this special case, read_csv assumes that the first column is to be used as the index of the DataFrame:
Note that the dates weren’t automatically parsed. In that case you would need to do as before:
Reading an index with a MultiIndex
Suppose you have data indexed by two columns:
The index_col argument to read_csv can take a list of column numbers to turn multiple columns into a MultiIndex for the index of the returned object:
Reading columns with a MultiIndex
By specifying list of row locations for the header argument, you can read in a MultiIndex for the columns. Specifying non-consecutive rows will skip the intervening rows.
read_csv is also able to interpret a more common format of multi-columns indices.
Note: If an index_col is not specified (e.g. you don’t have an index, or wrote it with df.to_csv(..., index=False), then any names on the columns index will be lost.
Automatically “sniffing” the delimiter
read_csv is capable of inferring delimited (not necessarily comma-separated) files, as pandas uses the csv.Sniffer class of the csv module. For this, you have to specify sep=None.
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 lazily rather than reading the entire file into memory, such as the following:
By specifying a chunksize to read_csv, the return value will be an iterable object of type TextFileReader:
Specifying iterator=True will also return the TextFileReader object:
Specifying the parser engine
Under the hood pandas uses a fast and efficient parser implemented in C as well as a Python implementation which is currently more feature-complete. Where possible pandas uses the C parser (specified as engine='c'), but may fall back to Python if C-unsupported options are specified. Currently, C-unsupported options include:
sepother than a single character (e.g. regex separators)skipfootersep=Nonewithdelim_whitespace=False
Specifying any of the above options will produce a ParserWarning unless the python engine is selected explicitly using engine='python'.
Reading remote files
You can pass in a URL to a CSV file:
S3 URLs are handled as well but require installing the S3Fs library:
If your S3 bucket requires credentials you will need to set them as environment variables or in the ~/.aws/credentials config file, refer to the S3Fs documentation on credentials.
Writing out data
Writing to CSV format
The Series and DataFrame objects have an instance method to_csv which allows storing the contents of the object as a comma-separated-values file. The function takes a number of arguments. Only the first is required.
path_or_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 numberscolumns: Columns to write (default None)header: Whether to write out the column names (default True)index: whether to write row (index) names (default True)index_label: Column label(s) for index column(s) if desired. If None (default), and header and index are True, then the index names are used. (A sequence should be given if theDataFrameuses MultiIndex).mode: Python write mode, default ‘w’encoding: a string representing the encoding to use if the contents are non-ASCII, for Python versions prior to 3line_terminator: Character sequence denoting line end (default os.linesep)quoting: Set quoting rules as in csv module (default csv.QUOTE_MINIMAL). Note that if you have set a float_format then floats are converted to strings and csv.QUOTE_NONNUMERIC will treat them as non-numericquotechar: Character used to quote fields (default ‘”’)doublequote: Control quoting ofquotecharin fields (default True)escapechar: Character used to escapesepandquotecharwhen appropriate (default None)chunksize: Number of rows to write at a timedate_format: Format string for datetime objects
Writing a formatted string
The DataFrame object has an instance method to_string which allows control over the string representation of the object. All arguments are optional:
bufdefault None, for example a StringIO objectcolumnsdefault None, which columns to writecol_spacedefault None, minimum width of each column.na_repdefaultNaN, representation of NA valueformattersdefault None, a dictionary (by column) of functions each of which takes a single argument and returns a formatted stringfloat_formatdefault None, a function which takes a single (float) argument and returns a formatted string; to be applied to floats in theDataFrame.sparsifydefault True, set to False for aDataFramewith a hierarchical index to print every MultiIndex key at each row.index_namesdefault True, will print the names of the indicesindexdefault True, will print the index (ie, row labels)headerdefault True, will print the column labelsjustifydefaultleft, will print column headers left- or right-justified
The Series object also has a to_string method, but with only the buf, na_rep, float_format arguments. There is also a length argument which, if set to True, will additionally output the length of the Series.
JSON
Read and write JSON format files and strings.
Writing JSON
A Series or DataFrame can be converted to a valid JSON string. Use to_json with optional parameters:
path_or_buf: the pathname or buffer to write the output This can beNonein which case a JSON string is returnedorient:Series:default is
indexallowed values are {
split,records,index}
DataFrame:default is
columnsallowed 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: Ifrecordsorient, 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.
Orient options
There are a number of different options for the format of the resulting JSON file / string. Consider the following DataFrame and Series:
Column oriented (the default for DataFrame) serializes the data as nested JSON objects with column labels acting as the primary index:
Index oriented (the default for Series) similar to column oriented but the index labels are now primary:
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 plotting libraries, for example the JavaScript library d3.js:
Value oriented is a bare-bones option which serializes to nested JSON arrays of values only, column and index labels are not included:
Split oriented serializes to a JSON object containing separate entries for values, index and columns. Name is also included for Series:
Table oriented serializes to the JSON Table Schema, allowing for the preservation 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 of index and column labels during round-trip serialization. If you wish to preserve label ordering use the split option as it uses ordered containers.
Date handling
Writing in ISO date format:
Writing in ISO date format, with microseconds:
Epoch timestamps, in seconds:
Writing to a file, with a date index and a date column:
Fallback behavior
If the JSON serializer cannot handle the container contents directly it will fall back in the following manner:
if the dtype is unsupported (e.g.
np.complex) then thedefault_handler, if provided, will be called for each value, otherwise an exception is raised.if an object is unsupported it will attempt the following:
check if the object has defined a
toDictmethod and call it. AtoDictmethod should return adictwhich will then be JSON serialized.invoke the
default_handlerif one was provided.convert the object to a
dictby traversing its contents. However this will often fail with anOverflowErroror give unexpected results.
In general the best approach for unsupported objects or dtypes is to provide a default_handler. For example:
can be dealt with by specifying a simple default_handler:
Reading JSON
Reading a JSON string to pandas object can take a number of parameters. The parser will try to parse a DataFrame if typ is not supplied or is None. To explicitly force Series parsing, pass typ=series
filepath_or_buffer: a VALID JSON string or file handle / StringIO. The string could be a URL. Valid URL schemes include http, ftp, S3, and file. For file URLs, a host is expected. For instance, a local file could be file ://localhost/path/to/table.jsontyp: type of object to recover (series or frame), default ‘frame’orient:Series :default is
indexallowed values are {
split,records,index}
DataFrame
default is
columnsallowed 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
tableadhering to the JSON Table Schema
dtype: if True, infer dtypes, if a dict of column to dtype, then use those, ifFalse, 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 isTrueconvert_dates: a list of columns to parse for dates; IfTrue, then try to parse date-like columns, default isTrue.keep_default_dates: boolean, defaultTrue. If parsing dates, then parse the default date-like columns.numpy: direct decoding to NumPy arrays. default isFalse; Supports numeric data only, although labels may be non-numeric. Also note that the JSON ordering MUST be the same for each term ifnumpy=True.precise_float: boolean, defaultFalse. Set to enable usage of higher precision (strtod) function when decoding string to double values. Default (False) is to use fast but less precise builtin functionality.date_unit: string, the timestamp unit to detect if converting dates. Default None. By default the timestamp precision will be detected, if this is not desired then pass one of ‘s’, ‘ms’, ‘us’ or ‘ns’ to force timestamp precision to seconds, 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 withlines=True, return a JsonReader which reads inchunksizelines 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 same option here so that decoding produces sensible results, see Orient Options for an overview.
Data conversion
The default of convert_axes=True, dtype=True, and convert_dates=True will try to parse the axes, and all of the data into appropriate types, including dates. If you need to override specific dtypes, pass a dict to dtype. convert_axes should only be set to False if you need to preserve string-like numbers (e.g. ‘1’, ‘2’) in an axes.
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
floatdata will be converted tointegerif it can be done safely, e.g. a column of1.bool columns will be converted to
integeron reconstruction
Thus there are times where you may want to specify specific dtypes via the dtype keyword argument.
Reading from a JSON string:
Reading from a file:
Don’t convert any data (but still convert axes and dates):
Specify dtypes for conversion:
Preserve string indices:
Dates written in nanoseconds need to be read back in nanoseconds:
The Numpy parameter
Note
This param has been deprecated as of version 1.0.0 and will raise a FutureWarning.
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 sniff an appropriate dtype during deserialization and to subsequently decode directly to NumPy arrays, bypassing the need for intermediate Python objects.
This can provide speedups if you are deserialising a large amount of numeric data:
The speedup is less noticeable for smaller datasets:
Warning
Direct NumPy decoding makes a number of assumptions and may fail or produce unexpected output if these assumptions are not satisfied:
data is numeric.
data is uniform. The dtype is sniffed from the first value decoded. A
ValueErrormay be raised, or incorrect output may be produced if this condition is not satisfied.labels are ordered. Labels are only read from the first container, it is assumed that each subsequent row / column has been encoded in the same order. This should be satisfied if the data was encoded using
to_jsonbut may not be the case if the JSON is from another source.
Normalization
pandas provides a utility function to take a dict or list of dicts and normalize this semi-structured data into a flat table.
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.
Line delimited json
pandas is able to read and write line-delimited json files that are common in data processing pipelines using 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.
Table schema
Table Schema is a spec for describing tabular datasets as a JSON object. The JSON includes information on the field names, types, and other attributes. You can use the orient table to build a JSON string with two fields, schema and data.
The schema field contains the fields key, which itself contains a 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)index is unique.
The second field, data, contains the serialized data with the records orient. The index is included, and any datetimes are ISO 8601 formatted, as required by the Table Schema spec.
The full list of types supported are described in the Table Schema spec. This table shows the mapping from pandas types:
Pandas type
Table Schema type
int64
integer
float64
number
bool
boolean
datetime64[ns]
datetime
timedelta64[ns]
duration
categorical
any
object
str
A few notes on the generated table schema:
The
schemaobject contains apandas_versionfield. This contains the version of pandas’ dialect of the schema, and will be incremented with each revision.All dates are converted to UTC when serializing. Even timezone naive values, which are treated as UTC with an offset of 0.
datetimes with a timezone (before serializing), include an additional field
tzwith the time zone name (e.g.'US/Central').Periods are converted to timestamps before serialization, and so have the same behavior of being converted to UTC. In addition, periods will contain and additional field
freqwith the period’s frequency, e.g.'A-DEC'.Categoricals use the
anytype and anenumconstraint listing the set of possible values. Additionally, anorderedfield is included:A
primaryKeyfield, containing an array of labels, is included if the index is unique:The
primaryKeybehavior is the same with MultiIndexes, but in this case theprimaryKeyis an array:The default naming roughly follows these rules:
For series, the
object.nameis used. If that’s none, then the name isvaluesFor
DataFrames, the stringified version of the column name is usedFor
Index(notMultiIndex),index.nameis used, with a fallback toindexif that is None.For
MultiIndex,mi.namesis used. If any level has no name, thenlevel_<i>is used.
New in version 0.23.0.
read_json also accepts orient='table' as an argument. This allows for the preservation of metadata such as dtypes and index names in a round-trippable manner.
Please note that the literal string ‘index’ as the name of an Index is not round-trippable, nor are any names beginning with 'level_' within a MultiIndex. These are used by default in DataFrame.to_json() to indicate missing values and the subsequent read cannot distinguish the intent.
HTML
Reading HTML content
Warning
We highly encourage you to read the HTML Table Parsing gotchas below regarding the issues surrounding the BeautifulSoup4/html5lib/lxml parsers.
The top-level read_html() function can accept an HTML string/file/URL and will parse HTML tables into list of pandas DataFrames. Let’s look at a few examples.
Note
read_html returns a list of DataFrame objects, even if there is only a single table contained in the HTML content.
Read a URL with no options:
Note
The data from the above URL changes every Monday so the resulting data above and the data below may be slightly different.
Read in the content of the file from the above URL and pass it to read_html as a string:
You can even pass in an instance of StringIO if you so desire:
Note
The following examples are not run by the IPython evaluator due to the fact that having so many network-accessing functions slows down the documentation build. If you spot an error or an example that doesn’t run, please do not hesitate to report it over on pandas GitHub issues page.
Read a URL and match a table that contains specific text:
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 taken from the data minus the parsed header elements (<th> elements).
Specify an index column:
Specify a number of rows to skip:
Specify a number of rows to skip using a list (xrange (Python 2 only) works as well):
Specify an HTML attribute:
Specify values that should be converted to NaN:
Specify whether to keep the default set of NaN values:
Specify converters for columns. This is useful for numerical text data that has leading zeros. By default columns that are numerical are cast to numeric types and the leading zeros are lost. To avoid this, we can convert these columns to strings.
Use some combination of the above:
Read in pandas to_html output (with some loss of floating point precision):
The lxml backend will raise an error on a failed parse if that is the only parser you provide. If you only have a single parser you can provide just a string, but it is considered good practice to pass a list with one string if, for example, the function expects a sequence of strings. You may use:
Or you could pass flavor='lxml' without a list:
However, if you have bs4 and html5lib installed and pass None or ['lxml', 'bs4'] then the parse will most likely succeed. Note that as soon as a parse succeeds, the function will return.
Writing to HTML files
DataFrame objects have an instance method to_html which renders the contents of the DataFrame as an HTML table. The function arguments are as in the method to_string described above.
Note
Not all of the possible options for DataFrame.to_html are shown here for brevity’s sake. See to_html() for the full set of options.
HTML:
0
1
0
-0.184744
0.496971
1
-0.856240
1.857977
The columns argument will limit the columns shown:
HTML:
0
0
-0.184744
1
-0.856240
float_format takes a Python callable to control the precision of floating point values:
HTML:
0
1
0
-0.1847438576
0.4969711327
1
-0.8562396763
1.8579766508
bold_rows will make the row labels bold by default, but you can turn that off:
0
1
0
-0.184744
0.496971
1
-0.856240
1.857977
The classes argument provides the ability to give the resulting HTML table CSS classes. Note that these classes are appended to the existing 'dataframe' class.
The render_links argument provides the ability to add hyperlinks to cells that contain URLs.
New in version 0.24.
HTML:
Finally, the escape argument allows you to control whether the “<”, “>” and “&” characters escaped in the resulting HTML (by default it is True). So to get the HTML without escaped characters pass escape=False
Escaped:
a
b
0
&
-0.474063
1
<
-0.230305
2
>
-0.400654
Not escaped:
a
b
0
&
-0.474063
1
<
-0.230305
2
>
-0.400654
Note
Some browsers may not show a difference in the rendering of the previous two HTML tables.
HTML Table Parsing Gotchas
There are some versioning issues surrounding the libraries that are used to parse HTML tables in the top-level pandas io function read_html.
Issues with lxml
Drawbacks
lxml does not make any guarantees about the results of its parse unless it is given strictly valid markup.
It is therefore highly recommended that you install both BeautifulSoup4 and html5lib, so that you will still get a valid result (provided everything else is valid) even if lxml fails.
Issues with BeautifulSoup4 using lxml as a backend
The above issues hold here as well since BeautifulSoup4 is essentially just a wrapper around a parser backend.
Issues with BeautifulSoup4 using html5lib as a backend
Benefits
html5lib generates valid HTML5 markup from invalid markup automatically. This is extremely important for parsing HTML tables, since it guarantees a valid document. However, that does NOT mean that it is “correct”, since the process of fixing markup does not have a single definition.
html5lib is pure Python and requires no additional build steps beyond its own installation.
Drawbacks
The biggest drawback to using html5lib is that it is slow as molasses. However consider the fact that many tables on the web are not big enough for the parsing algorithm runtime to matter. It is more likely that the bottleneck will be in the process of reading the raw text from the URL over the web, i.e., IO (input-output). For very large tables, 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) files can be read using either xlrd or openpyxl. Binary Excel (.xlsb) files can be read using pyxlsb. The to_excel() instance method is used for saving a DataFrame to Excel. Generally the semantics are similar 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 Excel file, and the sheet_name indicating which sheet to parse.
ExcelFile class
To facilitate working with multiple sheets from the same file, the ExcelFile class can be used to wrap the file and can be passed into read_excel There will be a performance benefit for reading multiple sheets as the file is read into memory only once.
The ExcelFile class can also be used as a context manager.
The sheet_names property will generate a list of the sheet names in the file.
The primary use-case for an ExcelFile is parsing multiple sheets with different parameters:
Note that if the same parsing parameters are used for all sheets, a list of sheet names can simply be passed to read_excel with no loss in performance.
ExcelFile can also be called with a xlrd.book.Book object as 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.
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_nameallows specifying the sheet or sheets to read.The default value for
sheet_nameis 0, indicating to read the first sheetPass 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 Python convention, beginning at 0.
Pass a list of either strings or integers, to return a dictionary of specified sheets.
Pass a
Noneto return a dictionary of all available sheets.
Using the sheet index:
Using all default values:
Using None to get all sheets:
Using a list to get multiple sheets:
read_excel can read more than one sheet, by setting sheet_name to either a 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_col and a MultiIndex column by passing a list of rows to header. If either the index or columns have serialized level names those will be read in as well by specifying the rows/columns that make up the levels.
For example, to read in a MultiIndex index without names:
If the index has level names, they will parsed as well, using the same parameters.
If the source file has both MultiIndex index and columns, lists specifying each should be passed to index_col and header:
Parsing specific columns
It is often the case that users will insert columns to do temporary computations in Excel and you may not want to read in those columns. read_excel takes a 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 list of ints from 0 to usecols inclusive instead.
If usecols is an integer, then it is assumed to indicate the last column to be parsed.
You can also specify a comma-delimited set of Excel columns and ranges as a string:
If usecols is a list of integers, then it is assumed to be the file column indices to be parsed.
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 corresponds to a column name provided either by the user in names or inferred from the document header row(s). Those strings define which columns will be parsed:
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 against the column names, returning names where the callable function evaluates to True.
Parsing dates
Datetime-like values are normally automatically converted to the appropriate dtype when reading the excel file. But if you have a column of strings that look like dates (but are not actually formatted as dates in excel), you can use the parse_dates keyword to parse those strings to datetimes:
Cell converters
It is possible to transform the contents of Excel cells via the converters option. For instance, to convert a column to boolean:
This options handles missing values and treats exceptions in the converters as missing data. Transformations are applied cell by cell rather than to the column as a whole, so the array dtype is not guaranteed. For instance, a column of integers with missing values cannot be transformed to an array with integer dtype, because NaN is strictly a float. You can manually mask missing data to recover integer dtype:
Dtype specifications
As an alternative to converters, the type for an entire column can be specified using the dtype keyword, which takes a dictionary mapping column names to types. To interpret data with no type inference, use the type str or object.
Writing Excel files
Writing Excel files to disk
To write a DataFrame object to a sheet of an Excel file, you can use the to_excel instance method. The arguments are largely the same as to_csv described above, the first argument being the name of the excel file, and the optional second argument the name of the sheet to which the DataFrame should be written. For example:
Files with a .xls extension will be written using xlwt and those with a .xlsx extension will be written using xlsxwriter (if available) or openpyxl.
The DataFrame will be written in a way that tries to mimic the REPL output. The index_label will be placed in the second row instead of the first. You can place it in the first row by setting the merge_cells option in to_excel() to False:
In order to write separate DataFrames to separate sheets in a single Excel file, one can pass an ExcelWriter.
Note
Wringing a little more performance out of read_excel Internally, Excel stores all numeric data as floats. Because this can produce unexpected behavior when reading in data, pandas defaults to trying to convert integers to floats if it doesn’t lose information (1.0 --> 1). You can pass convert_float=False to disable this behavior, which may give a slight performance improvement.
Writing Excel files to memory
Pandas supports writing Excel files to buffer-like objects such as StringIO or BytesIO using ExcelWriter.
Note
engine is optional but recommended. Setting the engine determines the version of workbook produced. Setting engine='xlrd' will produce an Excel 2003-format workbook (xls). Using either 'openpyxl' or 'xlsxwriter' will produce an Excel 2007-format workbook (xlsx). If omitted, an Excel 2007-formatted workbook is produced.
Excel writer engines
Pandas chooses an Excel writer via two methods:
the
enginekeyword argumentthe filename extension (via the default specified in config options)
By default, pandas uses the XlsxWriter for .xlsx, openpyxl for .xlsm, and xlwt for .xls files. If you have multiple engines installed, you can set the default engine through setting the config options io.excel.xlsx.writer and io.excel.xls.writer. pandas will fall back on openpyxl for .xlsx files if Xlsxwriter is not available.
To specify which writer you want to use, you can pass an engine keyword argument to to_excel and to ExcelWriter. The built-in engines are:
openpyxl: version 2.4 or higher is requiredxlsxwriterxlwt
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 (defaultNone).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 (defaultNone).
Using the Xlsxwriter engine provides many options for controlling the format of an Excel worksheet created with the to_excel method. Excellent examples can be found in the Xlsxwriter 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 spreadsheets using the odfpy module. The semantics and features for reading OpenDocument spreadsheets match what can be done for Excel files using engine='odf'.
Note
Currently pandas only supports reading OpenDocument spreadsheets. Writing is not implemented.
Binary Excel (.xlsb) files
New in version 1.0.0.
The read_excel() method can also read binary Excel files using the pyxlsb module. The semantics and features for reading binary Excel files mostly match what can be done for Excel files using engine='pyxlsb'. pyxlsb does not recognize datetime types in files and will return floats instead.
Note
Currently pandas only supports reading binary Excel files. Writing is 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 the read_csv method. For instance, you can copy the following text to the clipboard (CTRL-C on many operating systems):
And then import the data directly to a DataFrame by calling:
The to_clipboard method can be used to write the contents of a DataFrame to the clipboard. Following which you can paste the clipboard contents into other applications (CTRL-V on many operating systems). Here we illustrate writing a DataFrame into clipboard and reading it back.
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’s cPickle module to save data structures to disk using the pickle format.
The read_pickle function in the pandas namespace can be used to load any pickled pandas object (or any other pickled object) from file:
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
read_pickle(), DataFrame.to_pickle() and Series.to_pickle() can read and 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 file to 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.
Using an explicit compression type:
Inferring compression type from the extension:
The default is to ‘infer’:
msgpack
pandas support for msgpack has been removed in version 1.0.0. It is recommended to use pyarrow for on-the-wire transmission of pandas objects.
Example pyarrow usage:
For documentation on pyarrow, see here.
HDF5 (PyTables)
HDFStore is a dict-like object which reads and writes pandas using the high performance HDF5 format using the excellent PyTables library. See the cookbook for some advanced strategies
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.
Objects can be written to the file just like adding key-value pairs to a dict:
In a current or later Python session, you can retrieve stored objects:
Deletion of the object specified by the key:
Closing a Store and using a context manager:
Read/write API
HDFStore supports a top-level API using read_hdf for reading and to_hdf for writing, similar to how read_csv and to_csv work.
HDFStore will by default not drop rows that are all missing. This behavior can be changed by setting dropna=True.
Fixed format
The examples above show storing using put, which write the HDF5 to PyTables in a fixed array format, called the fixed format. These types of stores are not appendable once written (though you can simply remove them and rewrite). Nor are they queryable; they must be retrieved 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:
Table format
HDFStore supports another PyTables format on disk, the table format. Conceptually a table is shaped very much like a DataFrame, with rows and columns. A table may be appended to in the same or other sessions. In addition, delete and query type operations are supported. 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') to enable put/append/to_hdf to by default store in the table format.
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 a hierarchical path-name like format (e.g. foo/bar/bah), which will generate a hierarchy of sub-stores (or Groups in PyTables parlance). Keys can be specified without the leading ‘/’ and are always absolute (e.g. ‘foo’ refers to ‘/foo’). Removal operations can remove everything in the sub-store and below, so be careful.
You can walk through the group hierarchy using the walk method which will yield a tuple for each group key along with the relative keys of its contents.
New in version 0.24.0.
Warning
Hierarchical keys cannot be retrieved as dotted (attribute) access as described above for items stored under the root node.
Instead, use explicit string based keys:
Storing types
Storing mixed types in a table
Storing mixed-dtype data is supported. Strings are stored as a fixed-width using the maximum size of the appended column. Subsequent attempts at appending longer strings will raise a ValueError.
Passing min_itemsize={`values`: size} as a parameter to append will set a larger minimum for the string columns. Storing floats, strings, ints, bools, datetime64 are currently supported. For string columns, passing nan_rep = 'nan' to append will change the default nan representation on disk (which converts to/from np.nan), this defaults to nan.
Storing MultiIndex DataFrames
Storing MultiIndex DataFrames as tables is very similar to storing/selecting from homogeneous index DataFrames.
Note
The index keyword is reserved and cannot be use as a level name.
Querying
Querying a table
select and delete operations have an optional criterion that can be specified to select/delete only a subset of the data. This allows one to have a very large on-disk table and retrieve only a portion of the data.
A query is specified using the Term class under the hood, as a boolean expression.
indexandcolumnsare supported indexers ofDataFrames.if
data_columnsare specified, these can be used as additional indexers.level name in a MultiIndex, with default name
level_0,level_1, … if not provided.
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 limited circumstancesIf 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 query expression is not recommended. Simply assign the string of interest to a variable and use that variable in an expression. For example, do this
instead of this
The latter will not work and will raise a SyntaxError.Note that there’s a single quote followed by a double quote in the string variable.
If you must interpolate, use the '%r' format specifier
which will quote string.
Here are some examples:
Use boolean expressions, with in-line function evaluation.
Use inline column reference.
The columns keyword can be supplied to select a list of columns to be returned, this is equivalent to passing a 'columns=list_of_columns_to_filter':
start and stop parameters can be specified to limit the total search space. These are in terms of the total number of rows in a table.
Note
select will raise a ValueError if the query expression has an unknown variable reference. Usually this means that you are trying to select on a column that is not a data_column.
select will raise a SyntaxError if the query expression is not valid.
Query timedelta64[ns]
You can store and query using the timedelta64[ns] type. Terms can be specified in the format: <float>(<unit>), where float may be signed (and fractional), and unit can be D,s,ms,us,ns for the timedelta. Here’s an example:
Query MultiIndex
Selecting from a MultiIndex can be achieved by using the name of the level.
If the MultiIndex levels names are None, the levels are automatically made available via the level_n keyword with n the level of the MultiIndex you want to select from.
Indexing
You can create/modify an index for a table with create_table_index after data is already in the table (after and append/put operation). Creating a table index is highly encouraged. This will speed your queries a great deal when you use a select with the indexed dimension as the where.
Note
Indexes are automagically created on the indexables and any data columns you specify. This behavior can be turned off by passing index=False to append.
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.
Then create the index when finished appending.
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 able to perform queries (other than the indexable columns, which you can always query). For instance say you want to perform this common operation, on-disk, and return just the frame that matches this query. You can specify data_columns = True to force all columns to be data_columns.
There is some performance degradation by making lots of columns into data columns, so it is up to the user to designate these. In addition, you cannot change data columns (nor indexables) after the first append/put operation (Of course you can simply read in the data and create a new table!).
Iterator
You can pass iterator=True or chunksize=number_in_a_chunk to select and select_as_multiple to return an iterator on the results. The default is 50,000 rows returned in a chunk.
Note
You can also use the iterator with read_hdf which will open, then automatically close the store when finished iterating.
Note, that the chunksize keyword applies to the source rows. So if you are doing a query, then the chunksize will subdivide the total rows in the table and 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 return chunks.
Advanced queries
Select a single column
To retrieve a single indexable or data column, use the method select_column. This will, for example, enable you to get the index very quickly. These return a Series of the result, indexed by the row number. These do not currently accept the where selector.
Selecting coordinates
Sometimes you want to get the coordinates (a.k.a the index locations) of your query. This returns an Int64Index of the resulting locations. These coordinates can also be passed to subsequent where operations.
Selecting using a where mask
Sometime your query can involve creating a list of rows to select. Usually this mask would be a resulting index from an indexing operation. This example selects the months of a datetimeindex which are 5.
Storer object
If you want to inspect the stored object, retrieve via get_storer. You could use this programmatically to say get the number of rows in an object.
Multiple table queries
The methods append_to_multiple and select_as_multiple can perform appending/selecting from multiple tables at once. The idea is to have one table (call it the selector table) that you index most/all of the columns, and perform your queries. The other table(s) are data tables with an index matching the selector table’s index. You can then perform a very fast query on the selector table, yet get lots of data back. This method is similar to having a very wide table, but enables more efficient queries.
The append_to_multiple method splits a given single DataFrame into multiple tables according to d, a dictionary that maps the table 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 remaining unspecified columns of the given DataFrame. The argument selector defines which table is the selector table (which you can make queries from). The argument dropna will drop rows from the input DataFrame to ensure tables are synchronized. This means that if a row for one of the tables being 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 if you 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 unexpected results.
Delete from a table
You can delete from a table selectively by specifying a where. In deleting rows, it is important to understand the PyTables deletes rows by erasing the rows, then moving the following data. Thus deleting can potentially be a very expensive operation depending on the orientation of your data. To get optimal performance, it’s worthwhile to have the dimension you are deleting be the first of the indexables.
Data is ordered (on the disk) in terms of the indexables. Here’s a simple use case. You store panel-type data, with dates in the major_axis and ids in the minor_axis. The data is then interleaved like this:
date_1
id_1
id_2
.
id_n
date_2
id_1
.
id_n
It should be clear that a delete operation on the major_axis will be fairly quick, as one chunk is removed, then the following data moved. On the other hand a delete operation on the minor_axis will be very expensive. In this case it would almost certainly be faster to rewrite the table using a where that selects all but the missing data.
Warning
Please note that HDF5 DOES NOT RECLAIM SPACE in the h5 files automatically. Thus, repeatedly deleting (or removing nodes) and adding again, WILL TEND TO INCREASE THE FILE SIZE.
To repack and clean the file, use ptrepack.
Notes & caveats
Compression
PyTables allows the stored data to be compressed. This applies to all kinds of stores, not just tables. Two parameters are used to control compression: complevel and complib.complevel specifies if and how hard data is to be compressed.
complevel=0 and complevel=None disables compression and 0<complevel<10 enables compression.complib specifies which compression library to use. If nothing is
specified the default library zlib is used. A compression library usually optimizes for either good compression rates or speed and the results will depend on the type of data. Which type of compression to choose depends on your specific needs and data. 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.
Support for alternative blosc compressors:
blosc:blosclz This is the default compressor for
bloscblosc:lz4: A compact, very popular and fast compressor.
blosc:lz4hc: A tweaked version of LZ4, produces better compression 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, but achieving better compression ratios.
blosc:zstd: An extremely well balanced codec; it provides the best compression ratios among the others above, and at reasonably fast speed.
If
complibis defined as something other than the listed libraries aValueErrorexception 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:
Or on-the-fly compression (this only applies to tables) in stores where compression is not enabled:
ptrepack
PyTables offers better write performance when tables are compressed after they are written, as opposed to turning on compression at the very beginning. You can use the supplied PyTables utility ptrepack. In addition, ptrepack can change compression levels after the fact.
Furthermore ptrepack in.h5 out.h5 will repack the file to allow you to reuse previously deleted space. Alternatively, one can simply remove the file and write again, or use the copy method.
Caveats
Warning
HDFStore is not-threadsafe for writing. The underlying PyTables only supports concurrent reads (via threading or processes). If you need reading and writing at the same time, you need to serialize these operations in a single thread in a single process. You will corrupt your data otherwise. See the (GH2397) for more information.
If you use locks to manage write access between multiple processes, you may want to use
fsync()before releasing write locks. For convenience you can usestore.flush(fsync=True)to do this for you.Once a
tableis created columns (DataFrame) are fixed; only exactly the same columns can be appendedBe aware that timezones (e.g.,
pytz.timezone('US/Eastern')) are not necessarily equal across timezone versions. So if data is localized to a specific timezone in the HDFStore using one version of a timezone library and that data is updated with another version, the data will be converted to UTC since these timezones are not considered equal. Either use the same version of timezone library or usetz_convertwith the updated timezone definition.
Warning
PyTables will show a NaturalNameWarning if a column name cannot 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 clause and are generally a bad idea.
DataTypes
HDFStore will map an object dtype to the PyTables underlying dtype. This means the following types are known to work:
Type
Represents missing values
floating : float64, float32, float16
np.nan
integer : int64, int32, int8, uint64,uint32, uint8
boolean
datetime64[ns]
NaT
timedelta64[ns]
NaT
categorical : see the section below
object : strings
np.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 is stored in a more efficient manner.
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 the length of data (for that column) that is passed to the HDFStore, in the first append. Subsequent appends, may introduce a string for a column larger than the column can hold, an Exception will be raised (otherwise you could have a silent truncation of these columns, leading to loss of information). In the future we may relax this and allow a user-specified truncation to occur.
Pass min_itemsize on the first table creation to a-priori 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 to allow all indexables or data_columns to have this min_itemsize.
Passing a min_itemsize dict will cause all passed columns to be created as data_columns automatically.
Note
If you are not passing any data_columns, then the min_itemsize will be the maximum of the length of any string passed
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.
External compatibility
HDFStore writes table format objects in specific formats suitable for producing loss-less round trips to pandas objects. For external compatibility, HDFStore can read native PyTables format tables.
It is possible to write an HDFStore object that can easily be imported into R using the rhdf5 library (Package website). Create a table format store like this:
In R this file can be read into a data.frame object using the rhdf5 library. The following example function reads the corresponding column names and data values from the values and assembles them into a data.frame:
Now you can import the DataFrame into R:
Note
The R function lists the entire HDF5 file’s contents and assembles the data.frame object from all matching nodes, so use this only as a starting point if you have stored multiple DataFrame objects to a single HDF5 file.
Performance
tablesformat come with a writing performance penalty as compared tofixedstores. The benefit is the ability to append/delete and query (potentially very large amounts of data). Write times are generally longer as compared with regular stores. Query times can be quite fast, especially on an indexed axis.You can pass
chunksize=<int>toappend, specifying the write chunksize (default is 50000). This will significantly lower your memory usage on writing.You can pass
expectedrows=<int>to the firstappend, to set the TOTAL number of rows thatPyTableswill expect. This will optimize read/write performance.Duplicate rows can be written to tables, but are filtered out in selection (with the last items being selected; thus a table is unique on major, minor pairs)
A
PerformanceWarningwill be raised if you are attempting to store types that will be pickled by PyTables (rather than stored as endemic types). See Here for more information and some solutions.
Feather
Feather provides binary columnar serialization for data frames. It is designed to make reading and writing data frames 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 pandas dtypes, 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 compatible to the earlier versions.
The format will NOT write an
Index, orMultiIndexfor theDataFrameand will raise an error if a non-default one is provided. You can.reset_index()to store the index or.reset_index(drop=True)to ignore it.Duplicate column names and non-string columns names are not supported
Non supported types include
Periodand actual Python object types. These will raise a helpful error message on an attempt at serialization.
See the Full Documentation.
Write to a feather file.
Read from a feather file.
Parquet
New in version 0.21.0.
Apache Parquet provides a partitioned binary columnar serialization for data frames. It is designed to make reading and writing data frames efficient, and to make sharing data across data analysis languages easy. Parquet can use a variety of compression techniques to shrink the file size as much as possible while still maintaining good read performance.
Parquet is designed to faithfully serialize and de-serialize DataFrame s, supporting all of the pandas dtypes, including extension dtypes such as datetime with tz.
Several caveats.
Duplicate column names and non-string columns names are not supported.
The
pyarrowengine always writes the index to the output, butfastparquetonly writes non-default indexes. This extra column can cause problems for non-Pandas consumers that are not expecting it. You can force including or omitting indexes with theindexargument, regardless of the underlying engine.Index level names, if specified, must be strings.
In the
pyarrowengine, categorical dtypes for non-string types can be serialized to parquet, but will de-serialize as their primitive dtype.The
pyarrowengine preserves theorderedflag of categorical dtypes with string types.fastparquetdoes not preserve theorderedflag.Non supported types include
Intervaland actual Python object types. These will raise a helpful error message on an attempt at serialization.Periodtype is supported with pyarrow >= 0.16.0.The
pyarrowengine preserves extension data types such as the nullable integer and string data type (requiring pyarrow >= 0.16.0, and requiring the extension type to implement the needed protocols, see the extension types documentation).
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).
Write to a parquet file.
Read from a parquet file.
Read only certain columns of a parquet file.
Handling indexes
Serializing a DataFrame to parquet may include the implicit index as one or more columns in the output file. Thus, this code:
creates a parquet file with three columns if you use pyarrow for serialization: a, b, and __index_level_0__. If you’re using fastparquet, the index may or may not be written to the file.
This unexpected extra column causes some databases like Amazon Redshift to reject the 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 to to_parquet():
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 load this file into a DataFrame.
Passing index=True will always write the index, even if that’s not the underlying 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.
The path 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 are determined by the unique values in the partition columns. The above example creates a partitioned dataset that may look like:
ORC
New in version 1.0.0.
Similar to the parquet format, the ORC Format is a binary columnar serialization for data frames. It is designed to make reading data frames efficient. Pandas provides only a reader for the ORC format, read_orc(). This requires the pyarrow library.
SQL queries
The pandas.io.sql module provides a collection of query wrappers to both facilitate data retrieval and to reduce dependency on DB-specific API. Database abstraction is provided by SQLAlchemy if installed. In addition you will need a driver library for your database. Examples of such drivers are psycopg2 for PostgreSQL or pymysql for MySQL. For SQLite this is included in Python’s standard library by default. You can find an overview of supported drivers for each SQL dialect in the SQLAlchemy docs.
If SQLAlchemy is not installed, a fallback is only provided for sqlite (and for mysql for backwards compatibility, but this is deprecated and will be removed in a future version). This mode requires a Python database adapter which respect the Python DB-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 around read_sql_table() and read_sql_query() (and for backward compatibility) and will delegate to specific function depending on the 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 database engine. 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 engine object from database URI. You only need to create the engine once per database you are connecting to. For more information on create_engine() and the URI formatting, see the examples below and the SQLAlchemy documentation
If you want to manage your own connections you can pass one of those instead:
Writing DataFrames
Assuming the following data is in a DataFrame data, we can insert it into the database using to_sql().
id
Date
Col_1
Col_2
Col_3
26
2012-10-18
X
25.7
True
42
2012-10-19
Y
-12.4
False
63
2012-10-20
Z
5.73
True
With some databases, writing large DataFrames can result in errors due to packet size limitations being exceeded. This can be avoided by setting the chunksize parameter when calling to_sql. For example, the following writes data to the database in batches of 1000 rows at a time:
SQL data types
to_sql() will try to map your data to an appropriate SQL data type based on the dtype of the data. When you have columns of dtype object, pandas will try to infer the data type.
You can always override the default type by specifying the desired SQL type of any of the columns by using the dtype argument. This argument needs a dictionary mapping column names to SQLAlchemy types (or strings for the sqlite3 fallback mode). For example, specifying to use the sqlalchemy String type instead of the default Text type for string columns:
Note
Due to the limited support for timedelta’s in the different database flavors, columns with type timedelta64 will be written as integer values as nanoseconds to the database and a warning will be raised.
Note
Columns of category dtype will be converted to the dense representation as you would get with np.asarray(categorical) (e.g. for string categories this gives an array of strings). Because of this, reading the database table back in does not generate a categorical.
Datetime data types
Using SQLAlchemy, to_sql() is capable of writing datetime data that is timezone naive or timezone aware. However, the resulting data stored in the database ultimately depends on the supported data type for datetime data of the database system being used.
The following table lists supported data types for datetime data for some common databases. Other database dialects may have different data types for datetime data.
Database
SQL Datetime Types
Timezone Support
SQLite
TEXT
No
MySQL
TIMESTAMP or DATETIME
No
PostgreSQL
TIMESTAMP or TIMESTAMP WITH TIME ZONE
Yes
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 time with respect to the timezone.
read_sql_table() is also capable of reading datetime data that is timezone aware or naive. When reading TIMESTAMP WITH TIME ZONE types, pandas will 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 SQLINSERTclause (one per row).'multi': Pass multiple values in a singleINSERTclause. It uses a special SQL syntax not supported by all backends. This usually provides better performance for analytic databases like Presto and Redshift, but has worse performance for traditional 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 on specific backend dialect features.
Example of a callable using PostgreSQL COPY clause:
Reading tables
read_sql_table() will read a database table given the table name and optionally a subset of columns to read.
Note
In order to use read_sql_table(), you must have the SQLAlchemy optional dependency installed.
Note
Note that pandas infers column dtypes from query outputs, and not by looking up data types in the physical database schema. For example, assume userid is an integer column in a table. Then, intuitively, select userid ... will return integer-valued series, while select cast(userid as text) ... will return object-valued (str) series. Accordingly, if the query output is empty, then all resulting columns will be returned as object-valued (since they are most general). If you foresee that your query will sometimes generate an empty result, you may want to explicitly typecast afterwards to ensure dtype integrity.
You can also specify the name of the column as the DataFrame index, and specify a subset of columns to be read.
And you can explicitly force columns to be parsed as dates:
If needed you can explicitly specify a format string, or a dict of arguments to pass to pandas.to_datetime():
You can check if a table exists using has_table()
Schema support
Reading from and writing to different schema’s is supported through the schema keyword in the read_sql_table() and to_sql() functions. Note however that this depends on the database flavor (sqlite does not have schema’s). For example:
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.
Of course, you can specify a more “complex” query.
The read_sql_query() function supports a chunksize argument. Specifying this will return an iterator through chunks of the query result:
You can also run a plain query without creating a DataFrame with execute(). This is useful for queries that don’t return values, such as INSERT. This is functionally equivalent to calling execute on the SQLAlchemy engine or db connection object. Again, you must use the SQL syntax variant appropriate for your database.
Engine connection examples
To connect with SQLAlchemy you use the create_engine() function to create an engine object from database URI. You only need to create the engine once per database you are connecting to.
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
If you have an SQLAlchemy description of your database you can express where conditions using SQLAlchemy expressions
You can combine SQLAlchemy expressions with parameters passed to read_sql() using sqlalchemy.bindparam()
Sqlite fallback
The use of sqlite is supported without using SQLAlchemy. This mode requires a Python database adapter which respect the Python DB-API.
You can create connections like so:
And then issue the following queries:
Google BigQuery
Warning
Starting in 0.20.0, pandas has split off Google BigQuery support into the separate 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 can use the pandas methods pd.read_gbq and DataFrame.to_gbq, which will call the respective functions from pandas-gbq.
Full documentation can be found here.
Stata format
Writing to stata format
The method to_stata() will write a DataFrame into a .dta file. The format version of this file is always 115 (Stata 12).
Stata data files have limited data type support; only strings with 244 or fewer characters, int8, int16, int32, float32 and float64 can be stored in .dta files. Additionally, Stata reserves certain values to represent missing data. Exporting a non-missing value that is outside of the permitted range in Stata for a particular data type will retype the variable to the next larger size. For example, int8 values are restricted to lie between -127 and 100 in Stata, and so variables with values above 100 will trigger a conversion to int16. nan values in floating points data types 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 to the smallest supported type that can represent the data. For example, data with a type of uint8 will be cast to int8 if all values are less than 100 (the upper bound for non-missing int8 data in Stata), or, if values are outside of this range, the variable is cast to int16.
Warning
Conversion from int64 to float64 may result in a loss of precision if int64 values are larger than 2**53.
Warning
StataWriter and to_stata() only support fixed width strings containing up to 244 characters, a limitation imposed by the version 115 dta file format. Attempting to write Stata dta files with strings longer than 244 characters raises a ValueError.
Reading from Stata format
The top-level function read_stata will read a dta file and return either a DataFrame or a StataReader that can be used to read the file incrementally.
Specifying a chunksize yields a StataReader instance that can be used to read chunksize lines from the file at a time. The StataReader object can be used as an iterator.
For more fine-grained control, use iterator=True and specify chunksize with each call to read().
Currently the index is retrieved as a column.
The parameter convert_categoricals indicates whether value labels should be read and used to create a Categorical variable from them. Value labels can also be retrieved by the function value_labels, which requires read() to be called before use.
The parameter convert_missing indicates whether missing value representations in Stata should be preserved. If False (the default), missing values are represented as np.nan. If True, missing values are represented using StataMissingValue objects, and columns containing missing values will have object data type.
Note
read_stata() and StataReader 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 values and the categories as value labels. Stata does not have an explicit equivalent to a Categorical and information about whether the variable is ordered is lost when exporting.
Warning
Stata only supports string value labels, and so str is called on the categories when exporting data. Exporting Categorical variables with non-string categories produces a warning, and can result a loss of information if the str representations of the categories are not unique.
Labeled data can similarly be imported from Stata data files as Categorical variables using the keyword argument convert_categoricals (True by default). The keyword argument order_categoricals (True by default) determines whether 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 always use integer data types between -1 and n-1 where n is the number of categories. If the original values in the Stata data file are required, these can be imported by setting convert_categoricals=False, which will import original data (but not the variable labels). The original values can be matched to the imported categorical data since there is a simple mapping between the original Stata data values and the category codes of imported Categorical variables: missing values are assigned code -1, and the smallest original value is assigned 0, the second smallest is assigned 1 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 for some but not all data values. Importing a partially labeled series will produce a Categorical with string categories for the values that are labeled and numeric categories for values with no label.
SAS formats
The top-level function read_sas() can read (but not write) SAS xport (.XPT) and (since v0.18.0) SAS7BDAT (.sas7bdat) format files.
SAS files only contain two value types: ASCII text and floating point values (usually 8 bytes but sometimes truncated). For xport files, there is no automatic type conversion to integers, dates, or categoricals. For SAS7BDAT files, the format codes may allow date variables to be automatically converted to dates. By default the whole file is read and returned as a DataFrame.
Specify a chunksize or use iterator=True to obtain reader objects (XportReader or SAS7BDATReader) for incrementally reading the file. The reader objects also have attributes that contain additional information about the file and its variables.
Read a SAS7BDAT file:
Obtain an iterator and read an XPORT file 100,000 lines at a time:
The specification for the xport file format is available from the SAS web site.
No official documentation is available for the SAS7BDAT format.
SPSS formats
New in version 0.25.0.
The top-level function read_spss() can read (but not write) SPSS sav (.sav) and zsav (.zsav) format files.
SPSS files contain column names. By default the whole file is read, categorical columns are converted into pd.Categorical, and a DataFrame with all columns is returned.
Specify the usecols parameter to obtain a subset of columns. Specify convert_categoricals=False to avoid converting categorical columns into pd.Categorical.
Read an SPSS file:
Extract a subset of columns contained in usecols from an SPSS file and avoid converting categorical columns into pd.Categorical:
More information about the sav and zsav file format is available here.
Other file formats
pandas itself only supports IO with a limited set of file formats that map cleanly to its tabular data model. For reading and writing other file formats into and from pandas, we recommend these packages from the broader community.
netCDF
xarray provides data structures inspired by the pandas DataFrame for working with multi-dimensional datasets, with a focus on the netCDF file format and easy conversion to and from pandas.
Performance considerations
This is an informal comparison of various IO methods, using pandas 0.24.2. Timings are machine dependent and small differences should be ignored.
Given the next test set:
When writing, the top-three functions in terms of speed are test_feather_write, test_hdf_fixed_write and test_hdf_fixed_write_compress.
When reading, the top three are test_feather_read, test_pickle_read and test_hdf_fixed_read.
For this test case test.pkl.compress, test.parquet and test.feather took the least space on disk. Space on disk (in bytes)
Reference : https://pandas.pydata.org/pandas-docs/stable/user_guide/io.html
Last updated