Movatterモバイル変換


[0]ホーム

URL:


Skip to main content
Ctrl+K

IO tools (text, CSV, HDF5, …)#

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

Format Type

Data Description

Reader

Writer

text

CSV

read_csv

to_csv

text

Fixed-Width Text File

read_fwf

NA

text

JSON

read_json

to_json

text

HTML

read_html

to_html

text

LaTeX

Styler.to_latex

NA

text

XML

read_xml

to_xml

text

Local clipboard

read_clipboard

to_clipboard

binary

MS Excel

read_excel

to_excel

binary

OpenDocument

read_excel

NA

binary

HDF5 Format

read_hdf

to_hdf

binary

Feather Format

read_feather

to_feather

binary

Parquet Format

read_parquet

to_parquet

binary

ORC Format

read_orc

to_orc

binary

Stata

read_stata

to_stata

binary

SAS

read_sas

NA

binary

SPSS

read_spss

NA

binary

Python Pickle Format

read_pickle

to_pickle

SQL

SQL

read_sql

to_sql

SQL

Google BigQuery;:ref:read_gbq<io.bigquery>;:ref:to_gbq<io.bigquery>

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

Note

For examples that use theStringIO class, make sure you import itwithfromioimportStringIO for Python 3.

CSV & text files#

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

Parsing options#

read_csv() accepts the following common arguments:

Basic#

filepath_or_buffervarious

Either a path to a file (astr,pathlib.Path,orpy:py._path.local.LocalPath), URL (including http, ftp, and S3locations), or any object with aread() method (such as an open file orStringIO).

sepstr, defaults to',' forread_csv(),\t forread_table()

Delimiter to use. If sep isNone, the C engine cannot automatically detectthe separator, but the Python parsing engine can, meaning the latter will beused and automatically detect the separator by Python’s builtin sniffer tool,csv.Sniffer. In addition, separators longer than 1 character anddifferent from'\s+' will be interpreted as regular expressions andwill also force the use of the Python parsing engine. Note that regexdelimiters are prone to ignoring quoted data. Regex example:'\\r\\t'.

delimiterstr, defaultNone

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 settingsep='\s+'.If this option is set toTrue, nothing should be passed in for thedelimiter 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 thedata. Default behavior is to infer the column names: if no names arepassed the behavior is identical toheader=0 and column namesare inferred from the first line of the file, if column names arepassed explicitly then the behavior is identical toheader=None. Explicitly passheader=0 to be able to replaceexisting names.

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

namesarray-like, defaultNone

List of column names to use. If file contains no header row, then you shouldexplicitly passheader=None. Duplicates in this list are not allowed.

index_colint, str, sequence of int / str, or False, optional, defaultNone

Column(s) to use as the row labels of theDataFrame, either given asstring name or column index. If a sequence of int / str is given, aMultiIndex is used.

Note

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

The default value ofNone instructs pandas to guess. If the number offields in the column header row is equal to the number of fields in the bodyof the data file, then a default index is used. If it is larger, thenthe first columns are used as index so that the remaining number of fields inthe body are equal to the number of fields in the header.

The first row after the header is used to determine the number of columns,which will go into the index. If the subsequent rows contain less columnsthan the first row, they are filled withNaN.

This can be avoided throughusecols. This ensures that the columns aretaken as is and the trailing data are ignored.

usecolslist-like or callable, defaultNone

Return a subset of the columns. If list-like, all elements must eitherbe positional (i.e. integer indices into the document columns) or stringsthat correspond to column names provided either by the user innames orinferred from the document header row(s). Ifnames are given, the documentheader row(s) are not taken into account. For example, a valid list-likeusecols parameter would be[0,1,2] or['foo','bar','baz'].

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

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

In [1]:importpandasaspdIn [2]:fromioimportStringIOIn [3]:data="col1,col2,col3\na,b,1\na,b,2\nc,d,3"In [4]:pd.read_csv(StringIO(data))Out[4]:  col1 col2  col30    a    b     11    a    b     22    c    d     3In [5]:pd.read_csv(StringIO(data),usecols=lambdax:x.upper()in["COL1","COL3"])Out[5]:  col1  col30    a     11    a     22    c     3

Using this parameter results in much faster parsing time and lower memory usagewhen using the c engine. The Python engine loads the data first before decidingwhich columns to drop.

General parsing configuration#

dtypeType name or dict of column -> type, defaultNone

Data type for data or columns. E.g.{'a':np.float64,'b':np.int32,'c':'Int64'}Usestr orobject together with suitablena_values settings to preserveand not interpret dtype. If converters are specified, they will be applied INSTEADof dtype conversion.

Added in version 1.5.0:Support for defaultdict was added. Specify a defaultdict as input wherethe default determines the dtype of the columns which are not explicitlylisted.

dtype_backend{“numpy_nullable”, “pyarrow”}, defaults to NumPy backed DataFrames

Which dtype_backend to use, e.g. whether a DataFrame should have NumPyarrays, nullable dtypes are used for all dtypes that have a nullableimplementation when “numpy_nullable” is set, pyarrow is used for alldtypes if “pyarrow” is set.

The dtype_backends are still experimential.

Added in version 2.0.

engine{'c','python','pyarrow'}

Parser engine to use. The C and pyarrow engines are faster, while the python engineis currently more feature-complete. Multithreading is currently only supported bythe pyarrow engine.

Added in version 1.4.0:The “pyarrow” engine was added as anexperimental engine, and some featuresare unsupported, or may not work correctly, with this engine.

convertersdict, defaultNone

Dict of functions for converting values in certain columns. Keys can either beintegers or column labels.

true_valueslist, defaultNone

Values to consider asTrue.

false_valueslist, defaultNone

Values to consider asFalse.

skipinitialspaceboolean, defaultFalse

Skip spaces after delimiter.

skiprowslist-like or integer, defaultNone

Line numbers to skip (0-indexed) or number of lines to skip (int) at the startof the file.

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

In [6]:data="col1,col2,col3\na,b,1\na,b,2\nc,d,3"In [7]:pd.read_csv(StringIO(data))Out[7]:  col1 col2  col30    a    b     11    a    b     22    c    d     3In [8]:pd.read_csv(StringIO(data),skiprows=lambdax:x%2!=0)Out[8]:  col1 col2  col30    a    b     2
skipfooterint, default0

Number of lines at bottom of file to skip (unsupported with engine=’c’).

nrowsint, defaultNone

Number of rows of file to read. Useful for reading pieces of large files.

low_memoryboolean, defaultTrue

Internally process the file in chunks, resulting in lower memory usewhile parsing, but possibly mixed type inference. To ensure no mixedtypes either setFalse, or specify the type with thedtype parameter.Note that the entire file is read into a singleDataFrame regardless,use thechunksize oriterator parameter to return the data in chunks.(Only valid with C parser)

memory_mapboolean, default False

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

NA and missing data handling#

na_valuesscalar, str, list-like, or dict, defaultNone

Additional strings to recognize as NA/NaN. If dict passed, specific per-columnNA values. Seena values const belowfor a list of the values interpreted as NaN by default.

keep_default_naboolean, defaultTrue

Whether or not to include the default NaN values when parsing the data.Depending on whetherna_values is passed in, the behavior is as follows:

  • Ifkeep_default_na isTrue, andna_values are specified,na_valuesis appended to the default NaN values used for parsing.

  • Ifkeep_default_na isTrue, andna_values are not specified, onlythe default NaN values are used for parsing.

  • Ifkeep_default_na isFalse, andna_values are specified, onlythe NaN values specifiedna_values are used for parsing.

  • Ifkeep_default_na isFalse, andna_values are not specified, nostrings will be parsed as NaN.

Note that ifna_filter is passed in asFalse, thekeep_default_na andna_values parameters will be ignored.

na_filterboolean, defaultTrue

Detect missing value markers (empty strings and the value of na_values). Indata without any NAs, passingna_filter=False can improve the performanceof reading a large file.

verboseboolean, defaultFalse

Indicate number of NA values placed in non-numeric columns.

skip_blank_linesboolean, defaultTrue

IfTrue, 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, defaultFalse.
  • IfTrue -> try parsing the index.

  • If[1,2,3] -> try parsing columns 1, 2, 3 each as a separate datecolumn.

  • If[[1,3]] -> combine columns 1 and 3 and parse as a single datecolumn.

  • If{'foo':[1,3]} -> parse columns 1, 3 as date and call result ‘foo’.

Note

A fast-path exists for iso8601-formatted dates.

infer_datetime_formatboolean, defaultFalse

IfTrue and parse_dates is enabled for a column, attempt to infer thedatetime format to speed up the processing.

Deprecated since version 2.0.0:A strict version of this argument is now the default, passing it has no effect.

keep_date_colboolean, defaultFalse

IfTrue and parse_dates specifies combining multiple columns then keep theoriginal columns.

date_parserfunction, defaultNone

Function to use for converting a sequence of string columns to an array ofdatetime instances. The default usesdateutil.parser.parser to do theconversion. pandas will try to call date_parser in three different ways,advancing to the next if an exception occurs: 1) Pass one or more arrays (asdefined by parse_dates) as arguments; 2) concatenate (row-wise) the stringvalues from the columns defined by parse_dates into a single array and passthat; and 3) call date_parser once for each row using one or more strings(corresponding to the columns defined by parse_dates) as arguments.

Deprecated since version 2.0.0:Usedate_format instead, or read in asobject and then applyto_datetime() as-needed.

date_formatstr or dict of column -> format, defaultNone

If used in conjunction withparse_dates, will parse dates according to thisformat. For anything more complex,please read in asobject and then applyto_datetime() as-needed.

Added in version 2.0.0.

dayfirstboolean, defaultFalse

DD/MM format dates, international and European format.

cache_datesboolean, default True

If True, use a cache of unique, converted dates to apply the datetimeconversion. May produce significant speed-up when parsing duplicatedate strings, especially ones with timezone offsets.

Iteration#

iteratorboolean, defaultFalse

ReturnTextFileReader object for iteration or getting chunks withget_chunk().

chunksizeint, defaultNone

ReturnTextFileReader object for iteration. Seeiterating and chunking below.

Quoting, compression, and file format#

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

For on-the-fly decompression of on-disk data. If ‘infer’, then use gzip,bz2, zip, xz, or zstandard iffilepath_or_buffer is path-like ending in ‘.gz’, ‘.bz2’,‘.zip’, ‘.xz’, ‘.zst’, respectively, and no decompression otherwise. If using ‘zip’,the ZIP file must contain only one data file to be read in.Set toNone for no decompression. Can also be a dict with key'method'set to one of {'zip','gzip','bz2','zstd'} and other key-value pairs areforwarded tozipfile.ZipFile,gzip.GzipFile,bz2.BZ2File, orzstandard.ZstdDecompressor.As an example, the following could be passed for faster compression and tocreate a reproducible gzip archive:compression={'method':'gzip','compresslevel':1,'mtime':1}.

Changed in version 1.2.0:Previous versions forwarded dict entries for ‘gzip’ togzip.open.

thousandsstr, defaultNone

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 areNone for the ordinary converter,high for thehigh-precision converter, andround_trip for the round-trip converter.

lineterminatorstr (length 1), defaultNone

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 itemscan include the delimiter and it will be ignored.

quotingint orcsv.QUOTE_* instance, default0

Control field quoting behavior percsv.QUOTE_* constants. Use one ofQUOTE_MINIMAL (0),QUOTE_ALL (1),QUOTE_NONNUMERIC (2) orQUOTE_NONE (3).

doublequoteboolean, defaultTrue

Whenquotechar is specified andquoting is notQUOTE_NONE,indicate whether or not to interpret two consecutivequotechar elementsinside a field as a singlequotechar element.

escapecharstr (length 1), defaultNone

One-character string used to escape delimiter when quoting isQUOTE_NONE.

commentstr, defaultNone

Indicates remainder of line should not be parsed. If found at the beginning ofa line, the line will be ignored altogether. This parameter must be a singlecharacter. Like empty lines (as long asskip_blank_lines=True), fullycommented lines are ignored by the parameterheader but not byskiprows.For example, ifcomment='#', parsing ‘#empty\na,b,c\n1,2,3’ withheader=0 will result in ‘a,b,c’ being treated as the header.

encodingstr, defaultNone

Encoding to use for UTF when reading/writing (e.g.'utf-8').List ofPython standard encodings.

dialectstr orcsv.Dialect instance, defaultNone

If provided, this parameter will override values (default or not) for thefollowing parameters:delimiter,doublequote,escapechar,skipinitialspace,quotechar, andquoting. If it is necessary tooverride values, a ParserWarning will be issued. Seecsv.Dialectdocumentation for more details.

Error handling#

on_bad_lines(‘error’, ‘warn’, ‘skip’), default ‘error’

Specifies what to do upon encountering a bad line (a line with too many fields).Allowed values are :

  • ‘error’, raise an ParserError when a bad line is encountered.

  • ‘warn’, print a warning when a bad line is encountered and skip that line.

  • ‘skip’, skip bad lines without raising or warning when they are encountered.

Added in version 1.3.0.

Specifying column data types#

You can indicate the data type for the wholeDataFrame or individualcolumns:

In [9]:importnumpyasnpIn [10]:data="a,b,c,d\n1,2,3,4\n5,6,7,8\n9,10,11"In [11]:print(data)a,b,c,d1,2,3,45,6,7,89,10,11In [12]:df=pd.read_csv(StringIO(data),dtype=object)In [13]:dfOut[13]:   a   b   c    d0  1   2   3    41  5   6   7    82  9  10  11  NaNIn [14]:df["a"][0]Out[14]:'1'In [15]:df=pd.read_csv(StringIO(data),dtype={"b":object,"c":np.float64,"d":"Int64"})In [16]:df.dtypesOut[16]:a      int64b     objectc    float64d      Int64dtype: object

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

For instance, you can use theconverters argumentofread_csv():

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

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

In [21]:df2=pd.read_csv(StringIO(data))In [22]:df2["col_1"]=pd.to_numeric(df2["col_1"],errors="coerce")In [23]:df2Out[23]:   col_10   1.001   2.002    NaN3   4.22In [24]:df2["col_1"].apply(type).value_counts()Out[24]:col_1<class 'float'>    4Name: count, dtype: int64

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

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

Note

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

In [25]:col_1=list(range(500000))+["a","b"]+list(range(500000))In [26]:df=pd.DataFrame({"col_1":col_1})In [27]:df.to_csv("foo.csv")In [28]:mixed_df=pd.read_csv("foo.csv")In [29]:mixed_df["col_1"].apply(type).value_counts()Out[29]:col_1<class 'int'>    737858<class 'str'>    262144Name: count, dtype: int64In [30]:mixed_df["col_1"].dtypeOut[30]:dtype('O')

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

Settingdtype_backend="numpy_nullable" will result in nullable dtypes for every column.

In [31]:data="""a,b,c,d,e,f,g,h,i,j   ....:1,2.5,True,a,,,,,12-31-2019,   ....:3,4.5,False,b,6,7.5,True,a,12-31-2019,   ....:"""   ....:In [32]:df=pd.read_csv(StringIO(data),dtype_backend="numpy_nullable",parse_dates=["i"])In [33]:dfOut[33]:   a    b      c  d     e     f     g     h          i     j0  1  2.5   True  a  <NA>  <NA>  <NA>  <NA> 2019-12-31  <NA>1  3  4.5  False  b     6   7.5  True     a 2019-12-31  <NA>In [34]:df.dtypesOut[34]:a             Int64b           Float64c           booleand    string[python]e             Int64f           Float64g           booleanh    string[python]i    datetime64[ns]j             Int64dtype: object

Specifying categorical dtype#

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

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

Individual columns can be parsed as aCategorical using a dictspecification:

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

Specifyingdtype='category' will result in an unorderedCategoricalwhosecategories are the unique values observed in the data. For morecontrol on the categories and order, create aCategoricalDtype ahead of time, and pass that forthat column’sdtype.

In [40]:frompandas.api.typesimportCategoricalDtypeIn [41]:dtype=CategoricalDtype(["d","c","b","a"],ordered=True)In [42]:pd.read_csv(StringIO(data),dtype={"col1":dtype}).dtypesOut[42]:col1    categorycol2      objectcol3       int64dtype: object

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

In [43]:dtype=CategoricalDtype(["a","b","d"])# No 'c'In [44]:pd.read_csv(StringIO(data),dtype={"col1":dtype}).col1Out[44]:0      a1      a2    NaNName: col1, dtype: categoryCategories (3, object): ['a', 'b', 'd']

This matches the behavior ofCategorical.set_categories().

Note

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

Whendtype is aCategoricalDtype with homogeneouscategories (all numeric, all datetimes, etc.), the conversion is done automatically.

In [45]:df=pd.read_csv(StringIO(data),dtype="category")In [46]:df.dtypesOut[46]:col1    categorycol2    categorycol3    categorydtype: objectIn [47]:df["col3"]Out[47]:0    11    22    3Name: col3, dtype: categoryCategories (3, object): ['1', '2', '3']In [48]:new_categories=pd.to_numeric(df["col3"].cat.categories)In [49]:df["col3"]=df["col3"].cat.rename_categories(new_categories)In [50]:df["col3"]Out[50]:0    11    22    3Name: col3, dtype: categoryCategories (3, int64): [1, 2, 3]

Naming and using columns#

Handling column names#

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

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

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

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

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

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

Note

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

Duplicate names parsing#

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

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

There is no more duplicate data because duplicate columns ‘X’, …, ‘X’ become‘X’, ‘X.1’, …, ‘X.N’.

Filtering columns (usecols)#

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

In [61]:data="a,b,c,d\n1,2,3,foo\n4,5,6,bar\n7,8,9,baz"In [62]:pd.read_csv(StringIO(data))Out[62]:   a  b  c    d0  1  2  3  foo1  4  5  6  bar2  7  8  9  bazIn [63]:pd.read_csv(StringIO(data),usecols=["b","d"])Out[63]:   b    d0  2  foo1  5  bar2  8  bazIn [64]:pd.read_csv(StringIO(data),usecols=[0,2,3])Out[64]:   a  c    d0  1  3  foo1  4  6  bar2  7  9  bazIn [65]:pd.read_csv(StringIO(data),usecols=lambdax:x.upper()in["A","C"])Out[65]:   a  c0  1  31  4  62  7  9

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

In [66]:pd.read_csv(StringIO(data),usecols=lambdax:xnotin["a","c"])Out[66]:   b    d0  2  foo1  5  bar2  8  baz

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

Comments and empty lines#

Ignoring line comments and empty lines#

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

In [67]:data="\na,b,c\n\n# commented line\n1,2,3\n\n4,5,6"In [68]:print(data)a,b,c# commented line1,2,34,5,6In [69]:pd.read_csv(StringIO(data),comment="#")Out[69]:   a  b  c0  1  2  31  4  5  6

Ifskip_blank_lines=False, thenread_csv will not ignore blank lines:

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

Warning

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

In [72]:data="#comment\na,b,c\nA,B,C\n1,2,3"In [73]:pd.read_csv(StringIO(data),comment="#",header=1)Out[73]:   A  B  C0  1  2  3In [74]:data="A,B,C\n#comment\na,b,c\n1,2,3"In [75]:pd.read_csv(StringIO(data),comment="#",skiprows=2)Out[75]:   a  b  c0  1  2  3

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

In [76]:data=(   ....:"# empty\n"   ....:"# second empty line\n"   ....:"# third emptyline\n"   ....:"X,Y,Z\n"   ....:"1,2,3\n"   ....:"A,B,C\n"   ....:"1,2.,4.\n"   ....:"5.,NaN,10.0\n"   ....:)   ....:In [77]:print(data)# empty# second empty line# third emptylineX,Y,Z1,2,3A,B,C1,2.,4.5.,NaN,10.0In [78]:pd.read_csv(StringIO(data),comment="#",skiprows=4,header=1)Out[78]:     A    B     C0  1.0  2.0   4.01  5.0  NaN  10.0

Comments#

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

In [79]:data=(   ....:"ID,level,category\n"   ....:"Patient1,123000,x # really unpleasant\n"   ....:"Patient2,23000,y # wouldn't take his medicine\n"   ....:"Patient3,1234018,z # awesome"   ....:)   ....:In [80]:withopen("tmp.csv","w")asfh:   ....:fh.write(data)   ....:In [81]:print(open("tmp.csv").read())ID,level,categoryPatient1,123000,x # really unpleasantPatient2,23000,y # wouldn't take his medicinePatient3,1234018,z # awesome

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

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

We can suppress the comments using thecomment keyword:

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

Dealing with Unicode data#

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

In [86]:fromioimportBytesIOIn [87]:data=b"word,length\n"b"Tr\xc3\xa4umen,7\n"b"Gr\xc3\xbc\xc3\x9fe,5"In [88]:data=data.decode("utf8").encode("latin-1")In [89]:df=pd.read_csv(BytesIO(data),encoding="latin-1")In [90]:dfOut[90]:      word  length0  Träumen       71    Grüße       5In [91]:df["word"][1]Out[91]:'Grüße'

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

Index columns and trailing delimiters#

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

In [92]:data="a,b,c\n4,apple,bat,5.7\n8,orange,cow,10"In [93]:pd.read_csv(StringIO(data))Out[93]:        a    b     c4   apple  bat   5.78  orange  cow  10.0
In [94]:data="index,a,b,c\n4,apple,bat,5.7\n8,orange,cow,10"In [95]:pd.read_csv(StringIO(data),index_col=0)Out[95]:            a    b     cindex4       apple  bat   5.78      orange  cow  10.0

Ordinarily, you can achieve this behavior using theindex_col option.

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

In [96]:data="a,b,c\n4,apple,bat,\n8,orange,cow,"In [97]:print(data)a,b,c4,apple,bat,8,orange,cow,In [98]:pd.read_csv(StringIO(data))Out[98]:        a    b   c4   apple  bat NaN8  orange  cow NaNIn [99]:pd.read_csv(StringIO(data),index_col=False)Out[99]:   a       b    c0  4   apple  bat1  8  orange  cow

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

In [100]:data="a,b,c\n4,apple,bat,\n8,orange,cow,"In [101]:print(data)a,b,c4,apple,bat,8,orange,cow,In [102]:pd.read_csv(StringIO(data),usecols=["b","c"])Out[102]:     b   c4  bat NaN8  cow NaNIn [103]:pd.read_csv(StringIO(data),usecols=["b","c"],index_col=0)Out[103]:     b   c4  bat NaN8  cow NaN

Date Handling#

Specifying date columns#

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

The simplest case is to just pass inparse_dates=True:

In [104]:withopen("foo.csv",mode="w")asf:   .....:f.write("date,A,B,C\n20090101,a,1,2\n20090102,b,3,4\n20090103,c,4,5")   .....:# Use a column as an index, and parse it as dates.In [105]:df=pd.read_csv("foo.csv",index_col=0,parse_dates=True)In [106]:dfOut[106]:            A  B  Cdate2009-01-01  a  1  22009-01-02  b  3  42009-01-03  c  4  5# These are Python datetime objectsIn [107]:df.indexOut[107]:DatetimeIndex(['2009-01-01', '2009-01-02', '2009-01-03'], dtype='datetime64[ns]', name='date', freq=None)

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

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

In [108]:data=(   .....:"KORD,19990127, 19:00:00, 18:56:00, 0.8100\n"   .....:"KORD,19990127, 20:00:00, 19:56:00, 0.0100\n"   .....:"KORD,19990127, 21:00:00, 20:56:00, -0.5900\n"   .....:"KORD,19990127, 21:00:00, 21:18:00, -0.9900\n"   .....:"KORD,19990127, 22:00:00, 21:56:00, -0.5900\n"   .....:"KORD,19990127, 23:00:00, 22:56:00, -0.5900"   .....:)   .....:In [109]:withopen("tmp.csv","w")asfh:   .....:fh.write(data)   .....:In [110]:df=pd.read_csv("tmp.csv",header=None,parse_dates=[[1,2],[1,3]])In [111]:dfOut[111]:                  1_2                 1_3     0     40 1999-01-27 19:00:00 1999-01-27 18:56:00  KORD  0.811 1999-01-27 20:00:00 1999-01-27 19:56:00  KORD  0.012 1999-01-27 21:00:00 1999-01-27 20:56:00  KORD -0.593 1999-01-27 21:00:00 1999-01-27 21:18:00  KORD -0.994 1999-01-27 22:00:00 1999-01-27 21:56:00  KORD -0.595 1999-01-27 23:00:00 1999-01-27 22:56:00  KORD -0.59

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

In [112]:df=pd.read_csv(   .....:"tmp.csv",header=None,parse_dates=[[1,2],[1,3]],keep_date_col=True   .....:)   .....:In [113]:dfOut[113]:                  1_2                 1_3     0  ...          2          3     40 1999-01-27 19:00:00 1999-01-27 18:56:00  KORD  ...   19:00:00   18:56:00  0.811 1999-01-27 20:00:00 1999-01-27 19:56:00  KORD  ...   20:00:00   19:56:00  0.012 1999-01-27 21:00:00 1999-01-27 20:56:00  KORD  ...   21:00:00   20:56:00 -0.593 1999-01-27 21:00:00 1999-01-27 21:18:00  KORD  ...   21:00:00   21:18:00 -0.994 1999-01-27 22:00:00 1999-01-27 21:56:00  KORD  ...   22:00:00   21:56:00 -0.595 1999-01-27 23:00:00 1999-01-27 22:56:00  KORD  ...   23:00:00   22:56:00 -0.59[6 rows x 7 columns]

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

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

In [114]:date_spec={"nominal":[1,2],"actual":[1,3]}In [115]:df=pd.read_csv("tmp.csv",header=None,parse_dates=date_spec)In [116]:dfOut[116]:              nominal              actual     0     40 1999-01-27 19:00:00 1999-01-27 18:56:00  KORD  0.811 1999-01-27 20:00:00 1999-01-27 19:56:00  KORD  0.012 1999-01-27 21:00:00 1999-01-27 20:56:00  KORD -0.593 1999-01-27 21:00:00 1999-01-27 21:18:00  KORD -0.994 1999-01-27 22:00:00 1999-01-27 21:56:00  KORD -0.595 1999-01-27 23:00:00 1999-01-27 22:56:00  KORD -0.59

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

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

Note

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

Note

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

Deprecated since version 2.2.0:Combining date columns inside read_csv is deprecated. Usepd.to_datetimeon the relevant result columns instead.

Date parsing functions#

Finally, the parser allows you to specify a customdate_format.Performance-wise, you should try these methods of parsing dates in order:

  1. If you know the format, usedate_format, e.g.:date_format="%d/%m/%Y" ordate_format={column_name:"%d/%m/%Y"}.

  2. If you different formats for different columns, or want to pass any extra options (suchasutc) toto_datetime, then you should read in your data asobject dtype, andthen useto_datetime.

Parsing a CSV with mixed timezones#

pandas cannot natively represent a column or index with mixed timezones. If your CSVfile contains columns with a mixture of timezones, the default result will bean object-dtype column with strings, even withparse_dates.To parse the mixed-timezone values as a datetime column, read in asobject dtype andthen callto_datetime() withutc=True.

In [120]:content="""\   .....:a   .....:2000-01-01T00:00:00+05:00   .....:2000-01-01T00:00:00+06:00"""   .....:In [121]:df=pd.read_csv(StringIO(content))In [122]:df["a"]=pd.to_datetime(df["a"],utc=True)In [123]:df["a"]Out[123]:0   1999-12-31 19:00:00+00:001   1999-12-31 18:00:00+00:00Name: a, dtype: datetime64[ns, UTC]

Inferring datetime format#

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

  • “20111230”

  • “2011/12/30”

  • “20111230 00:00:00”

  • “12/30/2011 00:00:00”

  • “30/Dec/2011 00:00:00”

  • “30/December/2011 00:00:00”

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

If you try to parse a column of date strings, pandas will attempt to guess the formatfrom the first non-NaN element, and will then parse the rest of the column with thatformat. If pandas fails to guess the format (for example if your first string is'01DecemberUS/Pacific2000'), then a warning will be raised and eachrow will be parsed individually bydateutil.parser.parse. The safestway to parse dates is to explicitly setformat=.

In [124]:df=pd.read_csv(   .....:"foo.csv",   .....:index_col=0,   .....:parse_dates=True,   .....:)   .....:In [125]:dfOut[125]:            A  B  Cdate2009-01-01  a  1  22009-01-02  b  3  42009-01-03  c  4  5

In the case that you have mixed datetime formats within the same column, you canpassformat='mixed'

In [126]:data=StringIO("date\n12 Jan 2000\n2000-01-13\n")In [127]:df=pd.read_csv(data)In [128]:df['date']=pd.to_datetime(df['date'],format='mixed')In [129]:dfOut[129]:        date0 2000-01-121 2000-01-13

or, if your datetime formats are all ISO8601 (possibly not identically-formatted):

In [130]:data=StringIO("date\n2020-01-01\n2020-01-01 03:00\n")In [131]:df=pd.read_csv(data)In [132]:df['date']=pd.to_datetime(df['date'],format='ISO8601')In [133]:dfOut[133]:                 date0 2020-01-01 00:00:001 2020-01-01 03:00:00

International date formats#

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

In [134]:data="date,value,cat\n1/6/2000,5,a\n2/6/2000,10,b\n3/6/2000,15,c"In [135]:print(data)date,value,cat1/6/2000,5,a2/6/2000,10,b3/6/2000,15,cIn [136]:withopen("tmp.csv","w")asfh:   .....:fh.write(data)   .....:In [137]:pd.read_csv("tmp.csv",parse_dates=[0])Out[137]:        date  value cat0 2000-01-06      5   a1 2000-02-06     10   b2 2000-03-06     15   cIn [138]:pd.read_csv("tmp.csv",dayfirst=True,parse_dates=[0])Out[138]:        date  value cat0 2000-06-01      5   a1 2000-06-02     10   b2 2000-06-03     15   c

Writing CSVs to binary file objects#

Added in version 1.2.0.

df.to_csv(...,mode="wb") allows writing a CSV to a file objectopened binary mode. In most cases, it is not necessary to specifymode as Pandas will auto-detect whether the file object isopened in text or binary mode.

In [139]:importioIn [140]:data=pd.DataFrame([0,1,2])In [141]:buffer=io.BytesIO()In [142]:data.to_csv(buffer,encoding="utf-8",compression="gzip")

Specifying method for floating-point conversion#

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

In [143]:val="0.3066101993807095471566981359501369297504425048828125"In [144]:data="a,b,c\n1,2,{0}".format(val)In [145]:abs(   .....:pd.read_csv(   .....:StringIO(data),   .....:engine="c",   .....:float_precision=None,   .....:)["c"][0]-float(val)   .....:)   .....:Out[145]:5.551115123125783e-17In [146]:abs(   .....:pd.read_csv(   .....:StringIO(data),   .....:engine="c",   .....:float_precision="high",   .....:)["c"][0]-float(val)   .....:)   .....:Out[146]:5.551115123125783e-17In [147]:abs(   .....:pd.read_csv(StringIO(data),engine="c",float_precision="round_trip")["c"][0]   .....:-float(val)   .....:)   .....:Out[147]:0.0

Thousand separators#

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

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

In [148]:data=(   .....:"ID|level|category\n"   .....:"Patient1|123,000|x\n"   .....:"Patient2|23,000|y\n"   .....:"Patient3|1,234,018|z"   .....:)   .....:In [149]:withopen("tmp.csv","w")asfh:   .....:fh.write(data)   .....:In [150]:df=pd.read_csv("tmp.csv",sep="|")In [151]:dfOut[151]:         ID      level category0  Patient1    123,000        x1  Patient2     23,000        y2  Patient3  1,234,018        zIn [152]:df.level.dtypeOut[152]:dtype('O')

Thethousands keyword allows integers to be parsed correctly:

In [153]:df=pd.read_csv("tmp.csv",sep="|",thousands=",")In [154]:dfOut[154]:         ID    level category0  Patient1   123000        x1  Patient2    23000        y2  Patient3  1234018        zIn [155]:df.level.dtypeOut[155]:dtype('int64')

NA values#

To control which values are parsed as missing values (which are signified byNaN), specify a string inna_values. If you specify a list of strings,then all values in it are considered to be missing values. If you specify anumber (afloat, like5.0 or aninteger like5), thecorresponding equivalent values will also imply a missing value (in this caseeffectively[5.0,5] are recognized asNaN).

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

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

Let us consider some examples:

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

In the example above5 and5.0 will be recognized asNaN, inaddition to the defaults. A string will first be interpreted as a numerical5, then as aNaN.

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

Above, only an empty field will be recognized asNaN.

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

Above, bothNA and0 as strings areNaN.

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

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

Infinity#

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

Boolean values#

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

In [156]:data="a,b,c\n1,Yes,2\n3,No,4"In [157]:print(data)a,b,c1,Yes,23,No,4In [158]:pd.read_csv(StringIO(data))Out[158]:   a    b  c0  1  Yes  21  3   No  4In [159]:pd.read_csv(StringIO(data),true_values=["Yes"],false_values=["No"])Out[159]:   a      b  c0  1   True  21  3  False  4

Handling “bad” lines#

Some files may have malformed lines with too few fields or too many. Lines withtoo few fields will have NA values filled in the trailing fields. Lines withtoo many fields will raise an error by default:

In [160]:data="a,b,c\n1,2,3\n4,5,6,7\n8,9,10"In [161]:pd.read_csv(StringIO(data))---------------------------------------------------------------------------ParserErrorTraceback (most recent call last)CellIn[161],line1---->1pd.read_csv(StringIO(data))File ~/work/pandas/pandas/pandas/io/parsers/readers.py:1026, inread_csv(filepath_or_buffer, sep, delimiter, header, names, index_col, usecols, dtype, engine, converters, true_values, false_values, skipinitialspace, skiprows, skipfooter, nrows, na_values, keep_default_na, na_filter, verbose, skip_blank_lines, parse_dates, infer_datetime_format, keep_date_col, date_parser, date_format, dayfirst, cache_dates, iterator, chunksize, compression, thousands, decimal, lineterminator, quotechar, quoting, doublequote, escapechar, comment, encoding, encoding_errors, dialect, on_bad_lines, delim_whitespace, low_memory, memory_map, float_precision, storage_options, dtype_backend)1013kwds_defaults=_refine_defaults_read(1014dialect,1015delimiter,(...)1022dtype_backend=dtype_backend,1023)1024kwds.update(kwds_defaults)->1026return_read(filepath_or_buffer,kwds)File ~/work/pandas/pandas/pandas/io/parsers/readers.py:626, in_read(filepath_or_buffer, kwds)623returnparser625withparser:-->626returnparser.read(nrows)File ~/work/pandas/pandas/pandas/io/parsers/readers.py:1923, inTextFileReader.read(self, nrows)1916nrows=validate_integer("nrows",nrows)1917try:1918# error: "ParserBase" has no attribute "read"1919(1920index,1921columns,1922col_dict,->1923)=self._engine.read(# type: ignore[attr-defined]1924nrows1925)1926exceptException:1927self.close()File ~/work/pandas/pandas/pandas/io/parsers/c_parser_wrapper.py:234, inCParserWrapper.read(self, nrows)232try:233ifself.low_memory:-->234chunks=self._reader.read_low_memory(nrows)235# destructive to chunks236data=_concatenate_chunks(chunks)File parsers.pyx:838, inpandas._libs.parsers.TextReader.read_low_memory()File parsers.pyx:905, inpandas._libs.parsers.TextReader._read_rows()File parsers.pyx:874, inpandas._libs.parsers.TextReader._tokenize_rows()File parsers.pyx:891, inpandas._libs.parsers.TextReader._check_tokenize_status()File parsers.pyx:2061, inpandas._libs.parsers.raise_parser_error()ParserError: Error tokenizing data. C error: Expected 3 fields in line 3, saw 4

You can elect to skip bad lines:

In [162]:data="a,b,c\n1,2,3\n4,5,6,7\n8,9,10"In [163]:pd.read_csv(StringIO(data),on_bad_lines="skip")Out[163]:   a  b   c0  1  2   31  8  9  10

Added in version 1.4.0.

Or pass a callable function to handle the bad line ifengine="python".The bad line will be a list of strings that was split by thesep:

In [164]:external_list=[]In [165]:defbad_lines_func(line):   .....:external_list.append(line)   .....:returnline[-3:]   .....:In [166]:external_listOut[166]:[]

Note

The callable function will handle only a line with too many fields.Bad lines caused by other errors will be silently skipped.

In [167]:bad_lines_func=lambdaline:print(line)In [168]:data='name,type\nname a,a is of type a\nname b,"b\" is of type b"'In [169]:dataOut[169]:'name,type\nname a,a is of type a\nname b,"b" is of type b"'In [170]:pd.read_csv(StringIO(data),on_bad_lines=bad_lines_func,engine="python")Out[170]:     name            type0  name a  a is of type a

The line was not processed in this case, as a “bad line” here is caused by an escape character.

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

In [171]:pd.read_csv(StringIO(data),usecols=[0,1,2])---------------------------------------------------------------------------ValueErrorTraceback (most recent call last)CellIn[171],line1---->1pd.read_csv(StringIO(data),usecols=[0,1,2])File ~/work/pandas/pandas/pandas/io/parsers/readers.py:1026, inread_csv(filepath_or_buffer, sep, delimiter, header, names, index_col, usecols, dtype, engine, converters, true_values, false_values, skipinitialspace, skiprows, skipfooter, nrows, na_values, keep_default_na, na_filter, verbose, skip_blank_lines, parse_dates, infer_datetime_format, keep_date_col, date_parser, date_format, dayfirst, cache_dates, iterator, chunksize, compression, thousands, decimal, lineterminator, quotechar, quoting, doublequote, escapechar, comment, encoding, encoding_errors, dialect, on_bad_lines, delim_whitespace, low_memory, memory_map, float_precision, storage_options, dtype_backend)1013kwds_defaults=_refine_defaults_read(1014dialect,1015delimiter,(...)1022dtype_backend=dtype_backend,1023)1024kwds.update(kwds_defaults)->1026return_read(filepath_or_buffer,kwds)File ~/work/pandas/pandas/pandas/io/parsers/readers.py:620, in_read(filepath_or_buffer, kwds)617_validate_names(kwds.get("names",None))619# Create the parser.-->620parser=TextFileReader(filepath_or_buffer,**kwds)622ifchunksizeoriterator:623returnparserFile ~/work/pandas/pandas/pandas/io/parsers/readers.py:1620, inTextFileReader.__init__(self, f, engine, **kwds)1617self.options["has_index_names"]=kwds["has_index_names"]1619self.handles:IOHandles|None=None->1620self._engine=self._make_engine(f,self.engine)File ~/work/pandas/pandas/pandas/io/parsers/readers.py:1898, inTextFileReader._make_engine(self, f, engine)1895raiseValueError(msg)1897try:->1898returnmapping[engine](f,**self.options)1899exceptException:1900ifself.handlesisnotNone:File ~/work/pandas/pandas/pandas/io/parsers/c_parser_wrapper.py:155, inCParserWrapper.__init__(self, src, **kwds)152# error: Cannot determine type of 'names'153iflen(self.names)<len(usecols):# type: ignore[has-type]154# error: Cannot determine type of 'names'-->155self._validate_usecols_names(156usecols,157self.names,# type: ignore[has-type]158)160# error: Cannot determine type of 'names'161self._validate_parse_dates_presence(self.names)# type: ignore[has-type]File ~/work/pandas/pandas/pandas/io/parsers/base_parser.py:979, inParserBase._validate_usecols_names(self, usecols, names)977missing=[cforcinusecolsifcnotinnames]978iflen(missing)>0:-->979raiseValueError(980f"Usecols do not match columns, columns expected but not found: "981f"{missing}"982)984returnusecolsValueError: Usecols do not match columns, columns expected but not found: [0, 1, 2]

In case you want to keep all data including the lines with too many fields, you canspecify a sufficient number ofnames. This ensures that lines with not enoughfields are filled withNaN.

In [172]:pd.read_csv(StringIO(data),names=['a','b','c','d'])Out[172]:        a                b   c   d0    name             type NaN NaN1  name a   a is of type a NaN NaN2  name b  b is of type b" NaN NaN

Dialect#

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

Suppose you had data with unenclosed quotes:

In [173]:data="label1,label2,label3\n"'index1,"a,c,e\n'"index2,b,d,f"In [174]:print(data)label1,label2,label3index1,"a,c,eindex2,b,d,f

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

We can get around this usingdialect:

In [175]:importcsvIn [176]:dia=csv.excel()In [177]:dia.quoting=csv.QUOTE_NONEIn [178]:pd.read_csv(StringIO(data),dialect=dia)Out[178]:       label1 label2 label3index1     "a      c      eindex2      b      d      f

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

In [179]:data="a,b,c~1,2,3~4,5,6"In [180]:pd.read_csv(StringIO(data),lineterminator="~")Out[180]:   a  b  c0  1  2  31  4  5  6

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

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

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

Quoting and Escape Characters#

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

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

Files with fixed width columns#

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

  • colspecs: A list of pairs (tuples) giving the extents of thefixed-width fields of each line as half-open intervals (i.e., [from, to[ ).String value ‘infer’ can be used to instruct the parser to try detectingthe column specifications from the first 100 rows of the data. Defaultbehavior, if not specified, is to infer.

  • widths: A list of field widths which can be used instead of ‘colspecs’if the intervals are contiguous.

  • delimiter: Characters to consider as filler characters in the fixed-width file.Can be used to specify the filler character of the fieldsif it is not spaces (e.g., ‘~’).

Consider a typical fixed-width data file:

In [187]:data1=(   .....:"id8141    360.242940   149.910199   11950.7\n"   .....:"id1594    444.953632   166.985655   11788.4\n"   .....:"id1849    364.136849   183.628767   11806.2\n"   .....:"id1230    413.836124   184.375703   11916.8\n"   .....:"id1948    502.953953   173.237159   12468.3"   .....:)   .....:In [188]:withopen("bar.csv","w")asf:   .....:f.write(data1)   .....:

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

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

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

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

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

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

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

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

In [197]:pd.read_fwf("bar.csv",header=None,index_col=0).dtypesOut[197]:1    float642    float643    float64dtype: objectIn [198]:pd.read_fwf("bar.csv",header=None,dtype={2:"object"}).dtypesOut[198]:0     object1    float642     object3    float64dtype: object

Indexes#

Files with an “implicit” index column#

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

In [199]:data="A,B,C\n20090101,a,1,2\n20090102,b,3,4\n20090103,c,4,5"In [200]:print(data)A,B,C20090101,a,1,220090102,b,3,420090103,c,4,5In [201]:withopen("foo.csv","w")asf:   .....:f.write(data)   .....:

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

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

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

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

Reading an index with aMultiIndex#

Suppose you have data indexed by two columns:

In [205]:data='year,indiv,zit,xit\n1977,"A",1.2,.6\n1977,"B",1.5,.5'In [206]:print(data)year,indiv,zit,xit1977,"A",1.2,.61977,"B",1.5,.5In [207]:withopen("mindex_ex.csv",mode="w")asf:   .....:f.write(data)   .....:

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

In [208]:df=pd.read_csv("mindex_ex.csv",index_col=[0,1])In [209]:dfOut[209]:            zit  xityear indiv1977 A      1.2  0.6     B      1.5  0.5In [210]:df.loc[1977]Out[210]:       zit  xitindivA      1.2  0.6B      1.5  0.5

Reading columns with aMultiIndex#

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

In [211]:mi_idx=pd.MultiIndex.from_arrays([[1,2,3,4],list("abcd")],names=list("ab"))In [212]:mi_col=pd.MultiIndex.from_arrays([[1,2],list("ab")],names=list("cd"))In [213]:df=pd.DataFrame(np.ones((4,2)),index=mi_idx,columns=mi_col)In [214]:df.to_csv("mi.csv")In [215]:print(open("mi.csv").read())c,,1,2d,,a,ba,b,,1,a,1.0,1.02,b,1.0,1.03,c,1.0,1.04,d,1.0,1.0In [216]:pd.read_csv("mi.csv",header=[0,1,2,3],index_col=[0,1])Out[216]:c                    1                  2d                    a                  ba   Unnamed: 2_level_2 Unnamed: 3_level_21                  1.0                1.02 b                1.0                1.03 c                1.0                1.04 d                1.0                1.0

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

In [217]:data=",a,a,a,b,c,c\n,q,r,s,t,u,v\none,1,2,3,4,5,6\ntwo,7,8,9,10,11,12"In [218]:print(data),a,a,a,b,c,c,q,r,s,t,u,vone,1,2,3,4,5,6two,7,8,9,10,11,12In [219]:withopen("mi2.csv","w")asfh:   .....:fh.write(data)   .....:In [220]:pd.read_csv("mi2.csv",header=[0,1],index_col=0)Out[220]:     a         b   c     q  r  s   t   u   vone  1  2  3   4   5   6two  7  8  9  10  11  12

Note

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

Automatically “sniffing” the delimiter#

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

In [221]:df=pd.DataFrame(np.random.randn(10,4))In [222]:df.to_csv("tmp2.csv",sep=":",index=False)In [223]:pd.read_csv("tmp2.csv",sep=None,engine="python")Out[223]:          0         1         2         30  0.469112 -0.282863 -1.509059 -1.1356321  1.212112 -0.173215  0.119209 -1.0442362 -0.861849 -2.104569 -0.494929  1.0718043  0.721555 -0.706771 -1.039575  0.2718604 -0.424972  0.567020  0.276232 -1.0874015 -0.673690  0.113648 -1.478427  0.5249886  0.404705  0.577046 -1.715002 -1.0392687 -0.370647 -1.157892 -1.344312  0.8448858  1.075770 -0.109050  1.643563 -1.4693889  0.357021 -0.674600 -1.776904 -0.968914

Reading multiple files to create a single DataFrame#

It’s best to useconcat() to combine multiple files.See thecookbook for an example.

Iterating through files chunk by chunk#

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

In [224]:df=pd.DataFrame(np.random.randn(10,4))In [225]:df.to_csv("tmp.csv",index=False)In [226]:table=pd.read_csv("tmp.csv")In [227]:tableOut[227]:          0         1         2         30 -1.294524  0.413738  0.276662 -0.4720351 -0.013960 -0.362543 -0.006154 -0.9230612  0.895717  0.805244 -1.206412  2.5656463  1.431256  1.340309 -1.170299 -0.2261694  0.410835  0.813850  0.132003 -0.8273175 -0.076467 -1.187678  1.130127 -1.4367376 -1.413681  1.607920  1.024180  0.5696057  0.875906 -2.211372  0.974466 -2.0067478 -0.410001 -0.078638  0.545952 -1.2192179 -1.226825  0.769804 -1.281247 -0.727707

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

In [228]:withpd.read_csv("tmp.csv",chunksize=4)asreader:   .....:print(reader)   .....:forchunkinreader:   .....:print(chunk)   .....:<pandas.io.parsers.readers.TextFileReader object at 0x7fe8deebc0d0>          0         1         2         30 -1.294524  0.413738  0.276662 -0.4720351 -0.013960 -0.362543 -0.006154 -0.9230612  0.895717  0.805244 -1.206412  2.5656463  1.431256  1.340309 -1.170299 -0.226169          0         1         2         34  0.410835  0.813850  0.132003 -0.8273175 -0.076467 -1.187678  1.130127 -1.4367376 -1.413681  1.607920  1.024180  0.5696057  0.875906 -2.211372  0.974466 -2.006747          0         1         2         38 -0.410001 -0.078638  0.545952 -1.2192179 -1.226825  0.769804 -1.281247 -0.727707

Changed in version 1.2:read_csv/json/sas return a context-manager when iterating through a file.

Specifyingiterator=True will also return theTextFileReader object:

In [229]:withpd.read_csv("tmp.csv",iterator=True)asreader:   .....:print(reader.get_chunk(5))   .....:          0         1         2         30 -1.294524  0.413738  0.276662 -0.4720351 -0.013960 -0.362543 -0.006154 -0.9230612  0.895717  0.805244 -1.206412  2.5656463  1.431256  1.340309 -1.170299 -0.2261694  0.410835  0.813850  0.132003 -0.827317

Specifying the parser engine#

Pandas currently supports three engines, the C engine, the python engine, and an experimentalpyarrow engine (requires thepyarrow package). In general, the pyarrow engine is fasteston larger workloads and is equivalent in speed to the C engine on most other workloads.The python engine tends to be slower than the pyarrow and C engines on most workloads. However,the pyarrow engine is much less robust than the C engine, which lacks a few features compared to thePython engine.

Where possible, pandas uses the C parser (specified asengine='c'), but it may fallback to Python if C-unsupported options are specified.

Currently, options unsupported by the C and pyarrow engines include:

  • sep other than a single character (e.g. regex separators)

  • skipfooter

  • sep=None withdelim_whitespace=False

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

Options that are unsupported by the pyarrow engine which are not covered by the list above include:

  • float_precision

  • chunksize

  • comment

  • nrows

  • thousands

  • memory_map

  • dialect

  • on_bad_lines

  • delim_whitespace

  • quoting

  • lineterminator

  • converters

  • decimal

  • iterator

  • dayfirst

  • infer_datetime_format

  • verbose

  • skipinitialspace

  • low_memory

Specifying these options withengine='pyarrow' will raise aValueError.

Reading/writing remote files#

You can pass in a URL to read or write remote files to many of pandas’ IOfunctions - the following example shows reading a CSV file:

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

Added in version 1.3.0.

A custom header can be sent alongside HTTP(s) requests by passing a dictionaryof header key value mappings to thestorage_options keyword argument as shown below:

headers={"User-Agent":"pandas"}df=pd.read_csv("https://download.bls.gov/pub/time.series/cu/cu.item",sep="\t",storage_options=headers)

All URLs which are not local files or HTTP(s) are handled byfsspec, if installed, and its various filesystem implementations(including Amazon S3, Google Cloud, SSH, FTP, webHDFS…).Some of these implementations will require additional packages to beinstalled, for exampleS3 URLs require thes3fs library:

df=pd.read_json("s3://pandas-test/adatafile.json")

When dealing with remote storage systems, you might needextra configuration with environment variables or config files inspecial locations. For example, to access data in your S3 bucket,you will need to define credentials in one of the several ways listed intheS3Fs documentation. The same is truefor several of the storage backends, and you should follow the linksatfsimpl1 for implementations built intofsspec andfsimpl2for those not included in the mainfsspecdistribution.

You can also pass parameters directly to the backend driver. Sincefsspec does notutilize theAWS_S3_HOST environment variable, we can directly define adictionary containing the endpoint_url and pass the object into the storageoption parameter:

storage_options={"client_kwargs":{"endpoint_url":"http://127.0.0.1:5555"}}}df=pd.read_json("s3://pandas-test/test-1",storage_options=storage_options)

More sample configurations and documentation can be found atS3Fs documentation.

If you donot have S3 credentials, you can still access publicdata by specifying an anonymous connection, such as

Added in version 1.2.0.

pd.read_csv("s3://ncei-wcsd-archive/data/processed/SH1305/18kHz/SaKe2013""-D20130523-T080854_to_SaKe2013-D20130523-T085643.csv",storage_options={"anon":True},)

fsspec also allows complex URLs, for accessing data in compressedarchives, local caching of files, and more. To locally cache the aboveexample, you would modify the call to

pd.read_csv("simplecache::s3://ncei-wcsd-archive/data/processed/SH1305/18kHz/""SaKe2013-D20130523-T080854_to_SaKe2013-D20130523-T085643.csv",storage_options={"s3":{"anon":True}},)

where we specify that the “anon” parameter is meant for the “s3” part ofthe implementation, not to the caching implementation. Note that this caches to a temporarydirectory for the duration of the session only, but you can also specifya permanent store.

Writing out data#

Writing to CSV format#

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

  • path_or_buf: A string path to the file to write or a file object. If a file object it must be opened withnewline=''

  • sep : Field delimiter for the output file (default “,”)

  • na_rep: A string representation of a missing value (default ‘’)

  • float_format: Format string for floating point numbers

  • columns: Columns to write (default None)

  • header: Whether to write out the column names (default True)

  • index: whether to write row (index) names (default True)

  • index_label: Column label(s) for index column(s) if desired. If None(default), andheader andindex are True, then the index names areused. (A sequence should be given if theDataFrame uses MultiIndex).

  • mode : Python write mode, default ‘w’

  • encoding: a string representing the encoding to use if the contents arenon-ASCII, for Python versions prior to 3

  • lineterminator: Character sequence denoting line end (defaultos.linesep)

  • quoting: Set quoting rules as in csv module (default csv.QUOTE_MINIMAL). Note that if you have set afloat_format then floats are converted to strings and csv.QUOTE_NONNUMERIC will treat them as non-numeric

  • quotechar: Character used to quote fields (default ‘”’)

  • doublequote: Control quoting ofquotechar in fields (default True)

  • escapechar: Character used to escapesep andquotechar whenappropriate (default None)

  • chunksize: Number of rows to write at a time

  • date_format: Format string for datetime objects

Writing a formatted string#

TheDataFrame object has an instance methodto_string which allows controlover the string representation of the object. All arguments are optional:

  • buf default None, for example a StringIO object

  • columns default None, which columns to write

  • col_space default None, minimum width of each column.

  • na_rep defaultNaN, representation of NA value

  • formatters default None, a dictionary (by column) of functions each ofwhich takes a single argument and returns a formatted string

  • float_format default None, a function which takes a single (float)argument and returns a formatted string; to be applied to floats in theDataFrame.

  • sparsify default True, set to False for aDataFrame with a hierarchicalindex to print every MultiIndex key at each row.

  • index_names default True, will print the names of the indices

  • index default True, will print the index (ie, row labels)

  • header default True, will print the column labels

  • justify defaultleft, will print column headers left- orright-justified

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

JSON#

Read and writeJSON format files and strings.

Writing JSON#

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

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

  • orient :

    Series:
    • default isindex

    • allowed values are {split,records,index}

    DataFrame:
    • default iscolumns

    • allowed values are {split,records,index,columns,values,table}

    The format of the JSON string

    split

    dict like {index -> [index]; columns -> [columns]; data -> [values]}

    records

    list like [{column -> value}; … ]

    index

    dict like {index -> {column -> value}}

    columns

    dict like {column -> {index -> value}}

    values

    just the values array

    table

    adhering to the JSONTable Schema

  • date_format : string, type of date conversion, ‘epoch’ for timestamp, ‘iso’ for ISO8601.

  • double_precision : The number of decimal places to use when encoding floating point values, default 10.

  • force_ascii : force encoded string to be ASCII, default True.

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

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

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

  • mode : string, writer mode when writing to path. ‘w’ for write, ‘a’ for append. Default ‘w’

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

In [230]:dfj=pd.DataFrame(np.random.randn(5,2),columns=list("AB"))In [231]:json=dfj.to_json()In [232]:jsonOut[232]:'{"A":{"0":-0.1213062281,"1":0.6957746499,"2":0.9597255933,"3":-0.6199759194,"4":-0.7323393705},"B":{"0":-0.0978826728,"1":0.3417343559,"2":-1.1103361029,"3":0.1497483186,"4":0.6877383895}}'

Orient options#

There are a number of different options for the format of the resulting JSONfile / string. Consider the followingDataFrame andSeries:

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

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

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

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

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

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

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

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

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

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

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

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

Note

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

Date handling#

Writing in ISO date format:

In [245]:dfd=pd.DataFrame(np.random.randn(5,2),columns=list("AB"))In [246]:dfd["date"]=pd.Timestamp("20130101")In [247]:dfd=dfd.sort_index(axis=1,ascending=False)In [248]:json=dfd.to_json(date_format="iso")In [249]:jsonOut[249]:'{"date":{"0":"2013-01-01T00:00:00.000","1":"2013-01-01T00:00:00.000","2":"2013-01-01T00:00:00.000","3":"2013-01-01T00:00:00.000","4":"2013-01-01T00:00:00.000"},"B":{"0":0.403309524,"1":0.3016244523,"2":-1.3698493577,"3":1.4626960492,"4":-0.8265909164},"A":{"0":0.1764443426,"1":-0.1549507744,"2":-2.1798606054,"3":-0.9542078401,"4":-1.7431609117}}'

Writing in ISO date format, with microseconds:

In [250]:json=dfd.to_json(date_format="iso",date_unit="us")In [251]:jsonOut[251]:'{"date":{"0":"2013-01-01T00:00:00.000000","1":"2013-01-01T00:00:00.000000","2":"2013-01-01T00:00:00.000000","3":"2013-01-01T00:00:00.000000","4":"2013-01-01T00:00:00.000000"},"B":{"0":0.403309524,"1":0.3016244523,"2":-1.3698493577,"3":1.4626960492,"4":-0.8265909164},"A":{"0":0.1764443426,"1":-0.1549507744,"2":-2.1798606054,"3":-0.9542078401,"4":-1.7431609117}}'

Epoch timestamps, in seconds:

In [252]:json=dfd.to_json(date_format="epoch",date_unit="s")In [253]:jsonOut[253]:'{"date":{"0":1,"1":1,"2":1,"3":1,"4":1},"B":{"0":0.403309524,"1":0.3016244523,"2":-1.3698493577,"3":1.4626960492,"4":-0.8265909164},"A":{"0":0.1764443426,"1":-0.1549507744,"2":-2.1798606054,"3":-0.9542078401,"4":-1.7431609117}}'

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

In [254]:dfj2=dfj.copy()In [255]:dfj2["date"]=pd.Timestamp("20130101")In [256]:dfj2["ints"]=list(range(5))In [257]:dfj2["bools"]=TrueIn [258]:dfj2.index=pd.date_range("20130101",periods=5)In [259]:dfj2.to_json("test.json")In [260]:withopen("test.json")asfh:   .....:print(fh.read())   .....:{"A":{"1356998400000":-0.1213062281,"1357084800000":0.6957746499,"1357171200000":0.9597255933,"1357257600000":-0.6199759194,"1357344000000":-0.7323393705},"B":{"1356998400000":-0.0978826728,"1357084800000":0.3417343559,"1357171200000":-1.1103361029,"1357257600000":0.1497483186,"1357344000000":0.6877383895},"date":{"1356998400000":1356,"1357084800000":1356,"1357171200000":1356,"1357257600000":1356,"1357344000000":1356},"ints":{"1356998400000":0,"1357084800000":1,"1357171200000":2,"1357257600000":3,"1357344000000":4},"bools":{"1356998400000":true,"1357084800000":true,"1357171200000":true,"1357257600000":true,"1357344000000":true}}

Fallback behavior#

If the JSON serializer cannot handle the container contents directly it willfall back in the following manner:

  • if the dtype is unsupported (e.g.np.complex_) then thedefault_handler, if provided, will be calledfor each value, otherwise an exception is raised.

  • if an object is unsupported it will attempt the following:

    • check if the object has defined atoDict method and call it.AtoDict method should return adict which will then be JSON serialized.

    • invoke thedefault_handler if one was provided.

    • convert the object to adict by traversing its contents. However this will often failwith anOverflowError or give unexpected results.

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

>>>DataFrame([1.0,2.0,complex(1.0,2.0)]).to_json()# raisesRuntimeError: Unhandled numpy dtype 15

can be dealt with by specifying a simpledefault_handler:

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

Reading JSON#

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

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

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

  • orient :

    Series :
    • default isindex

    • allowed values are {split,records,index}

    DataFrame
    • default iscolumns

    • allowed values are {split,records,index,columns,values,table}

    The format of the JSON string

    split

    dict like {index -> [index]; columns -> [columns]; data -> [values]}

    records

    list like [{column -> value} …]

    index

    dict like {index -> {column -> value}}

    columns

    dict like {column -> {index -> value}}

    values

    just the values array

    table

    adhering to the JSONTable 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 isTrue

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

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

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

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

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

  • chunksize : when used in combination withlines=True, return apandas.api.typing.JsonReader which reads inchunksize lines per iteration.

  • engine: Either"ujson", the built-in JSON parser, or"pyarrow" which dispatches to pyarrow’spyarrow.json.read_json.The"pyarrow" is only available whenlines=True

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

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

Data conversion#

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

Note

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

  • it ends with'_at'

  • it ends with'_time'

  • it begins with'timestamp'

  • it is'modified'

  • it is'date'

Warning

When reading JSON data, automatic coercing into dtypes has some quirks:

  • an index can be reconstructed in a different order from serialization, that is, the returned order is not guaranteed to be the same as before serialization

  • a column that wasfloat data will be converted tointeger if it can be done safely, e.g. a column of1.

  • bool columns will be converted tointeger on reconstruction

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

Reading from a JSON string:

In [262]:fromioimportStringIOIn [263]:pd.read_json(StringIO(json))Out[263]:   date         B         A0     1  0.403310  0.1764441     1  0.301624 -0.1549512     1 -1.369849 -2.1798613     1  1.462696 -0.9542084     1 -0.826591 -1.743161

Reading from a file:

In [264]:pd.read_json("test.json")Out[264]:                   A         B  date  ints  bools2013-01-01 -0.121306 -0.097883  1356     0   True2013-01-02  0.695775  0.341734  1356     1   True2013-01-03  0.959726 -1.110336  1356     2   True2013-01-04 -0.619976  0.149748  1356     3   True2013-01-05 -0.732339  0.687738  1356     4   True

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

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

Specify dtypes for conversion:

In [266]:pd.read_json("test.json",dtype={"A":"float32","bools":"int8"}).dtypesOut[266]:A        float32B        float64date       int64ints       int64bools       int8dtype: object

Preserve string indices:

In [267]:fromioimportStringIOIn [268]:si=pd.DataFrame(   .....:np.zeros((4,4)),columns=list(range(4)),index=[str(i)foriinrange(4)]   .....:)   .....:In [269]:siOut[269]:     0    1    2    30  0.0  0.0  0.0  0.01  0.0  0.0  0.0  0.02  0.0  0.0  0.0  0.03  0.0  0.0  0.0  0.0In [270]:si.indexOut[270]:Index(['0', '1', '2', '3'], dtype='object')In [271]:si.columnsOut[271]:Index([0, 1, 2, 3], dtype='int64')In [272]:json=si.to_json()In [273]:sij=pd.read_json(StringIO(json),convert_axes=False)In [274]:sijOut[274]:   0  1  2  30  0  0  0  01  0  0  0  02  0  0  0  03  0  0  0  0In [275]:sij.indexOut[275]:Index(['0', '1', '2', '3'], dtype='object')In [276]:sij.columnsOut[276]:Index(['0', '1', '2', '3'], dtype='object')

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

In [277]:fromioimportStringIOIn [278]:json=dfj2.to_json(date_unit="ns")# Try to parse timestamps as milliseconds -> Won't WorkIn [279]:dfju=pd.read_json(StringIO(json),date_unit="ms")In [280]:dfjuOut[280]:                            A         B        date  ints  bools1356998400000000000 -0.121306 -0.097883  1356998400     0   True1357084800000000000  0.695775  0.341734  1356998400     1   True1357171200000000000  0.959726 -1.110336  1356998400     2   True1357257600000000000 -0.619976  0.149748  1356998400     3   True1357344000000000000 -0.732339  0.687738  1356998400     4   True# Let pandas detect the correct precisionIn [281]:dfju=pd.read_json(StringIO(json))In [282]:dfjuOut[282]:                   A         B       date  ints  bools2013-01-01 -0.121306 -0.097883 2013-01-01     0   True2013-01-02  0.695775  0.341734 2013-01-01     1   True2013-01-03  0.959726 -1.110336 2013-01-01     2   True2013-01-04 -0.619976  0.149748 2013-01-01     3   True2013-01-05 -0.732339  0.687738 2013-01-01     4   True# Or specify that all timestamps are in nanosecondsIn [283]:dfju=pd.read_json(StringIO(json),date_unit="ns")In [284]:dfjuOut[284]:                   A         B        date  ints  bools2013-01-01 -0.121306 -0.097883  1356998400     0   True2013-01-02  0.695775  0.341734  1356998400     1   True2013-01-03  0.959726 -1.110336  1356998400     2   True2013-01-04 -0.619976  0.149748  1356998400     3   True2013-01-05 -0.732339  0.687738  1356998400     4   True

By setting thedtype_backend argument you can control the default dtypes used for the resulting DataFrame.

In [285]:data=(   .....:'{"a":{"0":1,"1":3},"b":{"0":2.5,"1":4.5},"c":{"0":true,"1":false},"d":{"0":"a","1":"b"},'   .....:'"e":{"0":null,"1":6.0},"f":{"0":null,"1":7.5},"g":{"0":null,"1":true},"h":{"0":null,"1":"a"},'   .....:'"i":{"0":"12-31-2019","1":"12-31-2019"},"j":{"0":null,"1":null}}'   .....:)   .....:In [286]:df=pd.read_json(StringIO(data),dtype_backend="pyarrow")In [287]:dfOut[287]:   a    b      c  d     e     f     g     h           i     j0  1  2.5   True  a  <NA>  <NA>  <NA>  <NA>  12-31-2019  None1  3  4.5  False  b     6   7.5  True     a  12-31-2019  NoneIn [288]:df.dtypesOut[288]:a     int64[pyarrow]b    double[pyarrow]c      bool[pyarrow]d    string[pyarrow]e     int64[pyarrow]f    double[pyarrow]g      bool[pyarrow]h    string[pyarrow]i    string[pyarrow]j      null[pyarrow]dtype: object

Normalization#

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

In [289]:data=[   .....:{"id":1,"name":{"first":"Coleen","last":"Volk"}},   .....:{"name":{"given":"Mark","family":"Regner"}},   .....:{"id":2,"name":"Faye Raker"},   .....:]   .....:In [290]:pd.json_normalize(data)Out[290]:    id name.first name.last name.given name.family        name0  1.0     Coleen      Volk        NaN         NaN         NaN1  NaN        NaN       NaN       Mark      Regner         NaN2  2.0        NaN       NaN        NaN         NaN  Faye Raker
In [291]:data=[   .....:{   .....:"state":"Florida",   .....:"shortname":"FL",   .....:"info":{"governor":"Rick Scott"},   .....:"county":[   .....:{"name":"Dade","population":12345},   .....:{"name":"Broward","population":40000},   .....:{"name":"Palm Beach","population":60000},   .....:],   .....:},   .....:{   .....:"state":"Ohio",   .....:"shortname":"OH",   .....:"info":{"governor":"John Kasich"},   .....:"county":[   .....:{"name":"Summit","population":1234},   .....:{"name":"Cuyahoga","population":1337},   .....:],   .....:},   .....:]   .....:In [292]:pd.json_normalize(data,"county",["state","shortname",["info","governor"]])Out[292]:         name  population    state shortname info.governor0        Dade       12345  Florida        FL    Rick Scott1     Broward       40000  Florida        FL    Rick Scott2  Palm Beach       60000  Florida        FL    Rick Scott3      Summit        1234     Ohio        OH   John Kasich4    Cuyahoga        1337     Ohio        OH   John Kasich

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

In [293]:data=[   .....:{   .....:"CreatedBy":{"Name":"User001"},   .....:"Lookup":{   .....:"TextField":"Some text",   .....:"UserField":{"Id":"ID001","Name":"Name001"},   .....:},   .....:"Image":{"a":"b"},   .....:}   .....:]   .....:In [294]:pd.json_normalize(data,max_level=1)Out[294]:  CreatedBy.Name Lookup.TextField                    Lookup.UserField Image.a0        User001        Some text  {'Id': 'ID001', 'Name': 'Name001'}       b

Line delimited json#

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

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

In [295]:fromioimportStringIOIn [296]:jsonl="""   .....:    {"a": 1, "b": 2}   .....:    {"a": 3, "b": 4}   .....:"""   .....:In [297]:df=pd.read_json(StringIO(jsonl),lines=True)In [298]:dfOut[298]:   a  b0  1  21  3  4In [299]:df.to_json(orient="records",lines=True)Out[299]:'{"a":1,"b":2}\n{"a":3,"b":4}\n'# reader is an iterator that returns ``chunksize`` lines each iterationIn [300]:withpd.read_json(StringIO(jsonl),lines=True,chunksize=1)asreader:   .....:reader   .....:forchunkinreader:   .....:print(chunk)   .....:Empty DataFrameColumns: []Index: []   a  b0  1  2   a  b1  3  4

Line-limited json can also be read using the pyarrow reader by specifyingengine="pyarrow".

In [301]:fromioimportBytesIOIn [302]:df=pd.read_json(BytesIO(jsonl.encode()),lines=True,engine="pyarrow")In [303]:dfOut[303]:   a  b0  1  21  3  4

Added in version 2.0.0.

Table schema#

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

In [304]:df=pd.DataFrame(   .....:{   .....:"A":[1,2,3],   .....:"B":["a","b","c"],   .....:"C":pd.date_range("2016-01-01",freq="d",periods=3),   .....:},   .....:index=pd.Index(range(3),name="idx"),   .....:)   .....:In [305]:dfOut[305]:     A  B          Cidx0    1  a 2016-01-011    2  b 2016-01-022    3  c 2016-01-03In [306]:df.to_json(orient="table",date_format="iso")Out[306]:'{"schema":{"fields":[{"name":"idx","type":"integer"},{"name":"A","type":"integer"},{"name":"B","type":"string"},{"name":"C","type":"datetime"}],"primaryKey":["idx"],"pandas_version":"1.4.0"},"data":[{"idx":0,"A":1,"B":"a","C":"2016-01-01T00:00:00.000"},{"idx":1,"A":2,"B":"b","C":"2016-01-02T00:00:00.000"},{"idx":2,"A":3,"B":"c","C":"2016-01-03T00:00:00.000"}]}'

Theschema field contains thefields key, which itself containsa list of column name to type pairs, including theIndex orMultiIndex(see below for a list of types).Theschema field also contains aprimaryKey field if the (Multi)indexis unique.

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

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

pandas 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:

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

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

    In [307]:frompandas.io.jsonimportbuild_table_schemaIn [308]:s=pd.Series(pd.date_range("2016",periods=4))In [309]:build_table_schema(s)Out[309]:{'fields': [{'name': 'index', 'type': 'integer'},  {'name': 'values', 'type': 'datetime'}], 'primaryKey': ['index'], 'pandas_version': '1.4.0'}
  • datetimes with a timezone (before serializing), include an additional fieldtz with the time zone name (e.g.'US/Central').

    In [310]:s_tz=pd.Series(pd.date_range("2016",periods=12,tz="US/Central"))In [311]:build_table_schema(s_tz)Out[311]:{'fields': [{'name': 'index', 'type': 'integer'},  {'name': 'values', 'type': 'datetime', 'tz': 'US/Central'}], 'primaryKey': ['index'], 'pandas_version': '1.4.0'}
  • Periods are converted to timestamps before serialization, and so have thesame behavior of being converted to UTC. In addition, periods will containand additional fieldfreq with the period’s frequency, e.g.'A-DEC'.

    In [312]:s_per=pd.Series(1,index=pd.period_range("2016",freq="Y-DEC",periods=4))In [313]:build_table_schema(s_per)Out[313]:{'fields': [{'name': 'index', 'type': 'datetime', 'freq': 'YE-DEC'},  {'name': 'values', 'type': 'integer'}], 'primaryKey': ['index'], 'pandas_version': '1.4.0'}
  • Categoricals use theany type and anenum constraint listingthe set of possible values. Additionally, anordered field is included:

    In [314]:s_cat=pd.Series(pd.Categorical(["a","b","a"]))In [315]:build_table_schema(s_cat)Out[315]:{'fields': [{'name': 'index', 'type': 'integer'},  {'name': 'values',   'type': 'any',   'constraints': {'enum': ['a', 'b']},   'ordered': False}], 'primaryKey': ['index'], 'pandas_version': '1.4.0'}
  • AprimaryKey field, containing an array of labels, is includedif the index is unique:

    In [316]:s_dupe=pd.Series([1,2],index=[1,1])In [317]:build_table_schema(s_dupe)Out[317]:{'fields': [{'name': 'index', 'type': 'integer'},  {'name': 'values', 'type': 'integer'}], 'pandas_version': '1.4.0'}
  • TheprimaryKey behavior is the same with MultiIndexes, but in thiscase theprimaryKey is an array:

    In [318]:s_multi=pd.Series(1,index=pd.MultiIndex.from_product([("a","b"),(0,1)]))In [319]:build_table_schema(s_multi)Out[319]:{'fields': [{'name': 'level_0', 'type': 'string'},  {'name': 'level_1', 'type': 'integer'},  {'name': 'values', 'type': 'integer'}], 'primaryKey': FrozenList(['level_0', 'level_1']), 'pandas_version': '1.4.0'}
  • The default naming roughly follows these rules:

    • For series, theobject.name is used. If that’s none, then thename isvalues

    • ForDataFrames, the stringified version of the column name is used

    • ForIndex (notMultiIndex),index.name is used, with afallback toindex if that is None.

    • ForMultiIndex,mi.names is used. If any level has no name,thenlevel_<i> is used.

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

In [320]:df=pd.DataFrame(   .....:{   .....:"foo":[1,2,3,4],   .....:"bar":["a","b","c","d"],   .....:"baz":pd.date_range("2018-01-01",freq="d",periods=4),   .....:"qux":pd.Categorical(["a","b","c","c"]),   .....:},   .....:index=pd.Index(range(4),name="idx"),   .....:)   .....:In [321]:dfOut[321]:     foo bar        baz quxidx0      1   a 2018-01-01   a1      2   b 2018-01-02   b2      3   c 2018-01-03   c3      4   d 2018-01-04   cIn [322]:df.dtypesOut[322]:foo             int64bar            objectbaz    datetime64[ns]qux          categorydtype: objectIn [323]:df.to_json("test.json",orient="table")In [324]:new_df=pd.read_json("test.json",orient="table")In [325]:new_dfOut[325]:     foo bar        baz quxidx0      1   a 2018-01-01   a1      2   b 2018-01-02   b2      3   c 2018-01-03   c3      4   d 2018-01-04   cIn [326]:new_df.dtypesOut[326]:foo             int64bar            objectbaz    datetime64[ns]qux          categorydtype: object

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

In [327]:df.index.name="index"In [328]:df.to_json("test.json",orient="table")In [329]:new_df=pd.read_json("test.json",orient="table")In [330]:print(new_df.index.name)None

When usingorient='table' along with user-definedExtensionArray,the generated schema will contain an additionalextDtype key in the respectivefields element. This extra key is not standard but does enable JSON roundtripsfor extension types (e.g.read_json(df.to_json(orient="table"),orient="table")).

TheextDtype key carries the name of the extension, if you have properly registeredtheExtensionDtype, pandas will use said name to perform a lookup into the registryand re-convert the serialized data into your custom dtype.

HTML#

Reading HTML content#

Warning

Wehighly encourage you to read theHTML Table Parsing gotchasbelow regarding the issues surrounding the BeautifulSoup4/html5lib/lxml parsers.

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

Note

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

Read a URL with no options:

In [320]:url="https://www.fdic.gov/resources/resolutions/bank-failures/failed-bank-list"In [321]:pd.read_html(url)Out[321]:[                         Bank NameBank           CityCity StateSt  ...              Acquiring InstitutionAI Closing DateClosing FundFund 0                    Almena State Bank             Almena      KS  ...                          Equity Bank    October 23, 2020    10538 1           First City Bank of Florida  Fort Walton Beach      FL  ...            United Fidelity Bank, fsb    October 16, 2020    10537 2                 The First State Bank      Barboursville      WV  ...                       MVB Bank, Inc.       April 3, 2020    10536 3                   Ericson State Bank            Ericson      NE  ...           Farmers and Merchants Bank   February 14, 2020    10535 4     City National Bank of New Jersey             Newark      NJ  ...                      Industrial Bank    November 1, 2019    10534 ..                                 ...                ...     ...  ...                                  ...                 ...      ... 558                 Superior Bank, FSB           Hinsdale      IL  ...                Superior Federal, FSB       July 27, 2001     6004 559                Malta National Bank              Malta      OH  ...                    North Valley Bank         May 3, 2001     4648 560    First Alliance Bank & Trust Co.         Manchester      NH  ...  Southern New Hampshire Bank & Trust    February 2, 2001     4647 561  National State Bank of Metropolis         Metropolis      IL  ...              Banterra Bank of Marion   December 14, 2000     4646 562                   Bank of Honolulu           Honolulu      HI  ...                   Bank of the Orient    October 13, 2000     4645 [563 rows x 7 columns]]

Note

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

Read a URL while passing headers alongside the HTTP request:

In [322]:url='https://www.sump.org/notes/request/'# HTTP request reflectorIn [323]:pd.read_html(url)Out[323]:[                   0                    1 0     Remote Socket:  51.15.105.256:51760 1  Protocol Version:             HTTP/1.1 2    Request Method:                  GET 3       Request URI:      /notes/request/ 4     Request Query:                  NaN, 0   Accept-Encoding:             identity 1              Host:         www.sump.org 2        User-Agent:    Python-urllib/3.8 3        Connection:                close]In [324]:headers={In [325]:'User-Agent':'Mozilla Firefox v14.0',In [326]:'Accept':'application/json',In [327]:'Connection':'keep-alive',In [328]:'Auth':'Bearer 2*/f3+fe68df*4'In [329]:}In [340]:pd.read_html(url,storage_options=headers)Out[340]:[                   0                    1 0     Remote Socket:  51.15.105.256:51760 1  Protocol Version:             HTTP/1.1 2    Request Method:                  GET 3       Request URI:      /notes/request/ 4     Request Query:                  NaN, 0        User-Agent: Mozilla Firefox v14.0 1    AcceptEncoding:   gzip,  deflate,  br 2            Accept:      application/json 3        Connection:             keep-alive 4              Auth:  Bearer 2*/f3+fe68df*4]

Note

We see above that the headers we passed are reflected in the HTTP request.

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

In [331]:html_str="""   .....:         <table>   .....:             <tr>   .....:                 <th>A</th>   .....:                 <th colspan="1">B</th>   .....:                 <th rowspan="1">C</th>   .....:             </tr>   .....:             <tr>   .....:                 <td>a</td>   .....:                 <td>b</td>   .....:                 <td>c</td>   .....:             </tr>   .....:         </table>   .....:     """   .....:In [332]:withopen("tmp.html","w")asf:   .....:f.write(html_str)   .....:In [333]:df=pd.read_html("tmp.html")In [334]:df[0]Out[334]:   A  B  C0  a  b  c

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

In [335]:dfs=pd.read_html(StringIO(html_str))In [336]:dfs[0]Out[336]:   A  B  C0  a  b  c

Note

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

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

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

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

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

Specify an index column:

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

Specify a number of rows to skip:

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

Specify a number of rows to skip using a list (range worksas well):

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

Specify an HTML attribute:

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

Specify values that should be converted to NaN:

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

Specify whether to keep the default set of NaN values:

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

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

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

Use some combination of the above:

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

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

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

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

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

Or you could passflavor='lxml' without a list:

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

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

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

Links can be extracted from cells along with the text usingextract_links="all".

In [337]:html_table="""   .....:<table>   .....:  <tr>   .....:    <th>GitHub</th>   .....:  </tr>   .....:  <tr>   .....:    <td><a href="https://github.com/pandas-dev/pandas">pandas</a></td>   .....:  </tr>   .....:</table>   .....:"""   .....:In [338]:df=pd.read_html(   .....:StringIO(html_table),   .....:extract_links="all"   .....:)[0]   .....:In [339]:dfOut[339]:                                   (GitHub, None)0  (pandas, https://github.com/pandas-dev/pandas)In [340]:df[("GitHub",None)]Out[340]:0    (pandas, https://github.com/pandas-dev/pandas)Name: (GitHub, None), dtype: objectIn [341]:df[("GitHub",None)].str[1]Out[341]:0    https://github.com/pandas-dev/pandasName: (GitHub, None), dtype: object

Added in version 1.5.0.

Writing to HTML files#

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

Note

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

Note

In an HTML-rendering supported environment like a Jupyter Notebook,display(HTML(...))`will render the raw HTML into the environment.

In [342]:fromIPython.displayimportdisplay,HTMLIn [343]:df=pd.DataFrame(np.random.randn(2,2))In [344]:dfOut[344]:          0         10 -0.345352  1.3142321  0.690579  0.995761In [345]:html=df.to_html()In [346]:print(html)# raw html<table border="1" class="dataframe">  <thead>    <tr style="text-align: right;">      <th></th>      <th>0</th>      <th>1</th>    </tr>  </thead>  <tbody>    <tr>      <th>0</th>      <td>-0.345352</td>      <td>1.314232</td>    </tr>    <tr>      <th>1</th>      <td>0.690579</td>      <td>0.995761</td>    </tr>  </tbody></table>In [347]:display(HTML(html))<IPython.core.display.HTML object>

Thecolumns argument will limit the columns shown:

In [348]:html=df.to_html(columns=[0])In [349]:print(html)<table border="1" class="dataframe">  <thead>    <tr style="text-align: right;">      <th></th>      <th>0</th>    </tr>  </thead>  <tbody>    <tr>      <th>0</th>      <td>-0.345352</td>    </tr>    <tr>      <th>1</th>      <td>0.690579</td>    </tr>  </tbody></table>In [350]:display(HTML(html))<IPython.core.display.HTML object>

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

In [351]:html=df.to_html(float_format="{0:.10f}".format)In [352]:print(html)<table border="1" class="dataframe">  <thead>    <tr style="text-align: right;">      <th></th>      <th>0</th>      <th>1</th>    </tr>  </thead>  <tbody>    <tr>      <th>0</th>      <td>-0.3453521949</td>      <td>1.3142323796</td>    </tr>    <tr>      <th>1</th>      <td>0.6905793352</td>      <td>0.9957609037</td>    </tr>  </tbody></table>In [353]:display(HTML(html))<IPython.core.display.HTML object>

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

In [354]:html=df.to_html(bold_rows=False)In [355]:print(html)<table border="1" class="dataframe">  <thead>    <tr style="text-align: right;">      <th></th>      <th>0</th>      <th>1</th>    </tr>  </thead>  <tbody>    <tr>      <td>0</td>      <td>-0.345352</td>      <td>1.314232</td>    </tr>    <tr>      <td>1</td>      <td>0.690579</td>      <td>0.995761</td>    </tr>  </tbody></table>In [356]:display(HTML(html))<IPython.core.display.HTML object>

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

In [357]:print(df.to_html(classes=["awesome_table_class","even_more_awesome_class"]))<table border="1" class="dataframe awesome_table_class even_more_awesome_class">  <thead>    <tr style="text-align: right;">      <th></th>      <th>0</th>      <th>1</th>    </tr>  </thead>  <tbody>    <tr>      <th>0</th>      <td>-0.345352</td>      <td>1.314232</td>    </tr>    <tr>      <th>1</th>      <td>0.690579</td>      <td>0.995761</td>    </tr>  </tbody></table>

Therender_links argument provides the ability to add hyperlinks to cellsthat contain URLs.

In [358]:url_df=pd.DataFrame(   .....:{   .....:"name":["Python","pandas"],   .....:"url":["https://www.python.org/","https://pandas.pydata.org"],   .....:}   .....:)   .....:In [359]:html=url_df.to_html(render_links=True)In [360]:print(html)<table border="1" class="dataframe">  <thead>    <tr style="text-align: right;">      <th></th>      <th>name</th>      <th>url</th>    </tr>  </thead>  <tbody>    <tr>      <th>0</th>      <td>Python</td>      <td><a href="https://www.python.org/" target="_blank">https://www.python.org/</a></td>    </tr>    <tr>      <th>1</th>      <td>pandas</td>      <td><a href="https://pandas.pydata.org" target="_blank">https://pandas.pydata.org</a></td>    </tr>  </tbody></table>In [361]:display(HTML(html))<IPython.core.display.HTML object>

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

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

Escaped:

In [363]:html=df.to_html()In [364]:print(html)<table border="1" class="dataframe">  <thead>    <tr style="text-align: right;">      <th></th>      <th>a</th>      <th>b</th>    </tr>  </thead>  <tbody>    <tr>      <th>0</th>      <td>&amp;</td>      <td>2.396780</td>    </tr>    <tr>      <th>1</th>      <td>&lt;</td>      <td>0.014871</td>    </tr>    <tr>      <th>2</th>      <td>&gt;</td>      <td>3.357427</td>    </tr>  </tbody></table>In [365]:display(HTML(html))<IPython.core.display.HTML object>

Not escaped:

In [366]:html=df.to_html(escape=False)In [367]:print(html)<table border="1" class="dataframe">  <thead>    <tr style="text-align: right;">      <th></th>      <th>a</th>      <th>b</th>    </tr>  </thead>  <tbody>    <tr>      <th>0</th>      <td>&</td>      <td>2.396780</td>    </tr>    <tr>      <th>1</th>      <td><</td>      <td>0.014871</td>    </tr>    <tr>      <th>2</th>      <td>></td>      <td>3.357427</td>    </tr>  </tbody></table>In [368]:display(HTML(html))<IPython.core.display.HTML object>

Note

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

HTML Table Parsing Gotchas#

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

Issues withlxml

  • Benefits

    • lxml is very fast.

    • lxml requires Cython to install correctly.

  • Drawbacks

    • lxml doesnot make any guarantees about the results of its parseunless it is givenstrictly valid markup.

    • In light of the above, we have chosen to allow you, the user, to use thelxml backend, butthis backend will usehtml5lib iflxmlfails to parse

    • It is thereforehighly recommended that you install bothBeautifulSoup4 andhtml5lib, so that you will still get a validresult (provided everything else is valid) even iflxml fails.

Issues withBeautifulSoup4usinglxmlas a backend

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

Issues withBeautifulSoup4usinghtml5libas a backend

  • Benefits

    • html5lib is far more lenient thanlxml and consequently dealswithreal-life markup in a much saner way rather than just, e.g.,dropping an element without notifying you.

    • html5libgenerates valid HTML5 markup from invalid markupautomatically. This is extremely important for parsing HTML tables,since it guarantees a valid document. However, that does NOT mean thatit is “correct”, since the process of fixing markup does not have asingle definition.

    • html5lib is pure Python and requires no additional build steps beyondits own installation.

  • Drawbacks

    • The biggest drawback to usinghtml5lib is that it is slow asmolasses. However consider the fact that many tables on the web are notbig enough for the parsing algorithm runtime to matter. It is morelikely that the bottleneck will be in the process of reading the rawtext from the URL over the web, i.e., IO (input-output). For very largetables, this might not be true.

LaTeX#

Added in version 1.3.0.

Currently there are no methods to read from LaTeX, only output methods.

Writing to LaTeX files#

Note

DataFrameand Styler objects currently have ato_latex method. We recommendusing theStyler.to_latex() methodoverDataFrame.to_latex() due to the former’s greater flexibility withconditional styling, and the latter’s possible future deprecation.

Review the documentation forStyler.to_latex,which gives examples of conditional styling and explains the operation of its keywordarguments.

For simple application the following pattern is sufficient.

In [369]:df=pd.DataFrame([[1,2],[3,4]],index=["a","b"],columns=["c","d"])In [370]:print(df.style.to_latex())\begin{tabular}{lrr} & c & d \\a & 1 & 2 \\b & 3 & 4 \\\end{tabular}

To format values before output, chain theStyler.formatmethod.

In [371]:print(df.style.format("€{}").to_latex())\begin{tabular}{lrr} & c & d \\a & € 1 & € 2 \\b & € 3 & € 4 \\\end{tabular}

XML#

Reading XML#

Added in version 1.3.0.

The top-levelread_xml() function can accept an XMLstring/file/URL and will parse nodes and attributes into a pandasDataFrame.

Note

Since there is no standard XML structure where design types can vary inmany ways,read_xml works best with flatter, shallow versions. Ifan XML document is deeply nested, use thestylesheet feature totransform XML into a flatter version.

Let’s look at a few examples.

Read an XML string:

In [372]:fromioimportStringIOIn [373]:xml="""<?xml version="1.0" encoding="UTF-8"?>   .....:<bookstore>   .....:  <book category="cooking">   .....:    <title lang="en">Everyday Italian</title>   .....:    <author>Giada De Laurentiis</author>   .....:    <year>2005</year>   .....:    <price>30.00</price>   .....:  </book>   .....:  <book category="children">   .....:    <title lang="en">Harry Potter</title>   .....:    <author>J K. Rowling</author>   .....:    <year>2005</year>   .....:    <price>29.99</price>   .....:  </book>   .....:  <book category="web">   .....:    <title lang="en">Learning XML</title>   .....:    <author>Erik T. Ray</author>   .....:    <year>2003</year>   .....:    <price>39.95</price>   .....:  </book>   .....:</bookstore>"""   .....:In [374]:df=pd.read_xml(StringIO(xml))In [375]:dfOut[375]:   category             title               author  year  price0   cooking  Everyday Italian  Giada De Laurentiis  2005  30.001  children      Harry Potter         J K. Rowling  2005  29.992       web      Learning XML          Erik T. Ray  2003  39.95

Read a URL with no options:

In [376]:df=pd.read_xml("https://www.w3schools.com/xml/books.xml")In [377]:dfOut[377]:   category              title                  author  year  price      cover0   cooking   Everyday Italian     Giada De Laurentiis  2005  30.00       None1  children       Harry Potter            J K. Rowling  2005  29.99       None2       web  XQuery Kick Start  Vaidyanathan Nagarajan  2003  49.99       None3       web       Learning XML             Erik T. Ray  2003  39.95  paperback

Read in the content of the “books.xml” file and pass it toread_xmlas a string:

In [378]:file_path="books.xml"In [379]:withopen(file_path,"w")asf:   .....:f.write(xml)   .....:In [380]:withopen(file_path,"r")asf:   .....:df=pd.read_xml(StringIO(f.read()))   .....:In [381]:dfOut[381]:   category             title               author  year  price0   cooking  Everyday Italian  Giada De Laurentiis  2005  30.001  children      Harry Potter         J K. Rowling  2005  29.992       web      Learning XML          Erik T. Ray  2003  39.95

Read in the content of the “books.xml” as instance ofStringIO orBytesIO and pass it toread_xml:

In [382]:withopen(file_path,"r")asf:   .....:sio=StringIO(f.read())   .....:In [383]:df=pd.read_xml(sio)In [384]:dfOut[384]:   category             title               author  year  price0   cooking  Everyday Italian  Giada De Laurentiis  2005  30.001  children      Harry Potter         J K. Rowling  2005  29.992       web      Learning XML          Erik T. Ray  2003  39.95
In [385]:withopen(file_path,"rb")asf:   .....:bio=BytesIO(f.read())   .....:In [386]:df=pd.read_xml(bio)In [387]:dfOut[387]:   category             title               author  year  price0   cooking  Everyday Italian  Giada De Laurentiis  2005  30.001  children      Harry Potter         J K. Rowling  2005  29.992       web      Learning XML          Erik T. Ray  2003  39.95

Even read XML from AWS S3 buckets such as NIH NCBI PMC Article Datasets providingBiomedical and Life Science Jorurnals:

In [388]:df=pd.read_xml(   .....:"s3://pmc-oa-opendata/oa_comm/xml/all/PMC1236943.xml",   .....:xpath=".//journal-meta",   .....:)   .....:In [389]:dfOut[389]:              journal-id              journal-title       issn  publisher0  Cardiovasc Ultrasound  Cardiovascular Ultrasound  1476-7120        NaN

Withlxml as defaultparser, you access the full-featured XML librarythat extends Python’s ElementTree API. One powerful tool is ability to querynodes selectively or conditionally with more expressive XPath:

In [390]:df=pd.read_xml(file_path,xpath="//book[year=2005]")In [391]:dfOut[391]:   category             title               author  year  price0   cooking  Everyday Italian  Giada De Laurentiis  2005  30.001  children      Harry Potter         J K. Rowling  2005  29.99

Specify only elements or only attributes to parse:

In [392]:df=pd.read_xml(file_path,elems_only=True)In [393]:dfOut[393]:              title               author  year  price0  Everyday Italian  Giada De Laurentiis  2005  30.001      Harry Potter         J K. Rowling  2005  29.992      Learning XML          Erik T. Ray  2003  39.95
In [394]:df=pd.read_xml(file_path,attrs_only=True)In [395]:dfOut[395]:   category0   cooking1  children2       web

XML documents can have namespaces with prefixes and default namespaces withoutprefixes both of which are denoted with a special attributexmlns. In orderto parse by node under a namespace context,xpath must reference a prefix.

For example, below XML contains a namespace with prefix,doc, and URI athttps://example.com. In order to parsedoc:row nodes,namespaces must be used.

In [396]:xml="""<?xml version='1.0' encoding='utf-8'?>   .....:<doc:data xmlns:doc="https://example.com">   .....:  <doc:row>   .....:    <doc:shape>square</doc:shape>   .....:    <doc:degrees>360</doc:degrees>   .....:    <doc:sides>4.0</doc:sides>   .....:  </doc:row>   .....:  <doc:row>   .....:    <doc:shape>circle</doc:shape>   .....:    <doc:degrees>360</doc:degrees>   .....:    <doc:sides/>   .....:  </doc:row>   .....:  <doc:row>   .....:    <doc:shape>triangle</doc:shape>   .....:    <doc:degrees>180</doc:degrees>   .....:    <doc:sides>3.0</doc:sides>   .....:  </doc:row>   .....:</doc:data>"""   .....:In [397]:df=pd.read_xml(StringIO(xml),   .....:xpath="//doc:row",   .....:namespaces={"doc":"https://example.com"})   .....:In [398]:dfOut[398]:      shape  degrees  sides0    square      360    4.01    circle      360    NaN2  triangle      180    3.0

Similarly, an XML document can have a default namespace without prefix. Failingto assign a temporary prefix will return no nodes and raise aValueError.But assigningany temporary name to correct URI allows parsing by nodes.

In [399]:xml="""<?xml version='1.0' encoding='utf-8'?>   .....:<data xmlns="https://example.com">   .....: <row>   .....:   <shape>square</shape>   .....:   <degrees>360</degrees>   .....:   <sides>4.0</sides>   .....: </row>   .....: <row>   .....:   <shape>circle</shape>   .....:   <degrees>360</degrees>   .....:   <sides/>   .....: </row>   .....: <row>   .....:   <shape>triangle</shape>   .....:   <degrees>180</degrees>   .....:   <sides>3.0</sides>   .....: </row>   .....:</data>"""   .....:In [400]:df=pd.read_xml(StringIO(xml),   .....:xpath="//pandas:row",   .....:namespaces={"pandas":"https://example.com"})   .....:In [401]:dfOut[401]:      shape  degrees  sides0    square      360    4.01    circle      360    NaN2  triangle      180    3.0

However, if XPath does not reference node names such as default,/*, thennamespaces is not required.

Note

Sincexpath identifies the parent of content to be parsed, only immediatedesendants which include child nodes or current attributes are parsed.Therefore,read_xml will not parse the text of grandchildren or otherdescendants and will not parse attributes of any descendant. To retrievelower level content, adjust xpath to lower level. For example,

In [402]:xml="""   .....:<data>   .....:  <row>   .....:    <shape sides="4">square</shape>   .....:    <degrees>360</degrees>   .....:  </row>   .....:  <row>   .....:    <shape sides="0">circle</shape>   .....:    <degrees>360</degrees>   .....:  </row>   .....:  <row>   .....:    <shape sides="3">triangle</shape>   .....:    <degrees>180</degrees>   .....:  </row>   .....:</data>"""   .....:In [403]:df=pd.read_xml(StringIO(xml),xpath="./row")In [404]:dfOut[404]:      shape  degrees0    square      3601    circle      3602  triangle      180

shows the attributesides onshape element was not parsed asexpected since this attribute resides on the child ofrow elementand notrow element itself. In other words,sides attribute is agrandchild level descendant ofrow element. However, thexpathtargetsrow element which covers only its children and attributes.

Withlxml as parser, you can flatten nested XML documents with an XSLTscript which also can be string/file/URL types. As background,XSLT isa special-purpose language written in a special XML file that can transformoriginal XML documents into other XML, HTML, even text (CSV, JSON, etc.)using an XSLT processor.

For example, consider this somewhat nested structure of Chicago “L” Rideswhere station and rides elements encapsulate data in their own sections.With below XSLT,lxml can transform original nested document into a flatteroutput (as shown below for demonstration) for easier parse intoDataFrame:

In [405]:xml="""<?xml version='1.0' encoding='utf-8'?>   .....: <response>   .....:  <row>   .....:    <station id="40850" name="Library"/>   .....:    <month>2020-09-01T00:00:00</month>   .....:    <rides>   .....:      <avg_weekday_rides>864.2</avg_weekday_rides>   .....:      <avg_saturday_rides>534</avg_saturday_rides>   .....:      <avg_sunday_holiday_rides>417.2</avg_sunday_holiday_rides>   .....:    </rides>   .....:  </row>   .....:  <row>   .....:    <station id="41700" name="Washington/Wabash"/>   .....:    <month>2020-09-01T00:00:00</month>   .....:    <rides>   .....:      <avg_weekday_rides>2707.4</avg_weekday_rides>   .....:      <avg_saturday_rides>1909.8</avg_saturday_rides>   .....:      <avg_sunday_holiday_rides>1438.6</avg_sunday_holiday_rides>   .....:    </rides>   .....:  </row>   .....:  <row>   .....:    <station id="40380" name="Clark/Lake"/>   .....:    <month>2020-09-01T00:00:00</month>   .....:    <rides>   .....:      <avg_weekday_rides>2949.6</avg_weekday_rides>   .....:      <avg_saturday_rides>1657</avg_saturday_rides>   .....:      <avg_sunday_holiday_rides>1453.8</avg_sunday_holiday_rides>   .....:    </rides>   .....:  </row>   .....: </response>"""   .....:In [406]:xsl="""<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">   .....:   <xsl:output method="xml" omit-xml-declaration="no" indent="yes"/>   .....:   <xsl:strip-space elements="*"/>   .....:   <xsl:template match="/response">   .....:      <xsl:copy>   .....:        <xsl:apply-templates select="row"/>   .....:      </xsl:copy>   .....:   </xsl:template>   .....:   <xsl:template match="row">   .....:      <xsl:copy>   .....:        <station_id><xsl:value-of select="station/@id"/></station_id>   .....:        <station_name><xsl:value-of select="station/@name"/></station_name>   .....:        <xsl:copy-of select="month|rides/*"/>   .....:      </xsl:copy>   .....:   </xsl:template>   .....: </xsl:stylesheet>"""   .....:In [407]:output="""<?xml version='1.0' encoding='utf-8'?>   .....: <response>   .....:   <row>   .....:      <station_id>40850</station_id>   .....:      <station_name>Library</station_name>   .....:      <month>2020-09-01T00:00:00</month>   .....:      <avg_weekday_rides>864.2</avg_weekday_rides>   .....:      <avg_saturday_rides>534</avg_saturday_rides>   .....:      <avg_sunday_holiday_rides>417.2</avg_sunday_holiday_rides>   .....:   </row>   .....:   <row>   .....:      <station_id>41700</station_id>   .....:      <station_name>Washington/Wabash</station_name>   .....:      <month>2020-09-01T00:00:00</month>   .....:      <avg_weekday_rides>2707.4</avg_weekday_rides>   .....:      <avg_saturday_rides>1909.8</avg_saturday_rides>   .....:      <avg_sunday_holiday_rides>1438.6</avg_sunday_holiday_rides>   .....:   </row>   .....:   <row>   .....:      <station_id>40380</station_id>   .....:      <station_name>Clark/Lake</station_name>   .....:      <month>2020-09-01T00:00:00</month>   .....:      <avg_weekday_rides>2949.6</avg_weekday_rides>   .....:      <avg_saturday_rides>1657</avg_saturday_rides>   .....:      <avg_sunday_holiday_rides>1453.8</avg_sunday_holiday_rides>   .....:   </row>   .....: </response>"""   .....:In [408]:df=pd.read_xml(StringIO(xml),stylesheet=xsl)In [409]:dfOut[409]:   station_id       station_name  ... avg_saturday_rides  avg_sunday_holiday_rides0       40850            Library  ...              534.0                     417.21       41700  Washington/Wabash  ...             1909.8                    1438.62       40380         Clark/Lake  ...             1657.0                    1453.8[3 rows x 6 columns]

For very large XML files that can range in hundreds of megabytes to gigabytes,pandas.read_xml()supports parsing such sizeable files usinglxml’s iterparse andetree’s iterparsewhich are memory-efficient methods to iterate through an XML tree and extract specific elements and attributes.without holding entire tree in memory.

Added in version 1.5.0.

To use this feature, you must pass a physical XML file path intoread_xml and use theiterparse argument.Files should not be compressed or point to online sources but stored on local disk. Also,iterparse should bea dictionary where the key is the repeating nodes in document (which become the rows) and the value is a list ofany element or attribute that is a descendant (i.e., child, grandchild) of repeating node. Since XPath is notused in this method, descendants do not need to share same relationship with one another. Below shows exampleof reading in Wikipedia’s very large (12 GB+) latest article data dump.

In [1]:df=pd.read_xml(...         "/path/to/downloaded/enwikisource-latest-pages-articles.xml",...         iterparse = {"page": ["title", "ns", "id"]}...     )...     dfOut[2]:                                                     title   ns        id0                                       Gettysburg Address    0     214501                                                Main Page    0     429502                            Declaration by United Nations    0      84353             Constitution of the United States of America    0      84354                     Declaration of Independence (Israel)    0     17858...                                                    ...  ...       ...3578760               Page:Black cat 1897 07 v2 n10.pdf/17  104    2196493578761               Page:Black cat 1897 07 v2 n10.pdf/43  104    2196493578762               Page:Black cat 1897 07 v2 n10.pdf/44  104    2196493578763      The History of Tom Jones, a Foundling/Book IX    0  120842913578764  Page:Shakespeare of Stratford (1926) Yale.djvu/91  104     21450[3578765 rows x 3 columns]

Writing XML#

Added in version 1.3.0.

DataFrame objects have an instance methodto_xml which renders thecontents of theDataFrame as an XML document.

Note

This method does not support special properties of XML including DTD,CData, XSD schemas, processing instructions, comments, and others.Only namespaces at the root level is supported. However,stylesheetallows design changes after initial output.

Let’s look at a few examples.

Write an XML without options:

In [410]:geom_df=pd.DataFrame(   .....:{   .....:"shape":["square","circle","triangle"],   .....:"degrees":[360,360,180],   .....:"sides":[4,np.nan,3],   .....:}   .....:)   .....:In [411]:print(geom_df.to_xml())<?xml version='1.0' encoding='utf-8'?><data>  <row>    <index>0</index>    <shape>square</shape>    <degrees>360</degrees>    <sides>4.0</sides>  </row>  <row>    <index>1</index>    <shape>circle</shape>    <degrees>360</degrees>    <sides/>  </row>  <row>    <index>2</index>    <shape>triangle</shape>    <degrees>180</degrees>    <sides>3.0</sides>  </row></data>

Write an XML with new root and row name:

In [412]:print(geom_df.to_xml(root_name="geometry",row_name="objects"))<?xml version='1.0' encoding='utf-8'?><geometry>  <objects>    <index>0</index>    <shape>square</shape>    <degrees>360</degrees>    <sides>4.0</sides>  </objects>  <objects>    <index>1</index>    <shape>circle</shape>    <degrees>360</degrees>    <sides/>  </objects>  <objects>    <index>2</index>    <shape>triangle</shape>    <degrees>180</degrees>    <sides>3.0</sides>  </objects></geometry>

Write an attribute-centric XML:

In [413]:print(geom_df.to_xml(attr_cols=geom_df.columns.tolist()))<?xml version='1.0' encoding='utf-8'?><data>  <row index="0" shape="square" degrees="360" sides="4.0"/>  <row index="1" shape="circle" degrees="360"/>  <row index="2" shape="triangle" degrees="180" sides="3.0"/></data>

Write a mix of elements and attributes:

In [414]:print(   .....:geom_df.to_xml(   .....:index=False,   .....:attr_cols=['shape'],   .....:elem_cols=['degrees','sides'])   .....:)   .....:<?xml version='1.0' encoding='utf-8'?><data>  <row shape="square">    <degrees>360</degrees>    <sides>4.0</sides>  </row>  <row shape="circle">    <degrees>360</degrees>    <sides/>  </row>  <row shape="triangle">    <degrees>180</degrees>    <sides>3.0</sides>  </row></data>

AnyDataFrames with hierarchical columns will be flattened for XML element nameswith levels delimited by underscores:

In [415]:ext_geom_df=pd.DataFrame(   .....:{   .....:"type":["polygon","other","polygon"],   .....:"shape":["square","circle","triangle"],   .....:"degrees":[360,360,180],   .....:"sides":[4,np.nan,3],   .....:}   .....:)   .....:In [416]:pvt_df=ext_geom_df.pivot_table(index='shape',   .....:columns='type',   .....:values=['degrees','sides'],   .....:aggfunc='sum')   .....:In [417]:pvt_dfOut[417]:         degrees         sidestype       other polygon other polygonshapecircle     360.0     NaN   0.0     NaNsquare       NaN   360.0   NaN     4.0triangle     NaN   180.0   NaN     3.0In [418]:print(pvt_df.to_xml())<?xml version='1.0' encoding='utf-8'?><data>  <row>    <shape>circle</shape>    <degrees_other>360.0</degrees_other>    <degrees_polygon/>    <sides_other>0.0</sides_other>    <sides_polygon/>  </row>  <row>    <shape>square</shape>    <degrees_other/>    <degrees_polygon>360.0</degrees_polygon>    <sides_other/>    <sides_polygon>4.0</sides_polygon>  </row>  <row>    <shape>triangle</shape>    <degrees_other/>    <degrees_polygon>180.0</degrees_polygon>    <sides_other/>    <sides_polygon>3.0</sides_polygon>  </row></data>

Write an XML with default namespace:

In [419]:print(geom_df.to_xml(namespaces={"":"https://example.com"}))<?xml version='1.0' encoding='utf-8'?><data xmlns="https://example.com">  <row>    <index>0</index>    <shape>square</shape>    <degrees>360</degrees>    <sides>4.0</sides>  </row>  <row>    <index>1</index>    <shape>circle</shape>    <degrees>360</degrees>    <sides/>  </row>  <row>    <index>2</index>    <shape>triangle</shape>    <degrees>180</degrees>    <sides>3.0</sides>  </row></data>

Write an XML with namespace prefix:

In [420]:print(   .....:geom_df.to_xml(namespaces={"doc":"https://example.com"},   .....:prefix="doc")   .....:)   .....:<?xml version='1.0' encoding='utf-8'?><doc:data xmlns:doc="https://example.com">  <doc:row>    <doc:index>0</doc:index>    <doc:shape>square</doc:shape>    <doc:degrees>360</doc:degrees>    <doc:sides>4.0</doc:sides>  </doc:row>  <doc:row>    <doc:index>1</doc:index>    <doc:shape>circle</doc:shape>    <doc:degrees>360</doc:degrees>    <doc:sides/>  </doc:row>  <doc:row>    <doc:index>2</doc:index>    <doc:shape>triangle</doc:shape>    <doc:degrees>180</doc:degrees>    <doc:sides>3.0</doc:sides>  </doc:row></doc:data>

Write an XML without declaration or pretty print:

In [421]:print(   .....:geom_df.to_xml(xml_declaration=False,   .....:pretty_print=False)   .....:)   .....:<data><row><index>0</index><shape>square</shape><degrees>360</degrees><sides>4.0</sides></row><row><index>1</index><shape>circle</shape><degrees>360</degrees><sides/></row><row><index>2</index><shape>triangle</shape><degrees>180</degrees><sides>3.0</sides></row></data>

Write an XML and transform with stylesheet:

In [422]:xsl="""<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">   .....:   <xsl:output method="xml" omit-xml-declaration="no" indent="yes"/>   .....:   <xsl:strip-space elements="*"/>   .....:   <xsl:template match="/data">   .....:     <geometry>   .....:       <xsl:apply-templates select="row"/>   .....:     </geometry>   .....:   </xsl:template>   .....:   <xsl:template match="row">   .....:     <object index="{index}">   .....:       <xsl:if test="shape!='circle'">   .....:           <xsl:attribute name="type">polygon</xsl:attribute>   .....:       </xsl:if>   .....:       <xsl:copy-of select="shape"/>   .....:       <property>   .....:           <xsl:copy-of select="degrees|sides"/>   .....:       </property>   .....:     </object>   .....:   </xsl:template>   .....: </xsl:stylesheet>"""   .....:In [423]:print(geom_df.to_xml(stylesheet=xsl))<?xml version="1.0"?><geometry>  <object index="0" type="polygon">    <shape>square</shape>    <property>      <degrees>360</degrees>      <sides>4.0</sides>    </property>  </object>  <object index="1">    <shape>circle</shape>    <property>      <degrees>360</degrees>      <sides/>    </property>  </object>  <object index="2" type="polygon">    <shape>triangle</shape>    <property>      <degrees>180</degrees>      <sides>3.0</sides>    </property>  </object></geometry>

XML Final Notes#

  • All XML documents adhere toW3C specifications. Bothetree andlxmlparsers will fail to parse any markup document that is not well-formed orfollows XML syntax rules. Do be aware HTML is not an XML document unless itfollows XHTML specs. However, other popular markup types including KML, XAML,RSS, MusicML, MathML are compliantXML schemas.

  • For above reason, if your application builds XML prior to pandas operations,use appropriate DOM libraries likeetree andlxml to build the necessarydocument and not by string concatenation or regex adjustments. Always rememberXML is aspecial text file with markup rules.

  • With very large XML files (several hundred MBs to GBs), XPath and XSLTcan become memory-intensive operations. Be sure to have enough availableRAM for reading and writing to large XML files (roughly about 5 times thesize of text).

  • Because XSLT is a programming language, use it with caution since such scriptscan pose a security risk in your environment and can run large or infiniterecursive operations. Always test scripts on small fragments before full run.

  • Theetree parser supports all functionality of bothread_xml andto_xml except for complex XPath and any XSLT. Though limited in features,etree is still a reliable and capable parser and tree builder. Itsperformance may traillxml to a certain degree for larger files butrelatively unnoticeable on small to medium size files.

Excel files#

Theread_excel() method can read Excel 2007+ (.xlsx) filesusing theopenpyxl Python module. Excel 2003 (.xls) filescan be read usingxlrd. Binary Excel (.xlsb)files can be read usingpyxlsb. All formats can be readusingcalamine engine.Theto_excel() instance method is used forsaving aDataFrame to Excel. Generally the semantics aresimilar to working withcsv data.See thecookbook for some advanced strategies.

Note

Whenengine=None, the following logic will be used to determine the engine:

  • Ifpath_or_buffer is an OpenDocument format (.odf, .ods, .odt),thenodf will be used.

  • Otherwise ifpath_or_buffer is an xls format,xlrd will be used.

  • Otherwise ifpath_or_buffer is in xlsb format,pyxlsb will be used.

  • Otherwiseopenpyxl will be used.

Reading Excel files#

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

When using theengine_kwargs parameter, pandas will pass these arguments to theengine. For this, it is important to know which function pandas isusing internally.

  • For the engine openpyxl, pandas is usingopenpyxl.load_workbook() to read in (.xlsx) and (.xlsm) files.

  • For the engine xlrd, pandas is usingxlrd.open_workbook() to read in (.xls) files.

  • For the engine pyxlsb, pandas is usingpyxlsb.open_workbook() to read in (.xlsb) files.

  • For the engine odf, pandas is usingodf.opendocument.load() to read in (.ods) files.

  • For the engine calamine, pandas is usingpython_calamine.load_workbook()to read in (.xlsx), (.xlsm), (.xls), (.xlsb), (.ods) files.

# Returns a DataFramepd.read_excel("path_to_file.xls",sheet_name="Sheet1")

ExcelFile class#

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

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

TheExcelFile class can also be used as a context manager.

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

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

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

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

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

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

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

importxlrdxlrd_book=xlrd.open_workbook("path_to_file.xls",on_demand=True)withpd.ExcelFile(xlrd_book)asxls:df1=pd.read_excel(xls,"Sheet1")df2=pd.read_excel(xls,"Sheet2")

Specifying sheets#

Note

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

Note

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

  • The argumentssheet_name allows specifying the sheet or sheets to read.

  • The default value forsheet_name is 0, indicating to read the first sheet

  • Pass a string to refer to the name of a particular sheet in the workbook.

  • Pass an integer to refer to the index of a sheet. Indices follow Pythonconvention, beginning at 0.

  • Pass a list of either strings or integers, to return a dictionary of specified sheets.

  • Pass aNone to return a dictionary of all available sheets.

# Returns a DataFramepd.read_excel("path_to_file.xls","Sheet1",index_col=None,na_values=["NA"])

Using the sheet index:

# Returns a DataFramepd.read_excel("path_to_file.xls",0,index_col=None,na_values=["NA"])

Using all default values:

# Returns a DataFramepd.read_excel("path_to_file.xls")

Using None to get all sheets:

# Returns a dictionary of DataFramespd.read_excel("path_to_file.xls",sheet_name=None)

Using a list to get multiple sheets:

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

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

Reading aMultiIndex#

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

For example, to read in aMultiIndex index without names:

In [424]:df=pd.DataFrame(   .....:{"a":[1,2,3,4],"b":[5,6,7,8]},   .....:index=pd.MultiIndex.from_product([["a","b"],["c","d"]]),   .....:)   .....:In [425]:df.to_excel("path_to_file.xlsx")In [426]:df=pd.read_excel("path_to_file.xlsx",index_col=[0,1])In [427]:dfOut[427]:     a  ba c  1  5  d  2  6b c  3  7  d  4  8

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

In [428]:df.index=df.index.set_names(["lvl1","lvl2"])In [429]:df.to_excel("path_to_file.xlsx")In [430]:df=pd.read_excel("path_to_file.xlsx",index_col=[0,1])In [431]:dfOut[431]:           a  blvl1 lvl2a    c     1  5     d     2  6b    c     3  7     d     4  8

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

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

Missing values in columns specified inindex_col will be forward filled toallow roundtripping withto_excel formerged_cells=True. To avoid forwardfilling the missing values useset_index after reading the data instead ofindex_col.

Parsing specific columns#

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

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

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

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

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

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

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

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

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

Ifusecols is callable, the callable function will be evaluated againstthe column names, returning names where the callable function evaluates toTrue.

pd.read_excel("path_to_file.xls","Sheet1",usecols=lambdax:x.isalpha())

Parsing dates#

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

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

Cell converters#

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

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

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

defcfun(x):returnint(x)ifxelse-1pd.read_excel("path_to_file.xls","Sheet1",converters={"MyInts":cfun})

Dtype specifications#

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

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

Writing Excel files#

Writing Excel files to disk#

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

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

Files with a.xlsx extension will be written usingxlsxwriter (if available) oropenpyxl.

TheDataFrame will be written in a way that tries to mimic the REPL output.Theindex_label will be placed in the secondrow instead of the first. You can place it in the first row by setting themerge_cells option into_excel() toFalse:

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

In order to write separateDataFrames to separate sheets in a single Excel file,one can pass anExcelWriter.

withpd.ExcelWriter("path_to_file.xlsx")aswriter:df1.to_excel(writer,sheet_name="Sheet1")df2.to_excel(writer,sheet_name="Sheet2")

When using theengine_kwargs parameter, pandas will pass these arguments to theengine. For this, it is important to know which function pandas is using internally.

  • For the engine openpyxl, pandas is usingopenpyxl.Workbook() to create a new sheet andopenpyxl.load_workbook() to append data to an existing sheet. The openpyxl engine writes to (.xlsx) and (.xlsm) files.

  • For the engine xlsxwriter, pandas is usingxlsxwriter.Workbook() to write to (.xlsx) files.

  • For the engine odf, pandas is usingodf.opendocument.OpenDocumentSpreadsheet() to write to (.ods) files.

Writing Excel files to memory#

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

fromioimportBytesIObio=BytesIO()# By setting the 'engine' in the ExcelWriter constructor.writer=pd.ExcelWriter(bio,engine="xlsxwriter")df.to_excel(writer,sheet_name="Sheet1")# Save the workbookwriter.save()# Seek to the beginning and read to copy the workbook to a variable in memorybio.seek(0)workbook=bio.read()

Note

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

Excel writer engines#

pandas chooses an Excel writer via two methods:

  1. theengine keyword argument

  2. the filename extension (via the default specified in config options)

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

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

  • openpyxl: version 2.4 or higher is required

  • xlsxwriter

# By setting the 'engine' in the DataFrame 'to_excel()' methods.df.to_excel("path_to_file.xlsx",sheet_name="Sheet1",engine="xlsxwriter")# By setting the 'engine' in the ExcelWriter constructor.writer=pd.ExcelWriter("path_to_file.xlsx",engine="xlsxwriter")# Or via pandas configuration.frompandasimportoptions# noqa: E402options.io.excel.xlsx.writer="xlsxwriter"df.to_excel("path_to_file.xlsx",sheet_name="Sheet1")

Style and formatting#

The look and feel of Excel worksheets created from pandas can be modified using the following parameters on theDataFrame’sto_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 theXlsxwriter engine provides many options for controlling theformat of an Excel worksheet created with theto_excel method. Excellent examples can be found in theXlsxwriter documentation here:https://xlsxwriter.readthedocs.io/working_with_pandas.html

OpenDocument Spreadsheets#

The io methods forExcel files also support reading and writing OpenDocument spreadsheetsusing theodfpy module. The semantics and features for reading and writingOpenDocument spreadsheets match what can be done forExcel files usingengine='odf'. The optional dependency ‘odfpy’ needs to be installed.

Theread_excel() method can read OpenDocument spreadsheets

# Returns a DataFramepd.read_excel("path_to_file.ods",engine="odf")

Similarly, theto_excel() method can write OpenDocument spreadsheets

# Writes DataFrame to a .ods filedf.to_excel("path_to_file.ods",engine="odf")

Binary Excel (.xlsb) files#

Theread_excel() method can also read binary Excel filesusing thepyxlsb module. The semantics and features for readingbinary Excel files mostly match what can be done forExcel files usingengine='pyxlsb'.pyxlsb does not recognize datetime typesin files and will return floats instead (you can usecalamineif you need recognize datetime types).

# Returns a DataFramepd.read_excel("path_to_file.xlsb",engine="pyxlsb")

Note

Currently pandas only supportsreading binary Excel files. Writingis not implemented.

Calamine (Excel and ODS files)#

Theread_excel() method can read Excel file (.xlsx,.xlsm,.xls,.xlsb)and OpenDocument spreadsheets (.ods) using thepython-calamine module.This module is a binding for Rust librarycalamineand is faster than other engines in most cases. The optional dependency ‘python-calamine’ needs to be installed.

# Returns a DataFramepd.read_excel("path_to_file.xlsb",engine="calamine")

Clipboard#

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

  A B Cx 1 4 py 2 5 qz 3 6 r

And then import the data directly to aDataFrame by calling:

>>>clipdf=pd.read_clipboard()>>>clipdf  A B Cx 1 4 py 2 5 qz 3 6 r

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

>>>df=pd.DataFrame(...{"A":[1,2,3],"B":[4,5,6],"C":["p","q","r"]},index=["x","y","z"]...)>>>df  A B Cx 1 4 py 2 5 qz 3 6 r>>>df.to_clipboard()>>>pd.read_clipboard()  A B Cx 1 4 py 2 5 qz 3 6 r

We can see that we got the same content back, which we had earlier written to the clipboard.

Note

You may need to install xclip or xsel (with PyQt5, PyQt4 or qtpy) on Linux to use these methods.

Pickling#

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

In [436]:dfOut[436]:c1         ac2         b  dlvl1 lvl2a    c     1  5     d     2  6b    c     3  7     d     4  8In [437]:df.to_pickle("foo.pkl")

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

In [438]:pd.read_pickle("foo.pkl")Out[438]:c1         ac2         b  dlvl1 lvl2a    c     1  5     d     2  6b    c     3  7     d     4  8

Warning

Loading pickled data received from untrusted sources can be unsafe.

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

Warning

read_pickle() is only guaranteed backwards compatible back to a few minor release.

Compressed pickle files#

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

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

The compression parameter can also be adict in order to pass options to thecompression protocol. It must have a'method' key set to the nameof the compression protocol, which must be one of{'zip','gzip','bz2','xz','zstd'}. All other key-value pairs are passed tothe underlying compression library.

In [439]:df=pd.DataFrame(   .....:{   .....:"A":np.random.randn(1000),   .....:"B":"foo",   .....:"C":pd.date_range("20130101",periods=1000,freq="s"),   .....:}   .....:)   .....:In [440]:dfOut[440]:            A    B                   C0   -0.317441  foo 2013-01-01 00:00:001   -1.236269  foo 2013-01-01 00:00:012    0.896171  foo 2013-01-01 00:00:023   -0.487602  foo 2013-01-01 00:00:034   -0.082240  foo 2013-01-01 00:00:04..        ...  ...                 ...995 -0.171092  foo 2013-01-01 00:16:35996  1.786173  foo 2013-01-01 00:16:36997 -0.575189  foo 2013-01-01 00:16:37998  0.820750  foo 2013-01-01 00:16:38999 -1.256530  foo 2013-01-01 00:16:39[1000 rows x 3 columns]

Using an explicit compression type:

In [441]:df.to_pickle("data.pkl.compress",compression="gzip")In [442]:rt=pd.read_pickle("data.pkl.compress",compression="gzip")In [443]:rtOut[443]:            A    B                   C0   -0.317441  foo 2013-01-01 00:00:001   -1.236269  foo 2013-01-01 00:00:012    0.896171  foo 2013-01-01 00:00:023   -0.487602  foo 2013-01-01 00:00:034   -0.082240  foo 2013-01-01 00:00:04..        ...  ...                 ...995 -0.171092  foo 2013-01-01 00:16:35996  1.786173  foo 2013-01-01 00:16:36997 -0.575189  foo 2013-01-01 00:16:37998  0.820750  foo 2013-01-01 00:16:38999 -1.256530  foo 2013-01-01 00:16:39[1000 rows x 3 columns]

Inferring compression type from the extension:

In [444]:df.to_pickle("data.pkl.xz",compression="infer")In [445]:rt=pd.read_pickle("data.pkl.xz",compression="infer")In [446]:rtOut[446]:            A    B                   C0   -0.317441  foo 2013-01-01 00:00:001   -1.236269  foo 2013-01-01 00:00:012    0.896171  foo 2013-01-01 00:00:023   -0.487602  foo 2013-01-01 00:00:034   -0.082240  foo 2013-01-01 00:00:04..        ...  ...                 ...995 -0.171092  foo 2013-01-01 00:16:35996  1.786173  foo 2013-01-01 00:16:36997 -0.575189  foo 2013-01-01 00:16:37998  0.820750  foo 2013-01-01 00:16:38999 -1.256530  foo 2013-01-01 00:16:39[1000 rows x 3 columns]

The default is to ‘infer’:

In [447]:df.to_pickle("data.pkl.gz")In [448]:rt=pd.read_pickle("data.pkl.gz")In [449]:rtOut[449]:            A    B                   C0   -0.317441  foo 2013-01-01 00:00:001   -1.236269  foo 2013-01-01 00:00:012    0.896171  foo 2013-01-01 00:00:023   -0.487602  foo 2013-01-01 00:00:034   -0.082240  foo 2013-01-01 00:00:04..        ...  ...                 ...995 -0.171092  foo 2013-01-01 00:16:35996  1.786173  foo 2013-01-01 00:16:36997 -0.575189  foo 2013-01-01 00:16:37998  0.820750  foo 2013-01-01 00:16:38999 -1.256530  foo 2013-01-01 00:16:39[1000 rows x 3 columns]In [450]:df["A"].to_pickle("s1.pkl.bz2")In [451]:rt=pd.read_pickle("s1.pkl.bz2")In [452]:rtOut[452]:0     -0.3174411     -1.2362692      0.8961713     -0.4876024     -0.082240         ...995   -0.171092996    1.786173997   -0.575189998    0.820750999   -1.256530Name: A, Length: 1000, dtype: float64

Passing options to the compression protocol in order to speed up compression:

In [453]:df.to_pickle("data.pkl.gz",compression={"method":"gzip","compresslevel":1})

msgpack#

pandas support formsgpack has been removed in version 1.0.0. It isrecommended to usepickle instead.

Alternatively, you can also the Arrow IPC serialization format for on-the-wiretransmission of pandas objects. For documentation on pyarrow, seehere.

HDF5 (PyTables)#

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

Warning

pandas uses PyTables for reading and writing HDF5 files, which allowsserializing object-dtype data with pickle. Loading pickled data received fromuntrusted sources can be unsafe.

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

In [454]:store=pd.HDFStore("store.h5")In [455]:print(store)<class 'pandas.io.pytables.HDFStore'>File path: store.h5

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

In [456]:index=pd.date_range("1/1/2000",periods=8)In [457]:s=pd.Series(np.random.randn(5),index=["a","b","c","d","e"])In [458]:df=pd.DataFrame(np.random.randn(8,3),index=index,columns=["A","B","C"])# store.put('s', s) is an equivalent methodIn [459]:store["s"]=sIn [460]:store["df"]=dfIn [461]:storeOut[461]:<class 'pandas.io.pytables.HDFStore'>File path: store.h5

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

# store.get('df') is an equivalent methodIn [462]:store["df"]Out[462]:                   A         B         C2000-01-01  0.858644 -0.851236  1.0580062000-01-02 -0.080372 -1.268121  1.5619672000-01-03  0.816983  1.965656 -1.1694082000-01-04  0.712795 -0.062433  0.7367552000-01-05 -0.298721 -1.988045  1.4753082000-01-06  1.103675  1.382242 -0.6507622000-01-07 -0.729161 -0.142928 -1.0630382000-01-08 -1.005977  0.465222 -0.094517# dotted (attribute) access provides get as wellIn [463]:store.dfOut[463]:                   A         B         C2000-01-01  0.858644 -0.851236  1.0580062000-01-02 -0.080372 -1.268121  1.5619672000-01-03  0.816983  1.965656 -1.1694082000-01-04  0.712795 -0.062433  0.7367552000-01-05 -0.298721 -1.988045  1.4753082000-01-06  1.103675  1.382242 -0.6507622000-01-07 -0.729161 -0.142928 -1.0630382000-01-08 -1.005977  0.465222 -0.094517

Deletion of the object specified by the key:

# store.remove('df') is an equivalent methodIn [464]:delstore["df"]In [465]:storeOut[465]:<class 'pandas.io.pytables.HDFStore'>File path: store.h5

Closing a Store and using a context manager:

In [466]:store.close()In [467]:storeOut[467]:<class 'pandas.io.pytables.HDFStore'>File path: store.h5In [468]:store.is_openOut[468]:False# Working with, and automatically closing the store using a context managerIn [469]:withpd.HDFStore("store.h5")asstore:   .....:store.keys()   .....:

Read/write API#

HDFStore supports a top-level API usingread_hdf for reading andto_hdf for writing,similar to howread_csv andto_csv work.

In [470]:df_tl=pd.DataFrame({"A":list(range(5)),"B":list(range(5))})In [471]:df_tl.to_hdf("store_tl.h5",key="table",append=True)In [472]:pd.read_hdf("store_tl.h5","table",where=["index>2"])Out[472]:   A  B3  3  34  4  4

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

In [473]:df_with_missing=pd.DataFrame(   .....:{   .....:"col1":[0,np.nan,2],   .....:"col2":[1,np.nan,np.nan],   .....:}   .....:)   .....:In [474]:df_with_missingOut[474]:   col1  col20   0.0   1.01   NaN   NaN2   2.0   NaNIn [475]:df_with_missing.to_hdf("file.h5",key="df_with_missing",format="table",mode="w")In [476]:pd.read_hdf("file.h5","df_with_missing")Out[476]:   col1  col20   0.0   1.01   NaN   NaN2   2.0   NaNIn [477]:df_with_missing.to_hdf(   .....:"file.h5",key="df_with_missing",format="table",mode="w",dropna=True   .....:)   .....:In [478]:pd.read_hdf("file.h5","df_with_missing")Out[478]:   col1  col20   0.0   1.02   2.0   NaN

Fixed format#

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

Warning

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

In [479]:pd.DataFrame(np.random.randn(10,2)).to_hdf("test_fixed.h5",key="df")In [480]:pd.read_hdf("test_fixed.h5","df",where="index>5")---------------------------------------------------------------------------TypeErrorTraceback (most recent call last)CellIn[480],line1---->1pd.read_hdf("test_fixed.h5","df",where="index>5")File ~/work/pandas/pandas/pandas/io/pytables.py:452, inread_hdf(path_or_buf, key, mode, errors, where, start, stop, columns, iterator, chunksize, **kwargs)447raiseValueError(448"key must be provided when HDF5 "449"file contains multiple datasets."450)451key=candidate_only_group._v_pathname-->452returnstore.select(453key,454where=where,455start=start,456stop=stop,457columns=columns,458iterator=iterator,459chunksize=chunksize,460auto_close=auto_close,461)462except(ValueError,TypeError,LookupError):463ifnotisinstance(path_or_buf,HDFStore):464# if there is an error, close the store if we opened it.File ~/work/pandas/pandas/pandas/io/pytables.py:906, inHDFStore.select(self, key, where, start, stop, columns, iterator, chunksize, auto_close)892# create the iterator893it=TableIterator(894self,895s,(...)903auto_close=auto_close,904)-->906returnit.get_result()File ~/work/pandas/pandas/pandas/io/pytables.py:2029, inTableIterator.get_result(self, coordinates)2026where=self.where2028# directly return the result->2029results=self.func(self.start,self.stop,where)2030self.close()2031returnresultsFile ~/work/pandas/pandas/pandas/io/pytables.py:890, inHDFStore.select.<locals>.func(_start, _stop, _where)889deffunc(_start,_stop,_where):-->890returns.read(start=_start,stop=_stop,where=_where,columns=columns)File ~/work/pandas/pandas/pandas/io/pytables.py:3278, inBlockManagerFixed.read(self, where, columns, start, stop)3270defread(3271self,3272where=None,(...)3276)->DataFrame:3277# start, stop applied to rows, so 0th axis only->3278self.validate_read(columns,where)3279select_axis=self.obj_type()._get_block_manager_axis(0)3281axes=[]File ~/work/pandas/pandas/pandas/io/pytables.py:2922, inGenericFixed.validate_read(self, columns, where)2917raiseTypeError(2918"cannot pass a column specification when reading "2919"a Fixed format store. this store must be selected in its entirety"2920)2921ifwhereisnotNone:->2922raiseTypeError(2923"cannot pass a where specification when reading "2924"from a Fixed format store. this store must be selected in its entirety"2925)TypeError: cannot pass a where specification when reading from a Fixed format store. this store must be selected in its entirety

Table format#

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

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

In [481]:store=pd.HDFStore("store.h5")In [482]:df1=df[0:4]In [483]:df2=df[4:]# append data (creates a table automatically)In [484]:store.append("df",df1)In [485]:store.append("df",df2)In [486]:storeOut[486]:<class 'pandas.io.pytables.HDFStore'>File path: store.h5# select the entire objectIn [487]:store.select("df")Out[487]:                   A         B         C2000-01-01  0.858644 -0.851236  1.0580062000-01-02 -0.080372 -1.268121  1.5619672000-01-03  0.816983  1.965656 -1.1694082000-01-04  0.712795 -0.062433  0.7367552000-01-05 -0.298721 -1.988045  1.4753082000-01-06  1.103675  1.382242 -0.6507622000-01-07 -0.729161 -0.142928 -1.0630382000-01-08 -1.005977  0.465222 -0.094517# the type of stored dataIn [488]:store.root.df._v_attrs.pandas_typeOut[488]:'frame_table'

Note

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

Hierarchical keys#

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

In [489]:store.put("foo/bar/bah",df)In [490]:store.append("food/orange",df)In [491]:store.append("food/apple",df)In [492]:storeOut[492]:<class 'pandas.io.pytables.HDFStore'>File path: store.h5# a list of keys are returnedIn [493]:store.keys()Out[493]:['/df', '/food/apple', '/food/orange', '/foo/bar/bah']# remove all nodes under this levelIn [494]:store.remove("food")In [495]:storeOut[495]:<class 'pandas.io.pytables.HDFStore'>File path: store.h5

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

In [496]:for(path,subgroups,subkeys)instore.walk():   .....:forsubgroupinsubgroups:   .....:print("GROUP:{}/{}".format(path,subgroup))   .....:forsubkeyinsubkeys:   .....:key="/".join([path,subkey])   .....:print("KEY:{}".format(key))   .....:print(store.get(key))   .....:GROUP: /fooKEY: /df                   A         B         C2000-01-01  0.858644 -0.851236  1.0580062000-01-02 -0.080372 -1.268121  1.5619672000-01-03  0.816983  1.965656 -1.1694082000-01-04  0.712795 -0.062433  0.7367552000-01-05 -0.298721 -1.988045  1.4753082000-01-06  1.103675  1.382242 -0.6507622000-01-07 -0.729161 -0.142928 -1.0630382000-01-08 -1.005977  0.465222 -0.094517GROUP: /foo/barKEY: /foo/bar/bah                   A         B         C2000-01-01  0.858644 -0.851236  1.0580062000-01-02 -0.080372 -1.268121  1.5619672000-01-03  0.816983  1.965656 -1.1694082000-01-04  0.712795 -0.062433  0.7367552000-01-05 -0.298721 -1.988045  1.4753082000-01-06  1.103675  1.382242 -0.6507622000-01-07 -0.729161 -0.142928 -1.0630382000-01-08 -1.005977  0.465222 -0.094517

Warning

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

In [497]:store.foo.bar.bah---------------------------------------------------------------------------TypeErrorTraceback (most recent call last)CellIn[497],line1---->1store.foo.bar.bahFile ~/work/pandas/pandas/pandas/io/pytables.py:613, inHDFStore.__getattr__(self, name)611"""allow attribute access to get stores"""612try:-->613returnself.get(name)614except(KeyError,ClosedFileError):615passFile ~/work/pandas/pandas/pandas/io/pytables.py:813, inHDFStore.get(self, key)811ifgroupisNone:812raiseKeyError(f"No object named{key} in the file")-->813returnself._read_group(group)File ~/work/pandas/pandas/pandas/io/pytables.py:1878, inHDFStore._read_group(self, group)1877def_read_group(self,group:Node):->1878s=self._create_storer(group)1879s.infer_axes()1880returns.read()File ~/work/pandas/pandas/pandas/io/pytables.py:1752, inHDFStore._create_storer(self, group, format, value, encoding, errors)1750tt="generic_table"1751else:->1752raiseTypeError(1753"cannot create a storer if the object is not existing "1754"nor a value are passed"1755)1756else:1757ifisinstance(value,Series):TypeError: cannot create a storer if the object is not existing nor a value are passed
# you can directly access the actual PyTables node but using the root nodeIn [498]:store.root.foo.bar.bahOut[498]:/foo/bar/bah (Group) ''  children := ['axis0' (Array), 'axis1' (Array), 'block0_items' (Array), 'block0_values' (Array)]

Instead, use explicit string based keys:

In [499]:store["foo/bar/bah"]Out[499]:                   A         B         C2000-01-01  0.858644 -0.851236  1.0580062000-01-02 -0.080372 -1.268121  1.5619672000-01-03  0.816983  1.965656 -1.1694082000-01-04  0.712795 -0.062433  0.7367552000-01-05 -0.298721 -1.988045  1.4753082000-01-06  1.103675  1.382242 -0.6507622000-01-07 -0.729161 -0.142928 -1.0630382000-01-08 -1.005977  0.465222 -0.094517

Storing types#

Storing mixed types in a table#

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

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

In [500]:df_mixed=pd.DataFrame(   .....:{   .....:"A":np.random.randn(8),   .....:"B":np.random.randn(8),   .....:"C":np.array(np.random.randn(8),dtype="float32"),   .....:"string":"string",   .....:"int":1,   .....:"bool":True,   .....:"datetime64":pd.Timestamp("20010102"),   .....:},   .....:index=list(range(8)),   .....:)   .....:In [501]:df_mixed.loc[df_mixed.index[3:5],["A","B","string","datetime64"]]=np.nanIn [502]:store.append("df_mixed",df_mixed,min_itemsize={"values":50})In [503]:df_mixed1=store.select("df_mixed")In [504]:df_mixed1Out[504]:          A         B         C  ... int  bool                    datetime640  0.013747 -1.166078 -1.292080  ...   1  True 1970-01-01 00:00:00.9783936001 -0.712009  0.247572  1.526911  ...   1  True 1970-01-01 00:00:00.9783936002 -0.645096  1.687406  0.288504  ...   1  True 1970-01-01 00:00:00.9783936003       NaN       NaN  0.097771  ...   1  True                           NaT4       NaN       NaN  1.536408  ...   1  True                           NaT5 -0.023202  0.043702  0.926790  ...   1  True 1970-01-01 00:00:00.9783936006  2.359782  0.088224 -0.676448  ...   1  True 1970-01-01 00:00:00.9783936007 -0.143428 -0.813360 -0.179724  ...   1  True 1970-01-01 00:00:00.978393600[8 rows x 7 columns]In [505]:df_mixed1.dtypes.value_counts()Out[505]:float64           2float32           1object            1int64             1bool              1datetime64[ns]    1Name: count, dtype: int64# we have provided a minimum string column sizeIn [506]:store.root.df_mixed.tableOut[506]:/df_mixed/table (Table(8,)) ''  description := {  "index": Int64Col(shape=(), dflt=0, pos=0),  "values_block_0": Float64Col(shape=(2,), dflt=0.0, pos=1),  "values_block_1": Float32Col(shape=(1,), dflt=0.0, pos=2),  "values_block_2": StringCol(itemsize=50, shape=(1,), dflt=b'', pos=3),  "values_block_3": Int64Col(shape=(1,), dflt=0, pos=4),  "values_block_4": BoolCol(shape=(1,), dflt=False, pos=5),  "values_block_5": Int64Col(shape=(1,), dflt=0, pos=6)}  byteorder := 'little'  chunkshape := (689,)  autoindex := True  colindexes := {    "index": Index(6, mediumshuffle, zlib(1)).is_csi=False}

Storing MultiIndex DataFrames#

Storing MultiIndexDataFrames as tables is very similar tostoring/selecting from homogeneous indexDataFrames.

In [507]:index=pd.MultiIndex(   .....:levels=[["foo","bar","baz","qux"],["one","two","three"]],   .....:codes=[[0,0,0,1,1,2,2,3,3,3],[0,1,2,0,1,1,2,0,1,2]],   .....:names=["foo","bar"],   .....:)   .....:In [508]:df_mi=pd.DataFrame(np.random.randn(10,3),index=index,columns=["A","B","C"])In [509]:df_miOut[509]:                  A         B         Cfoo barfoo one   -1.303456 -0.642994 -0.649456    two    1.012694  0.414147  1.950460    three  1.094544 -0.802899 -0.583343bar one    0.410395  0.618321  0.560398    two    1.434027 -0.033270  0.343197baz two   -1.646063 -0.695847 -0.429156    three -0.244688 -1.428229 -0.138691qux one    1.866184 -1.446617  0.036660    two   -1.660522  0.929553 -1.298649    three  3.565769  0.682402  1.041927In [510]:store.append("df_mi",df_mi)In [511]:store.select("df_mi")Out[511]:                  A         B         Cfoo barfoo one   -1.303456 -0.642994 -0.649456    two    1.012694  0.414147  1.950460    three  1.094544 -0.802899 -0.583343bar one    0.410395  0.618321  0.560398    two    1.434027 -0.033270  0.343197baz two   -1.646063 -0.695847 -0.429156    three -0.244688 -1.428229 -0.138691qux one    1.866184 -1.446617  0.036660    two   -1.660522  0.929553 -1.298649    three  3.565769  0.682402  1.041927# the levels are automatically included as data columnsIn [512]:store.select("df_mi","foo=bar")Out[512]:                A         B         Cfoo barbar one  0.410395  0.618321  0.560398    two  1.434027 -0.033270  0.343197

Note

Theindex keyword is reserved and cannot be use as a level name.

Querying#

Querying a table#

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

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

  • index andcolumns are supported indexers ofDataFrames.

  • ifdata_columns are specified, these can be used as additional indexers.

  • level name in a MultiIndex, with default namelevel_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 limitedcircumstances

  • If a list/tuple of expressions is passed they will be combined via&

The following are valid expressions:

  • 'index>=date'

  • "columns=['A','D']"

  • "columnsin['A','D']"

  • 'columns=A'

  • 'columns==A'

  • "~(columns=['A','B'])"

  • 'index>df.index[3]&string="bar"'

  • '(index>df.index[3]&index<=df.index[6])|string="bar"'

  • "ts>=Timestamp('2012-02-01')"

  • "major_axis>=20130101"

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

columns,major_axis,ts

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

  • functions that will be evaluated, e.g.Timestamp('2012-02-01')

  • strings, e.g."bar"

  • date-like, e.g.20130101, or"20130101"

  • lists, e.g."['A','B']"

  • variables that are defined in the local names space, e.g.date

Note

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

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

instead of this

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

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

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

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

which will quotestring.

Here are some examples:

In [513]:dfq=pd.DataFrame(   .....:np.random.randn(10,4),   .....:columns=list("ABCD"),   .....:index=pd.date_range("20130101",periods=10),   .....:)   .....:In [514]:store.append("dfq",dfq,format="table",data_columns=True)

Use boolean expressions, with in-line function evaluation.

In [515]:store.select("dfq","index>pd.Timestamp('20130104') & columns=['A', 'B']")Out[515]:                   A         B2013-01-05 -0.830545 -0.4570712013-01-06  0.431186  1.0494212013-01-07  0.617509 -0.8112302013-01-08  0.947422 -0.6712332013-01-09 -0.183798 -1.2112302013-01-10  0.361428  0.887304

Use inline column reference.

In [516]:store.select("dfq",where="A>0 or C>0")Out[516]:                   A         B         C         D2013-01-02  0.658179  0.362814 -0.917897  0.0101652013-01-03  0.905122  1.848731 -1.184241  0.9320532013-01-05 -0.830545 -0.457071  1.565581  1.1480322013-01-06  0.431186  1.049421  0.383309  0.5950132013-01-07  0.617509 -0.811230 -2.088563 -1.3935002013-01-08  0.947422 -0.671233 -0.847097 -1.1877852013-01-10  0.361428  0.887304  0.266457 -0.399641

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

In [517]:store.select("df","columns=['A', 'B']")Out[517]:                   A         B2000-01-01  0.858644 -0.8512362000-01-02 -0.080372 -1.2681212000-01-03  0.816983  1.9656562000-01-04  0.712795 -0.0624332000-01-05 -0.298721 -1.9880452000-01-06  1.103675  1.3822422000-01-07 -0.729161 -0.1429282000-01-08 -1.005977  0.465222

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

Note

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

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

Query timedelta64[ns]#

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

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

Query MultiIndex#

Selecting from aMultiIndex can be achieved by using the name of the level.

In [524]:df_mi.index.namesOut[524]:FrozenList(['foo', 'bar'])In [525]:store.select("df_mi","foo=baz and bar=two")Out[525]:                A         B         Cfoo barbaz two -1.646063 -0.695847 -0.429156

If theMultiIndex levels names areNone, the levels are automatically made available viathelevel_n keyword withn the level of theMultiIndex you want to select from.

In [526]:index=pd.MultiIndex(   .....:levels=[["foo","bar","baz","qux"],["one","two","three"]],   .....:codes=[[0,0,0,1,1,2,2,3,3,3],[0,1,2,0,1,1,2,0,1,2]],   .....:)   .....:In [527]:df_mi_2=pd.DataFrame(np.random.randn(10,3),index=index,columns=["A","B","C"])In [528]:df_mi_2Out[528]:                  A         B         Cfoo one   -0.219582  1.186860 -1.437189    two    0.053768  1.872644 -1.469813    three -0.564201  0.876341  0.407749bar one   -0.232583  0.179812  0.922152    two   -1.820952 -0.641360  2.133239baz two   -0.941248 -0.136307 -1.271305    three -0.099774 -0.061438 -0.845172qux one    0.465793  0.756995 -0.541690    two   -0.802241  0.877657 -2.553831    three  0.094899 -2.319519  0.293601In [529]:store.append("df_mi_2",df_mi_2)# the levels are automatically included as data columns with keyword level_nIn [530]:store.select("df_mi_2","level_0=foo and level_1=two")Out[530]:                A         B         Cfoo two  0.053768  1.872644 -1.469813

Indexing#

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

Note

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

# we have automagically already created an index (in the first section)In [531]:i=store.root.df.table.cols.index.indexIn [532]:i.optlevel,i.kindOut[532]:(6, 'medium')# change an index by passing new parametersIn [533]:store.create_table_index("df",optlevel=9,kind="full")In [534]:i=store.root.df.table.cols.index.indexIn [535]:i.optlevel,i.kindOut[535]:(9, 'full')

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

In [536]:df_1=pd.DataFrame(np.random.randn(10,2),columns=list("AB"))In [537]:df_2=pd.DataFrame(np.random.randn(10,2),columns=list("AB"))In [538]:st=pd.HDFStore("appends.h5",mode="w")In [539]:st.append("df",df_1,data_columns=["B"],index=False)In [540]:st.append("df",df_2,data_columns=["B"],index=False)In [541]:st.get_storer("df").tableOut[541]:/df/table (Table(20,)) ''  description := {  "index": Int64Col(shape=(), dflt=0, pos=0),  "values_block_0": Float64Col(shape=(1,), dflt=0.0, pos=1),  "B": Float64Col(shape=(), dflt=0.0, pos=2)}  byteorder := 'little'  chunkshape := (2730,)

Then create the index when finished appending.

In [542]:st.create_table_index("df",columns=["B"],optlevel=9,kind="full")In [543]:st.get_storer("df").tableOut[543]:/df/table (Table(20,)) ''  description := {  "index": Int64Col(shape=(), dflt=0, pos=0),  "values_block_0": Float64Col(shape=(1,), dflt=0.0, pos=1),  "B": Float64Col(shape=(), dflt=0.0, pos=2)}  byteorder := 'little'  chunkshape := (2730,)  autoindex := True  colindexes := {    "B": Index(9, fullshuffle, zlib(1)).is_csi=True}In [544]:st.close()

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

Query via data columns#

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

In [545]:df_dc=df.copy()In [546]:df_dc["string"]="foo"In [547]:df_dc.loc[df_dc.index[4:6],"string"]=np.nanIn [548]:df_dc.loc[df_dc.index[7:9],"string"]="bar"In [549]:df_dc["string2"]="cool"In [550]:df_dc.loc[df_dc.index[1:3],["B","C"]]=1.0In [551]:df_dcOut[551]:                   A         B         C string string22000-01-01  0.858644 -0.851236  1.058006    foo    cool2000-01-02 -0.080372  1.000000  1.000000    foo    cool2000-01-03  0.816983  1.000000  1.000000    foo    cool2000-01-04  0.712795 -0.062433  0.736755    foo    cool2000-01-05 -0.298721 -1.988045  1.475308    NaN    cool2000-01-06  1.103675  1.382242 -0.650762    NaN    cool2000-01-07 -0.729161 -0.142928 -1.063038    foo    cool2000-01-08 -1.005977  0.465222 -0.094517    bar    cool# on-disk operationsIn [552]:store.append("df_dc",df_dc,data_columns=["B","C","string","string2"])In [553]:store.select("df_dc",where="B > 0")Out[553]:                   A         B         C string string22000-01-02 -0.080372  1.000000  1.000000    foo    cool2000-01-03  0.816983  1.000000  1.000000    foo    cool2000-01-06  1.103675  1.382242 -0.650762    NaN    cool2000-01-08 -1.005977  0.465222 -0.094517    bar    cool# getting creativeIn [554]:store.select("df_dc","B > 0 & C > 0 & string == foo")Out[554]:                   A    B    C string string22000-01-02 -0.080372  1.0  1.0    foo    cool2000-01-03  0.816983  1.0  1.0    foo    cool# this is in-memory version of this type of selectionIn [555]:df_dc[(df_dc.B>0)&(df_dc.C>0)&(df_dc.string=="foo")]Out[555]:                   A    B    C string string22000-01-02 -0.080372  1.0  1.0    foo    cool2000-01-03  0.816983  1.0  1.0    foo    cool# we have automagically created this index and the B/C/string/string2# columns are stored separately as ``PyTables`` columnsIn [556]:store.root.df_dc.tableOut[556]:/df_dc/table (Table(8,)) ''  description := {  "index": Int64Col(shape=(), dflt=0, pos=0),  "values_block_0": Float64Col(shape=(1,), dflt=0.0, pos=1),  "B": Float64Col(shape=(), dflt=0.0, pos=2),  "C": Float64Col(shape=(), dflt=0.0, pos=3),  "string": StringCol(itemsize=3, shape=(), dflt=b'', pos=4),  "string2": StringCol(itemsize=4, shape=(), dflt=b'', pos=5)}  byteorder := 'little'  chunkshape := (1680,)  autoindex := True  colindexes := {    "index": Index(6, mediumshuffle, zlib(1)).is_csi=False,    "B": Index(6, mediumshuffle, zlib(1)).is_csi=False,    "C": Index(6, mediumshuffle, zlib(1)).is_csi=False,    "string": Index(6, mediumshuffle, zlib(1)).is_csi=False,    "string2": Index(6, mediumshuffle, zlib(1)).is_csi=False}

There is some performance degradation by making lots of columns intodatacolumns, so it is up to the user to designate these. In addition,you cannot change data columns (nor indexables) after the firstappend/put operation (Of course you can simply read in the data andcreate a new table!).

Iterator#

You can passiterator=True orchunksize=number_in_a_chunktoselect andselect_as_multiple to return an iterator on the results.The default is 50,000 rows returned in a chunk.

In [557]:fordfinstore.select("df",chunksize=3):   .....:print(df)   .....:                   A         B         C2000-01-01  0.858644 -0.851236  1.0580062000-01-02 -0.080372 -1.268121  1.5619672000-01-03  0.816983  1.965656 -1.169408                   A         B         C2000-01-04  0.712795 -0.062433  0.7367552000-01-05 -0.298721 -1.988045  1.4753082000-01-06  1.103675  1.382242 -0.650762                   A         B         C2000-01-07 -0.729161 -0.142928 -1.0630382000-01-08 -1.005977  0.465222 -0.094517

Note

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

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

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

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

In [558]:dfeq=pd.DataFrame({"number":np.arange(1,11)})In [559]:dfeqOut[559]:   number0       11       22       33       44       55       66       77       88       99      10In [560]:store.append("dfeq",dfeq,data_columns=["number"])In [561]:defchunks(l,n):   .....:return[l[i:i+n]foriinrange(0,len(l),n)]   .....:In [562]:evens=[2,4,6,8,10]In [563]:coordinates=store.select_as_coordinates("dfeq","number=evens")In [564]:forcinchunks(coordinates,2):   .....:print(store.select("dfeq",where=c))   .....:   number1       23       4   number5       67       8   number9      10

Advanced queries#

Select a single column#

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

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

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

In [567]:df_coord=pd.DataFrame(   .....:np.random.randn(1000,2),index=pd.date_range("20000101",periods=1000)   .....:)   .....:In [568]:store.append("df_coord",df_coord)In [569]:c=store.select_as_coordinates("df_coord","index > 20020101")In [570]:cOut[570]:Index([732, 733, 734, 735, 736, 737, 738, 739, 740, 741,       ...       990, 991, 992, 993, 994, 995, 996, 997, 998, 999],      dtype='int64', length=268)In [571]:store.select("df_coord",where=c)Out[571]:                   0         12002-01-02  0.007717  1.1683862002-01-03  0.759328 -0.6389342002-01-04 -1.154018 -0.3240712002-01-05 -0.804551 -1.2805932002-01-06 -0.047208  1.260503...              ...       ...2002-09-22 -1.139583  0.3443162002-09-23 -0.760643 -1.3067042002-09-24  0.059018  1.7754822002-09-25  1.242255 -0.0554572002-09-26  0.410317  2.194489[268 rows x 2 columns]
Selecting using a where mask#

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

In [572]:df_mask=pd.DataFrame(   .....:np.random.randn(1000,2),index=pd.date_range("20000101",periods=1000)   .....:)   .....:In [573]:store.append("df_mask",df_mask)In [574]:c=store.select_column("df_mask","index")In [575]:where=c[pd.DatetimeIndex(c).month==5].indexIn [576]:store.select("df_mask",where=where)Out[576]:                   0         12000-05-01  1.479511  0.5164332000-05-02 -0.334984 -1.4935372000-05-03  0.900321  0.0496952000-05-04  0.614266 -1.0771512000-05-05  0.233881  0.493246...              ...       ...2002-05-27  0.294122  0.4574072002-05-28 -1.102535  1.2156502002-05-29 -0.432911  0.7536062002-05-30 -1.105212  2.3118772002-05-31  2.567296  2.610691[93 rows x 2 columns]
Storer object#

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

In [577]:store.get_storer("df_dc").nrowsOut[577]:8

Multiple table queries#

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

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

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

In [578]:df_mt=pd.DataFrame(   .....:np.random.randn(8,6),   .....:index=pd.date_range("1/1/2000",periods=8),   .....:columns=["A","B","C","D","E","F"],   .....:)   .....:In [579]:df_mt["foo"]="bar"In [580]:df_mt.loc[df_mt.index[1],("A","B")]=np.nan# you can also create the tables individuallyIn [581]:store.append_to_multiple(   .....:{"df1_mt":["A","B"],"df2_mt":None},df_mt,selector="df1_mt"   .....:)   .....:In [582]:storeOut[582]:<class 'pandas.io.pytables.HDFStore'>File path: store.h5# individual tables were createdIn [583]:store.select("df1_mt")Out[583]:                   A         B2000-01-01  0.162291 -0.4304892000-01-02       NaN       NaN2000-01-03  0.429207 -1.0992742000-01-04  1.869081 -1.4660392000-01-05  0.092130 -1.7262802000-01-06  0.266901 -0.0368542000-01-07 -0.517871 -0.9903172000-01-08 -0.231342  0.557402In [584]:store.select("df2_mt")Out[584]:                   C         D         E         F  foo2000-01-01 -2.502042  0.668149  0.460708  1.834518  bar2000-01-02  0.130441 -0.608465  0.439872  0.506364  bar2000-01-03 -1.069546  1.236277  0.116634 -1.772519  bar2000-01-04  0.137462  0.313939  0.748471 -0.943009  bar2000-01-05  0.836517  2.049798  0.562167  0.189952  bar2000-01-06  1.112750 -0.151596  1.503311  0.939470  bar2000-01-07 -0.294348  0.335844 -0.794159  1.495614  bar2000-01-08  0.860312 -0.538674 -0.541986 -1.759606  bar# as a multipleIn [585]:store.select_as_multiple(   .....:["df1_mt","df2_mt"],   .....:where=["A>0","B>0"],   .....:selector="df1_mt",   .....:)   .....:Out[585]:Empty DataFrameColumns: [A, B, C, D, E, F, foo]Index: []

Delete from a table#

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

Data is ordered (on the disk) in terms of theindexables. Here’s asimple use case. You store panel-type data, with dates in themajor_axis and ids in theminor_axis. The data is theninterleaved like this:

  • date_1
    • id_1

    • id_2

    • .

    • id_n

  • date_2
    • id_1

    • .

    • id_n

It should be clear that a delete operation on themajor_axis will befairly quick, as one chunk is removed, then the following data moved. Onthe other hand a delete operation on theminor_axis will be veryexpensive. In this case it would almost certainly be faster to rewritethe table using awhere that selects all but the missing data.

Warning

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

Torepack and clean the file, useptrepack.

Notes & caveats#

Compression#

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

  • complevel specifies if and how hard data is to be compressed.complevel=0 andcomplevel=None disables compression and0<complevel<10 enables compression.

  • complib specifies which compression library to use.If nothing is specified the default libraryzlib is used. Acompression library usually optimizes for either good compression ratesor speed and the results will depend on the type of data. Which type ofcompression to choose depends on your specific needs and data. The listof supported compression libraries:

    • zlib: The default compression library.A classic in terms of compression, achieves good compressionrates but is somewhat slow.

    • lzo: Fastcompression and decompression.

    • bzip2: Good compression rates.

    • blosc: Fast compression anddecompression.

      Support for alternative blosc compressors:

      • blosc:blosclz This is thedefault compressor forblosc

      • blosc:lz4:A compact, very popular and fast compressor.

      • blosc:lz4hc:A tweaked version of LZ4, produces bettercompression ratios at the expense of speed.

      • blosc:snappy:A popular compressor used in many places.

      • blosc:zlib: A classic;somewhat slower than the previous ones, butachieving better compression ratios.

      • blosc:zstd: Anextremely well balanced codec; it provides the bestcompression ratios among the others above, and atreasonably fast speed.

    Ifcomplib is defined as something other than the listed libraries aValueError exception is issued.

Note

If the library specified with thecomplib option is missing on your platform,compression defaults tozlib without further ado.

Enable compression for all objects within the file:

store_compressed=pd.HDFStore("store_compressed.h5",complevel=9,complib="blosc:blosclz")

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

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

ptrepack#

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

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

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

Caveats#

Warning

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

  • If you use locks to manage write access between multiple processes, youmay want to usefsync() before releasing write locks. Forconvenience you can usestore.flush(fsync=True) to do this for you.

  • Once atable is created columns (DataFrame)are fixed; only exactly the same columns can be appended

  • Be aware that timezones (e.g.,pytz.timezone('US/Eastern'))are not necessarily equal across timezone versions. So if data islocalized to a specific timezone in the HDFStore using one versionof a timezone library and that data is updated with another version, the datawill be converted to UTC since these timezones are not consideredequal. Either use the same version of timezone library or usetz_convert withthe updated timezone definition.

Warning

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

DataTypes#

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

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, andWILL FAIL.

Categorical data#

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

In [586]:dfcat=pd.DataFrame(   .....:{"A":pd.Series(list("aabbcdba")).astype("category"),"B":np.random.randn(8)}   .....:)   .....:In [587]:dfcatOut[587]:   A         B0  a -1.5204781  a -1.0693912  b -0.5519813  b  0.4524074  c  0.4092575  d  0.3019116  b -0.6408437  a -2.253022In [588]:dfcat.dtypesOut[588]:A    categoryB     float64dtype: objectIn [589]:cstore=pd.HDFStore("cats.h5",mode="w")In [590]:cstore.append("dfcat",dfcat,format="table",data_columns=["A"])In [591]:result=cstore.select("dfcat",where="A in ['b', 'c']")In [592]:resultOut[592]:   A         B2  b -0.5519813  b  0.4524074  c  0.4092576  b -0.640843In [593]:result.dtypesOut[593]:A    categoryB     float64dtype: object

String columns#

min_itemsize

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

Passmin_itemsize on the first table creation to a-priori specify the minimum length of a particular string column.min_itemsize can be an integer, or a dict mapping a column name to an integer. You can passvalues as a key toallow allindexables ordata_columns to have this min_itemsize.

Passing amin_itemsize dict will cause all passed columns to be created asdata_columns automatically.

Note

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

In [594]:dfs=pd.DataFrame({"A":"foo","B":"bar"},index=list(range(5)))In [595]:dfsOut[595]:     A    B0  foo  bar1  foo  bar2  foo  bar3  foo  bar4  foo  bar# A and B have a size of 30In [596]:store.append("dfs",dfs,min_itemsize=30)In [597]:store.get_storer("dfs").tableOut[597]:/dfs/table (Table(5,)) ''  description := {  "index": Int64Col(shape=(), dflt=0, pos=0),  "values_block_0": StringCol(itemsize=30, shape=(2,), dflt=b'', pos=1)}  byteorder := 'little'  chunkshape := (963,)  autoindex := True  colindexes := {    "index": Index(6, mediumshuffle, zlib(1)).is_csi=False}# A is created as a data_column with a size of 30# B is size is calculatedIn [598]:store.append("dfs2",dfs,min_itemsize={"A":30})In [599]:store.get_storer("dfs2").tableOut[599]:/dfs2/table (Table(5,)) ''  description := {  "index": Int64Col(shape=(), dflt=0, pos=0),  "values_block_0": StringCol(itemsize=3, shape=(1,), dflt=b'', pos=1),  "A": StringCol(itemsize=30, shape=(), dflt=b'', pos=2)}  byteorder := 'little'  chunkshape := (1598,)  autoindex := True  colindexes := {    "index": Index(6, mediumshuffle, zlib(1)).is_csi=False,    "A": Index(6, mediumshuffle, zlib(1)).is_csi=False}

nan_rep

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

In [600]:dfss=pd.DataFrame({"A":["foo","bar","nan"]})In [601]:dfssOut[601]:     A0  foo1  bar2  nanIn [602]:store.append("dfss",dfss)In [603]:store.select("dfss")Out[603]:     A0  foo1  bar2  NaN# here you need to specify a different nan repIn [604]:store.append("dfss2",dfss,nan_rep="_nan_")In [605]:store.select("dfss2")Out[605]:     A0  foo1  bar2  nan

Performance#

  • tables format come with a writing performance penalty as compared tofixed stores. The benefit is the ability to append/delete andquery (potentially very large amounts of data). Write times aregenerally longer as compared with regular stores. Query times canbe quite fast, especially on an indexed axis.

  • You can passchunksize=<int> toappend, specifying thewrite chunksize (default is 50000). This will significantly loweryour memory usage on writing.

  • You can passexpectedrows=<int> to the firstappend,to set the TOTAL number of rows thatPyTables will expect.This will optimize read/write performance.

  • Duplicate rows can be written to tables, but are filtered out inselection (with the last items being selected; thus a table isunique on major, minor pairs)

  • APerformanceWarning will be raised if you are attempting tostore types that will be pickled by PyTables (rather than stored asendemic types). SeeHerefor more information and some solutions.

Feather#

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

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

Several caveats:

  • The format will NOT write anIndex, orMultiIndex for theDataFrame and will raise an error if a non-default one is provided. Youcan.reset_index() to store the index or.reset_index(drop=True) toignore it.

  • Duplicate column names and non-string columns names are not supported

  • Actual Python objects in object dtype columns are not supported. These willraise a helpful error message on an attempt at serialization.

See theFull Documentation.

In [606]:df=pd.DataFrame(   .....:{   .....:"a":list("abc"),   .....:"b":list(range(1,4)),   .....:"c":np.arange(3,6).astype("u1"),   .....:"d":np.arange(4.0,7.0,dtype="float64"),   .....:"e":[True,False,True],   .....:"f":pd.Categorical(list("abc")),   .....:"g":pd.date_range("20130101",periods=3),   .....:"h":pd.date_range("20130101",periods=3,tz="US/Eastern"),   .....:"i":pd.date_range("20130101",periods=3,freq="ns"),   .....:}   .....:)   .....:In [607]:dfOut[607]:   a  b  c  ...          g                         h                             i0  a  1  3  ... 2013-01-01 2013-01-01 00:00:00-05:00 2013-01-01 00:00:00.0000000001  b  2  4  ... 2013-01-02 2013-01-02 00:00:00-05:00 2013-01-01 00:00:00.0000000012  c  3  5  ... 2013-01-03 2013-01-03 00:00:00-05:00 2013-01-01 00:00:00.000000002[3 rows x 9 columns]In [608]:df.dtypesOut[608]:a                        objectb                         int64c                         uint8d                       float64e                          boolf                      categoryg                datetime64[ns]h    datetime64[ns, US/Eastern]i                datetime64[ns]dtype: object

Write to a feather file.

In [609]:df.to_feather("example.feather")

Read from a feather file.

In [610]:result=pd.read_feather("example.feather")In [611]:resultOut[611]:   a  b  c  ...          g                         h                             i0  a  1  3  ... 2013-01-01 2013-01-01 00:00:00-05:00 2013-01-01 00:00:00.0000000001  b  2  4  ... 2013-01-02 2013-01-02 00:00:00-05:00 2013-01-01 00:00:00.0000000012  c  3  5  ... 2013-01-03 2013-01-03 00:00:00-05:00 2013-01-01 00:00:00.000000002[3 rows x 9 columns]# we preserve dtypesIn [612]:result.dtypesOut[612]:a                        objectb                         int64c                         uint8d                       float64e                          boolf                      categoryg                datetime64[ns]h    datetime64[ns, US/Eastern]i                datetime64[ns]dtype: object

Parquet#

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

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

Several caveats.

  • Duplicate column names and non-string columns names are not supported.

  • Thepyarrow engine always writes the index to the output, butfastparquet only writes non-defaultindexes. This extra column can cause problems for non-pandas consumers that are not expecting it. You canforce including or omitting indexes with theindex argument, regardless of the underlying engine.

  • Index level names, if specified, must be strings.

  • In thepyarrow engine, categorical dtypes for non-string types can be serialized to parquet, but will de-serialize as their primitive dtype.

  • Thepyarrow engine preserves theordered flag of categorical dtypes with string types.fastparquet does not preserve theordered flag.

  • Non supported types includeInterval and actual Python object types. These will raise a helpful error messageon an attempt at serialization.Period type is supported with pyarrow >= 0.16.0.

  • Thepyarrow engine preserves extension data types such as the nullable integer and string datatype (requiring pyarrow >= 0.16.0, and requiring the extension type to implement the needed protocols,see theextension types documentation).

You can specify anengine to direct the serialization. This can be one ofpyarrow, orfastparquet, orauto.If the engine is NOT specified, then thepd.options.io.parquet.engine option is checked; if this is alsoauto,thenpyarrow is tried, and falling back tofastparquet.

See the documentation forpyarrow andfastparquet.

Note

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

In [613]:df=pd.DataFrame(   .....:{   .....:"a":list("abc"),   .....:"b":list(range(1,4)),   .....:"c":np.arange(3,6).astype("u1"),   .....:"d":np.arange(4.0,7.0,dtype="float64"),   .....:"e":[True,False,True],   .....:"f":pd.date_range("20130101",periods=3),   .....:"g":pd.date_range("20130101",periods=3,tz="US/Eastern"),   .....:"h":pd.Categorical(list("abc")),   .....:"i":pd.Categorical(list("abc"),ordered=True),   .....:}   .....:)   .....:In [614]:dfOut[614]:   a  b  c    d      e          f                         g  h  i0  a  1  3  4.0   True 2013-01-01 2013-01-01 00:00:00-05:00  a  a1  b  2  4  5.0  False 2013-01-02 2013-01-02 00:00:00-05:00  b  b2  c  3  5  6.0   True 2013-01-03 2013-01-03 00:00:00-05:00  c  cIn [615]:df.dtypesOut[615]:a                        objectb                         int64c                         uint8d                       float64e                          boolf                datetime64[ns]g    datetime64[ns, US/Eastern]h                      categoryi                      categorydtype: object

Write to a parquet file.

In [616]:df.to_parquet("example_pa.parquet",engine="pyarrow")In [617]:df.to_parquet("example_fp.parquet",engine="fastparquet")

Read from a parquet file.

In [618]:result=pd.read_parquet("example_fp.parquet",engine="fastparquet")In [619]:result=pd.read_parquet("example_pa.parquet",engine="pyarrow")In [620]:result.dtypesOut[620]:a                        objectb                         int64c                         uint8d                       float64e                          boolf                datetime64[ns]g    datetime64[ns, US/Eastern]h                      categoryi                      categorydtype: object

By setting thedtype_backend argument you can control the default dtypes used for the resulting DataFrame.

In [621]:result=pd.read_parquet("example_pa.parquet",engine="pyarrow",dtype_backend="pyarrow")In [622]:result.dtypesOut[622]:a                                      string[pyarrow]b                                       int64[pyarrow]c                                       uint8[pyarrow]d                                      double[pyarrow]e                                        bool[pyarrow]f                               timestamp[ns][pyarrow]g                timestamp[ns, tz=US/Eastern][pyarrow]h    dictionary<values=string, indices=int32, order...i    dictionary<values=string, indices=int32, order...dtype: object

Note

Note that this is not supported forfastparquet.

Read only certain columns of a parquet file.

In [623]:result=pd.read_parquet(   .....:"example_fp.parquet",   .....:engine="fastparquet",   .....:columns=["a","b"],   .....:)   .....:In [624]:result=pd.read_parquet(   .....:"example_pa.parquet",   .....:engine="pyarrow",   .....:columns=["a","b"],   .....:)   .....:In [625]:result.dtypesOut[625]:a    objectb     int64dtype: object

Handling indexes#

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

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

creates a parquet file withthree columns if you usepyarrow for serialization:a,b, and__index_level_0__. If you’re usingfastparquet, theindexmay or may notbe written to the file.

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

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

In [628]:df.to_parquet("test.parquet",index=False)

This creates a parquet file with just the two expected columns,a andb.If yourDataFrame has a custom index, you won’t get it back when you loadthis file into aDataFrame.

Passingindex=True willalways write the index, even if that’s not theunderlying engine’s default behavior.

Partitioning Parquet files#

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

In [629]:df=pd.DataFrame({"a":[0,0,1,1],"b":[0,1,0,1]})In [630]:df.to_parquet(path="test",engine="pyarrow",partition_cols=["a"],compression=None)

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

test├── a=0│   ├── 0bac803e32dc42ae83fddfd029cbdebc.parquet│   └──  ...└── a=1    ├── e6ab24a4f45147b49b54a662f0c412a3.parquet    └── ...

ORC#

Similar to theparquet format, theORC Format is a binary columnar serializationfor data frames. It is designed to make reading data frames efficient. pandas provides both the reader and the writer for theORC format,read_orc() andto_orc(). This requires thepyarrow library.

Warning

In [631]:df=pd.DataFrame(   .....:{   .....:"a":list("abc"),   .....:"b":list(range(1,4)),   .....:"c":np.arange(4.0,7.0,dtype="float64"),   .....:"d":[True,False,True],   .....:"e":pd.date_range("20130101",periods=3),   .....:}   .....:)   .....:In [632]:dfOut[632]:   a  b    c      d          e0  a  1  4.0   True 2013-01-011  b  2  5.0  False 2013-01-022  c  3  6.0   True 2013-01-03In [633]:df.dtypesOut[633]:a            objectb             int64c           float64d              boole    datetime64[ns]dtype: object

Write to an orc file.

In [634]:df.to_orc("example_pa.orc",engine="pyarrow")

Read from an orc file.

In [635]:result=pd.read_orc("example_pa.orc")In [636]:result.dtypesOut[636]:a            objectb             int64c           float64d              boole    datetime64[ns]dtype: object

Read only certain columns of an orc file.

In [637]:result=pd.read_orc(   .....:"example_pa.orc",   .....:columns=["a","b"],   .....:)   .....:In [638]:result.dtypesOut[638]:a    objectb     int64dtype: object

SQL queries#

Thepandas.io.sql module provides a collection of query wrappers to bothfacilitate data retrieval and to reduce dependency on DB-specific API.

Where available, users may first want to opt forApache Arrow ADBC drivers. These driversshould provide the best performance, null handling, and type detection.

Added in version 2.2.0:Added native support for ADBC drivers

For a full list of ADBC drivers and their development status, see theADBC DriverImplementation Statusdocumentation.

Where an ADBC driver is not available or may be missing functionality,users should opt for installing SQLAlchemy alongside their database driver library.Examples of such drivers arepsycopg2for PostgreSQL orpymysql for MySQL.ForSQLite this isincluded in Python’s standard library by default.You can find an overview of supported drivers for each SQL dialect in theSQLAlchemy docs.

If SQLAlchemy is not installed, you can use asqlite3.Connection in place ofa SQLAlchemy engine, connection, or URI string.

See also somecookbook examples for some advanced strategies.

The key functions are:

read_sql_table(table_name, con[, schema, ...])

Read SQL database table into a DataFrame.

read_sql_query(sql, con[, index_col, ...])

Read SQL query into a DataFrame.

read_sql(sql, con[, index_col, ...])

Read SQL query or database table into a DataFrame.

DataFrame.to_sql(name, con, *[, schema, ...])

Write records stored in a DataFrame to a SQL database.

Note

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

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

To connect using an ADBC driver you will want to install theadbc_driver_sqlite using yourpackage manager. Once installed, you can use the DBAPI interface provided by the ADBC driverto connect to your database.

importadbc_driver_sqlite.dbapiassqlite_dbapi# Create the connectionwithsqlite_dbapi.connect("sqlite:///:memory:")asconn:df=pd.read_sql_table("data",conn)

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

In [639]:fromsqlalchemyimportcreate_engine# Create your engine.In [640]:engine=create_engine("sqlite:///:memory:")

If you want to manage your own connections you can pass one of those instead. The example below opens aconnection to the database using a Python context manager that automatically closes the connection afterthe block has completed.See theSQLAlchemy docsfor an explanation of how the database connection is handled.

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

Warning

When you open a connection to a database you are also responsible for closing it.Side effects of leaving a connection open may include locking the database orother breaking behaviour.

Writing DataFrames#

Assuming the following data is in aDataFramedata, we can insert it intothe database usingto_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

In [641]:importdatetimeIn [642]:c=["id","Date","Col_1","Col_2","Col_3"]In [643]:d=[   .....:(26,datetime.datetime(2010,10,18),"X",27.5,True),   .....:(42,datetime.datetime(2010,10,19),"Y",-12.5,False),   .....:(63,datetime.datetime(2010,10,20),"Z",5.73,True),   .....:]   .....:In [644]:data=pd.DataFrame(d,columns=c)In [645]:dataOut[645]:   id       Date Col_1  Col_2  Col_30  26 2010-10-18     X  27.50   True1  42 2010-10-19     Y -12.50  False2  63 2010-10-20     Z   5.73   TrueIn [646]:data.to_sql("data",con=engine)Out[646]:3

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

In [647]:data.to_sql("data_chunked",con=engine,chunksize=1000)Out[647]:3

SQL data types#

Ensuring consistent data type management across SQL databases is challenging.Not every SQL database offers the same types, and even when they do the implementationof a given type can vary in ways that have subtle effects on how types can bepreserved.

For the best odds at preserving database types users are advised to useADBC drivers when available. The Arrow type system offers a wider array oftypes that more closely match database types than the historical pandas/NumPytype system. To illustrate, note this (non-exhaustive) listing of typesavailable in different databases and pandas backends:

numpy/pandas

arrow

postgres

sqlite

int16/Int16

int16

SMALLINT

INTEGER

int32/Int32

int32

INTEGER

INTEGER

int64/Int64

int64

BIGINT

INTEGER

float32

float32

REAL

REAL

float64

float64

DOUBLE PRECISION

REAL

object

string

TEXT

TEXT

bool

bool_

BOOLEAN

datetime64[ns]

timestamp(us)

TIMESTAMP

datetime64[ns,tz]

timestamp(us,tz)

TIMESTAMPTZ

date32

DATE

month_day_nano_interval

INTERVAL

binary

BINARY

BLOB

decimal128

DECIMAL[1]

list

ARRAY[1]

struct

COMPOSITE TYPE

[1]

Footnotes

[1](1,2,3)

Not implemented as of writing, but theoretically possible

If you are interested in preserving database types as best as possiblethroughout the lifecycle of your DataFrame, users are encouraged toleverage thedtype_backend="pyarrow" argument ofread_sql()

# for roundtrippingwithpg_dbapi.connect(uri)asconn:df2=pd.read_sql("pandas_table",conn,dtype_backend="pyarrow")

This will prevent your data from being converted to the traditional pandas/NumPytype system, which often converts SQL types in ways that make them impossible toround-trip.

In case an ADBC driver is not available,to_sql()will try to map your data to an appropriate SQL data type based on the dtype ofthe data. When you have columns of dtypeobject, pandas will try to inferthe data type.

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

In [648]:fromsqlalchemy.typesimportStringIn [649]:data.to_sql("data_dtype",con=engine,dtype={"Col_1":String})Out[649]:3

Note

Due to the limited support for timedelta’s in the different databaseflavors, columns with typetimedelta64 will be written as integervalues as nanoseconds to the database and a warning will be raised. The onlyexception to this is when using the ADBC PostgreSQL driver in which case atimedelta will be written to the database as anINTERVAL

Note

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

Datetime data types#

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

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

Database

SQL Datetime Types

Timezone Support

SQLite

TEXT

No

MySQL

TIMESTAMP orDATETIME

No

PostgreSQL

TIMESTAMP orTIMESTAMPWITHTIMEZONE

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 timewith respect to the timezone.

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

Insertion method#

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

  • None: Uses standard SQLINSERT clause (one per row).

  • 'multi': Pass multiple values in a singleINSERT clause.It uses aspecial SQL syntax not supported by all backends.This usually provides better performance for analytic databaseslikePresto andRedshift, but has worse performance fortraditional SQL backend if the table contains many columns.For more information check the SQLAlchemydocumentation.

  • callable with signature(pd_table,conn,keys,data_iter):This can be used to implement a more performant insertion method based onspecific backend dialect features.

Example of a callable using PostgreSQLCOPY clause:

# Alternative to_sql() *method* for DBs that support COPY FROMimportcsvfromioimportStringIOdefpsql_insert_copy(table,conn,keys,data_iter):"""    Execute SQL statement inserting data    Parameters    ----------    table : pandas.io.sql.SQLTable    conn : sqlalchemy.engine.Engine or sqlalchemy.engine.Connection    keys : list of str        Column names    data_iter : Iterable that iterates the values to be inserted    """# gets a DBAPI connection that can provide a cursordbapi_conn=conn.connectionwithdbapi_conn.cursor()ascur:s_buf=StringIO()writer=csv.writer(s_buf)writer.writerows(data_iter)s_buf.seek(0)columns=', '.join(['"{}"'.format(k)forkinkeys])iftable.schema:table_name='{}.{}'.format(table.schema,table.name)else:table_name=table.namesql='COPY{} ({}) FROM STDIN WITH CSV'.format(table_name,columns)cur.copy_expert(sql=sql,file=s_buf)

Reading tables#

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

Note

In order to useread_sql_table(), youmust have theADBC driver or SQLAlchemy optional dependency installed.

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

Note

ADBC drivers will map database types directly back to arrow types. For other driversnote that pandas infers column dtypes from query outputs, and not by lookingup data types in the physical database schema. For example, assumeuseridis an integer column in a table. Then, intuitively,selectuserid... willreturn integer-valued series, whileselectcast(useridastext)... willreturn object-valued (str) series. Accordingly, if the query output is empty,then all resulting columns will be returned as object-valued (since they aremost general). If you foresee that your query will sometimes generate an emptyresult, you may want to explicitly typecast afterwards to ensure dtypeintegrity.

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

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

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

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

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

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

You can check if a table exists usinghas_table()

Schema support#

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

df.to_sql(name="table",con=engine,schema="other_schema")pd.read_sql_table("table",engine,schema="other_schema")

Querying#

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

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

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

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

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

In [656]:df=pd.DataFrame(np.random.randn(20,3),columns=list("abc"))In [657]:df.to_sql(name="data_chunks",con=engine,index=False)Out[657]:20
In [658]:forchunkinpd.read_sql_query("SELECT * FROM data_chunks",engine,chunksize=5):   .....:print(chunk)   .....:          a         b         c0 -0.395347 -0.822726 -0.3637771  1.676124 -0.908102 -1.3913462 -1.094269  0.278380  1.2058993  1.503443  0.932171 -0.7094594 -0.645944 -1.351389  0.132023          a         b         c0  0.210427  0.192202  0.6619491  1.690629 -1.046044  0.6186972 -0.013863  1.314289  1.9516113 -1.485026  0.304662  1.1947574 -0.446717  0.528496 -0.657575          a         b         c0 -0.876654  0.336252  0.1726681  0.337684 -0.411202 -0.8283942 -0.244413  1.094948  0.0871833  1.125934 -1.480095  1.2059444 -0.451849  0.452214 -2.208192          a         b         c0 -2.061019  0.044184 -0.0171181  1.248959 -0.675595 -1.9082962 -0.125934  1.491974  0.6487263  0.391214  0.438609  1.6342484  1.208707 -1.535740  1.620399

Engine connection examples#

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

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

For more information see the examples the SQLAlchemydocumentation

Advanced SQLAlchemy queries#

You can use SQLAlchemy constructs to describe your query.

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

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

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

In [661]:metadata=sa.MetaData()In [662]:data_table=sa.Table(   .....:"data",   .....:metadata,   .....:sa.Column("index",sa.Integer),   .....:sa.Column("Date",sa.DateTime),   .....:sa.Column("Col_1",sa.String),   .....:sa.Column("Col_2",sa.Float),   .....:sa.Column("Col_3",sa.Boolean),   .....:)   .....:In [663]:pd.read_sql(sa.select(data_table).where(data_table.c.Col_3isTrue),engine)Out[663]:Empty DataFrameColumns: [index, Date, Col_1, Col_2, Col_3]Index: []

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

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

Sqlite fallback#

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

You can create connections like so:

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

And then issue the following queries:

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

Google BigQuery#

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

pandas integrates with this external package. ifpandas-gbq is installed, you canuse the pandas methodspd.read_gbq andDataFrame.to_gbq, which will call therespective functions frompandas-gbq.

Full documentation can be foundhere.

Stata format#

Writing to stata format#

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

In [667]:df=pd.DataFrame(np.random.randn(10,2),columns=list("AB"))In [668]:df.to_stata("stata.dta")

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

Note

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

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

Warning

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

Warning

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

Reading from Stata format#

The top-level functionread_stata will read a dta file and returneither aDataFrame or apandas.api.typing.StataReader that canbe used to read the file incrementally.

In [669]:pd.read_stata("stata.dta")Out[669]:   index         A         B0      0 -0.165614  0.4904821      1 -0.637829  0.0670912      2 -0.242577  1.3480383      3  0.647699 -0.6449374      4  0.625771  0.9183765      5  0.401781 -1.4889196      6 -0.981845 -0.0468827      7 -0.306796  0.8770258      8 -0.336606  0.6247479      9 -1.582600  0.806340

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

In [670]:withpd.read_stata("stata.dta",chunksize=3)asreader:   .....:fordfinreader:   .....:print(df.shape)   .....:(3, 3)(3, 3)(3, 3)(1, 3)

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

In [671]:withpd.read_stata("stata.dta",iterator=True)asreader:   .....:chunk1=reader.read(5)   .....:chunk2=reader.read(5)   .....:

Currently theindex is retrieved as a column.

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

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

Note

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

Note

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

Note

AllStataReader objects, whether created byread_stata()(when usingiterator=True orchunksize) or instantiated by hand, must be used as contextmanagers (e.g. thewith statement).While theclose() method is available, its use is unsupported.It is not part of the public API and will be removed in with future without warning.

Categorical data#

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

Warning

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

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

Note

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

Note

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

SAS formats#

The top-level functionread_sas() can read (but not write) SASXPORT (.xpt) and SAS7BDAT (.sas7bdat) format files.

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

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

Read a SAS7BDAT file:

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

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

defdo_something(chunk):passwithpd.read_sas("sas_xport.xpt",chunk=100000)asrdr:forchunkinrdr:do_something(chunk)

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

No official documentation is available for the SAS7BDAT format.

SPSS formats#

The top-level functionread_spss() can read (but not write) SPSSSAV (.sav) and ZSAV (.zsav) format files.

SPSS files contain column names. By default thewhole file is read, categorical columns are converted intopd.Categorical,and aDataFrame with all columns is returned.

Specify theusecols parameter to obtain a subset of columns. Specifyconvert_categoricals=Falseto avoid converting categorical columns intopd.Categorical.

Read an SPSS file:

df=pd.read_spss("spss_data.sav")

Extract a subset of columns contained inusecols from an SPSS file andavoid converting categorical columns intopd.Categorical:

df=pd.read_spss("spss_data.sav",usecols=["foo","bar"],convert_categoricals=False,)

More information about the SAV and ZSAV file formats is availablehere.

Other file formats#

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

netCDF#

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

Performance considerations#

This is an informal comparison of various IO methods, using pandas0.24.2. Timings are machine dependent and small differences should beignored.

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

The following test functions will be used below to compare the performance of several IO methods:

importnumpyasnpimportossz=1000000df=pd.DataFrame({"A":np.random.randn(sz),"B":[1]*sz})sz=1000000np.random.seed(42)df=pd.DataFrame({"A":np.random.randn(sz),"B":[1]*sz})deftest_sql_write(df):ifos.path.exists("test.sql"):os.remove("test.sql")sql_db=sqlite3.connect("test.sql")df.to_sql(name="test_table",con=sql_db)sql_db.close()deftest_sql_read():sql_db=sqlite3.connect("test.sql")pd.read_sql_query("select * from test_table",sql_db)sql_db.close()deftest_hdf_fixed_write(df):df.to_hdf("test_fixed.hdf",key="test",mode="w")deftest_hdf_fixed_read():pd.read_hdf("test_fixed.hdf","test")deftest_hdf_fixed_write_compress(df):df.to_hdf("test_fixed_compress.hdf",key="test",mode="w",complib="blosc")deftest_hdf_fixed_read_compress():pd.read_hdf("test_fixed_compress.hdf","test")deftest_hdf_table_write(df):df.to_hdf("test_table.hdf",key="test",mode="w",format="table")deftest_hdf_table_read():pd.read_hdf("test_table.hdf","test")deftest_hdf_table_write_compress(df):df.to_hdf("test_table_compress.hdf",key="test",mode="w",complib="blosc",format="table")deftest_hdf_table_read_compress():pd.read_hdf("test_table_compress.hdf","test")deftest_csv_write(df):df.to_csv("test.csv",mode="w")deftest_csv_read():pd.read_csv("test.csv",index_col=0)deftest_feather_write(df):df.to_feather("test.feather")deftest_feather_read():pd.read_feather("test.feather")deftest_pickle_write(df):df.to_pickle("test.pkl")deftest_pickle_read():pd.read_pickle("test.pkl")deftest_pickle_write_compress(df):df.to_pickle("test.pkl.compress",compression="xz")deftest_pickle_read_compress():pd.read_pickle("test.pkl.compress",compression="xz")deftest_parquet_write(df):df.to_parquet("test.parquet")deftest_parquet_read():pd.read_parquet("test.parquet")

When writing, the top three functions in terms of speed aretest_feather_write,test_hdf_fixed_write andtest_hdf_fixed_write_compress.

In [4]:%timeit test_sql_write(df)3.29 s ± 43.2 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)In [5]:%timeit test_hdf_fixed_write(df)19.4 ms ± 560 µs per loop (mean ± std. dev. of 7 runs, 1 loop each)In [6]:%timeit test_hdf_fixed_write_compress(df)19.6 ms ± 308 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)In [7]:%timeit test_hdf_table_write(df)449 ms ± 5.61 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)In [8]:%timeit test_hdf_table_write_compress(df)448 ms ± 11.9 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)In [9]:%timeit test_csv_write(df)3.66 s ± 26.2 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)In [10]:%timeit test_feather_write(df)9.75 ms ± 117 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)In [11]:%timeit test_pickle_write(df)30.1 ms ± 229 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)In [12]:%timeit test_pickle_write_compress(df)4.29 s ± 15.9 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)In [13]:%timeit test_parquet_write(df)67.6 ms ± 706 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)

When reading, the top three functions in terms of speed aretest_feather_read,test_pickle_read andtest_hdf_fixed_read.

In [14]:%timeit test_sql_read()1.77 s ± 17.7 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)In [15]:%timeit test_hdf_fixed_read()19.4 ms ± 436 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)In [16]:%timeit test_hdf_fixed_read_compress()19.5 ms ± 222 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)In [17]:%timeit test_hdf_table_read()38.6 ms ± 857 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)In [18]:%timeit test_hdf_table_read_compress()38.8 ms ± 1.49 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)In [19]:%timeit test_csv_read()452 ms ± 9.04 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)In [20]:%timeit test_feather_read()12.4 ms ± 99.7 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)In [21]:%timeit test_pickle_read()18.4 ms ± 191 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)In [22]:%timeit test_pickle_read_compress()915 ms ± 7.48 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)In [23]:%timeit test_parquet_read()24.4 ms ± 146 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)

The filestest.pkl.compress,test.parquet andtest.feather took the least space on disk (in bytes).

29519500 Oct 10 06:45 test.csv16000248 Oct 10 06:45 test.feather8281983  Oct 10 06:49 test.parquet16000857 Oct 10 06:47 test.pkl7552144  Oct 10 06:48 test.pkl.compress34816000 Oct 10 06:42 test.sql24009288 Oct 10 06:43 test_fixed.hdf24009288 Oct 10 06:43 test_fixed_compress.hdf24458940 Oct 10 06:44 test_table.hdf24458940 Oct 10 06:44 test_table_compress.hdf
On this page

[8]ページ先頭

©2009-2025 Movatter.jp