Convert the object to a JSON string.
Note NaN’s and None will be converted to null and datetime objects will be converted to UNIX timestamps.
String, path object (implementing os.PathLike[str]), or file-like object implementing a write() function. If None, the result is returned as a string.
Indication of expected JSON string format.
Series:
default is ‘index’
allowed values are: {‘split’, ‘records’, ‘index’, ‘table’}.
DataFrame:
default is ‘columns’
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}, … , {column -> value}]
‘index’ : dict like {index -> {column -> value}}
‘columns’ : dict like {column -> {index -> value}}
‘values’ : just the values array
‘table’ : dict like {‘schema’: {schema}, ‘data’: {data}}
Describing the data, where data component is like orient='records'.
Type of date conversion. ‘epoch’ = epoch milliseconds, ‘iso’ = ISO8601. The default depends on the orient. For orient='table', the default is ‘iso’. For all other orients, the default is ‘epoch’.
The number of decimal places to use when encoding floating point values.
Force encoded string to be ASCII.
The time unit to encode to, governs timestamp and ISO8601 precision. One of ‘s’, ‘ms’, ‘us’, ‘ns’ for second, millisecond, microsecond, and nanosecond respectively.
Handler to call if object cannot otherwise be converted to a suitable format for JSON. Should receive a single argument which is the object to convert and return a serialisable object.
If ‘orient’ is ‘records’ write out line-delimited json format. Will throw ValueError if incorrect ‘orient’ since others are not list-like.
For on-the-fly compression of the output data. If ‘infer’ and ‘path_or_buf’ path-like, then detect compression from the following extensions: ‘.gz’, ‘.bz2’, ‘.zip’, ‘.xz’, or ‘.zst’ (otherwise no compression). Set to None for no compression. Can also be a dict with key 'method' set to one of {'zip', 'gzip', 'bz2', 'zstd'} and other key-value pairs are forwarded to zipfile.ZipFile, gzip.GzipFile, bz2.BZ2File, or zstandard.ZstdDecompressor, respectively. As an example, the following could be passed for faster compression and to create a reproducible gzip archive: compression={'method': 'gzip', 'compresslevel': 1, 'mtime': 1}.
Changed in version 1.4.0: Zstandard support.
Whether to include the index values in the JSON string. Not including the index (index=False) is only supported when orient is ‘split’ or ‘table’.
Length of whitespace used to indent each record.
New in version 1.0.0.
Extra options that make sense for a particular storage connection, e.g. host, port, username, password, etc. For HTTP(S) URLs the key-value pairs are forwarded to urllib as header options. For other URLs (e.g. starting with “s3://”, and “gcs://”) the key-value pairs are forwarded to fsspec. Please see fsspec and urllib for more details.
New in version 1.2.0.
If path_or_buf is None, returns the resulting json format as a string. Otherwise returns None.
See also
Convert a JSON string to pandas object.
Notes
The behavior of indent=0 varies from the stdlib, which does not indent the output but does insert newlines. Currently, indent=0 and the default indent=None are equivalent in pandas, though this may change in a future release.
orient='table' contains a ‘pandas_version’ field under ‘schema’. This stores the version of pandas used in the latest revision of the schema.
Examples
Encoding/decoding a Dataframe using 'records' formatted JSON. Note that index labels are not preserved with this encoding.
Encoding/decoding a Dataframe using 'index' formatted JSON:
Encoding/decoding a Dataframe using 'columns' formatted JSON:
Encoding/decoding a Dataframe using 'values' formatted JSON:
Encoding with Table Schema:


Render object to a LaTeX tabular, longtable, or nested table.
Requires \usepackage{booktabs}. The output can be copy/pasted into a main LaTeX document or read from an external file with \input{table.tex}.
Changed in version 1.0.0: Added caption and label arguments.
Changed in version 1.2.0: Added position argument, changed meaning of caption argument.
Buffer to write to. If None, the output is returned as a string.
The subset of columns to write. Writes all columns by default.
The minimum width of each column.
Write out the column names. If a list of strings is given, it is assumed to be aliases for the column names.
Write row names (index).
Missing data representation.
Formatter functions to apply to columns’ elements by position or name. The result of each function must be a unicode string. List must be of length equal to the number of columns.
Formatter for floating point numbers. For example float_format="%.2f" and float_format="{:0.2f}".format will both result in 0.1234 being formatted as 0.12.
Set to False for a DataFrame with a hierarchical index to print every multiindex key at each row. By default, the value will be read from the config module.
Prints the names of the indexes.
Make the row labels bold in the output.
The columns format as specified in LaTeX table format e.g. ‘rcl’ for 3 columns. By default, ‘l’ will be used for all columns except columns of numbers, which default to ‘r’.
By default, the value will be read from the pandas config module. Use a longtable environment instead of tabular. Requires adding a usepackage{longtable} to your LaTeX preamble.
By default, the value will be read from the pandas config module. When set to False prevents from escaping latex special characters in column names.
A string representing the encoding to use in the output file, defaults to ‘utf-8’.
Character recognized as decimal separator, e.g. ‘,’ in Europe.
Use multicolumn to enhance MultiIndex columns. The default will be read from the config module.
The alignment for multicolumns, similar to column_format The default will be read from the config module.
Use multirow to enhance MultiIndex rows. Requires adding a usepackage{multirow} to your LaTeX preamble. Will print centered labels (instead of top-aligned) across the contained rows, separating groups via clines. The default will be read from the pandas config module.
Tuple (full_caption, short_caption), which results in \caption[short_caption]{full_caption}; if a single string is passed, no short caption will be set.
New in version 1.0.0.
Changed in version 1.2.0: Optionally allow caption to be a tuple (full_caption, short_caption).
The LaTeX label to be placed inside \label{} in the output. This is used with \ref{} in the main .tex file.
New in version 1.0.0.
The LaTeX positional argument for tables, to be placed after \begin{} in the output.
New in version 1.2.0.
If buf is None, returns the result as a string. Otherwise returns None.
See also
Render a DataFrame to LaTeX with conditional formatting.
Render a DataFrame to a console-friendly tabular output.
Render a DataFrame as an HTML table.
Examples


Return a list of the values.
These are each a scalar type, which is a Python scalar (for str, int, float) or a pandas scalar (for Timestamp/Timedelta/Interval/Period)
See also
Return the array as an a.ndim-levels deep nested list of Python scalars.


Print Series in Markdown-friendly format.
New in version 1.0.0.
Buffer to write to. If None, the output is returned as a string.
Mode in which file is opened, “wt” by default.
Add index (row) labels.
New in version 1.1.0.
Extra options that make sense for a particular storage connection, e.g. host, port, username, password, etc. For HTTP(S) URLs the key-value pairs are forwarded to urllib as header options. For other URLs (e.g. starting with “s3://”, and “gcs://”) the key-value pairs are forwarded to fsspec. Please see fsspec and urllib for more details.
New in version 1.2.0.
These parameters will be passed to tabulate.
Series in Markdown-friendly format.
Notes
Requires the tabulate package.
Examples
Output markdown with a tabulate option.


A NumPy ndarray representing the values in this Series or Index.
The dtype to pass to numpy.asarray().
Whether to ensure that the returned value is not a view on another array. Note that copy=False does not ensure that to_numpy() is no-copy. Rather, copy=True ensure that a copy is made, even if not strictly necessary.
The value to use for missing values. The default value depends on dtype and the type of the array.
New in version 1.0.0.
Additional keywords passed through to the to_numpy method of the underlying array (for extension arrays).
New in version 1.0.0.
See also
Get the actual data stored within.
Get the actual data stored within.
Similar method for DataFrame.
Notes
The returned array will be the same up to equality (values equal in self will be equal in the returned array; likewise for values that are not equal). When self contains an ExtensionArray, the dtype may be different. For example, for a category-dtype Series, to_numpy() will return a NumPy array and the categorical dtype will be lost.
For NumPy dtypes, this will be a reference to the actual data stored in this Series or Index (assuming copy=False). Modifying the result in place will modify the data stored in the Series or Index (not that we recommend doing that).
For extension types, to_numpy() may require copying data and coercing the result to a NumPy type (possibly object), which may be expensive. When you need a no-copy reference to the underlying data, Series.array should be used instead.
This table lays out the different dtypes and default return types of to_numpy() for various dtypes within pandas.
dtype
array type
category[T]
ndarray[T] (same dtype as input)
period
ndarray[object] (Periods)
interval
ndarray[object] (Intervals)
IntegerNA
ndarray[object]
datetime64[ns]
datetime64[ns]
datetime64[ns, tz]
ndarray[object] (Timestamps)
Examples
Specify the dtype to control how datetime-aware data is represented. Use dtype=object to return an ndarray of pandas Timestamp objects, each with the correct tz.
Or dtype='datetime64[ns]' to return an ndarray of native datetime64 values. The values are converted to UTC and the timezone info is dropped.


Convert Series from DatetimeIndex to PeriodIndex.
Frequency associated with the PeriodIndex.
Whether or not to return a copy.
Series with index converted to PeriodIndex.


Pickle (serialize) object to file.
File path where the pickled object will be stored.
For on-the-fly compression of the output data. If ‘infer’ and ‘path’ path-like, then detect compression from the following extensions: ‘.gz’, ‘.bz2’, ‘.zip’, ‘.xz’, or ‘.zst’ (otherwise no compression). Set to None for no compression. Can also be a dict with key 'method' set to one of {'zip', 'gzip', 'bz2', 'zstd'} and other key-value pairs are forwarded to zipfile.ZipFile, gzip.GzipFile, bz2.BZ2File, or zstandard.ZstdDecompressor, respectively. As an example, the following could be passed for faster compression and to create a reproducible gzip archive: compression={'method': 'gzip', 'compresslevel': 1, 'mtime': 1}.
Int which indicates which protocol should be used by the pickler, default HIGHEST_PROTOCOL (see [1] paragraph 12.1.2). The possible values are 0, 1, 2, 3, 4, 5. A negative value for the protocol parameter is equivalent to setting its value to HIGHEST_PROTOCOL.
https://docs.python.org/3/library/pickle.html.
Extra options that make sense for a particular storage connection, e.g. host, port, username, password, etc. For HTTP(S) URLs the key-value pairs are forwarded to urllib as header options. For other URLs (e.g. starting with “s3://”, and “gcs://”) the key-value pairs are forwarded to fsspec. Please see fsspec and urllib for more details.
New in version 1.2.0.
See also
Load pickled pandas object (or any object) from file.
Write DataFrame to an HDF5 file.
Write DataFrame to a SQL database.
Write a DataFrame to the binary parquet format.
Examples


Write records stored in a DataFrame to a SQL database.
Databases supported by SQLAlchemy [1] are supported. Tables can be newly created, appended to, or overwritten.
Name of SQL table.
Using SQLAlchemy makes it possible to use any DB supported by that library. Legacy support is provided for sqlite3.Connection objects. The user is responsible for engine disposal and connection closure for the SQLAlchemy connectable See here.
Specify the schema (if database flavor supports this). If None, use default schema.
How to behave if the table already exists.
fail: Raise a ValueError.
replace: Drop the table before inserting new values.
append: Insert new values to the existing table.
Write DataFrame index as a column. Uses index_label as the column name in the table.
Column label for index column(s). If None is given (default) and index is True, then the index names are used. A sequence should be given if the DataFrame uses MultiIndex.
Specify the number of rows in each batch to be written at a time. By default, all rows will be written at once.
Specifying the datatype for columns. If a dictionary is used, the keys should be the column names and the values should be the SQLAlchemy types or strings for the sqlite3 legacy mode. If a scalar is provided, it will be applied to all columns.
Controls the SQL insertion clause used:
None : Uses standard SQL INSERT clause (one per row).
‘multi’: Pass multiple values in a single INSERT clause.
callable with signature (pd_table, conn, keys, data_iter).
Details and a sample callable implementation can be found in the section insert method.
Number of rows affected by to_sql. None is returned if the callable passed into method does not return the number of rows.
The number of returned rows affected is the sum of the rowcount attribute of sqlite3.Cursor or SQLAlchemy connectable which may not reflect the exact number of written rows as stipulated in the sqlite3 or SQLAlchemy.
New in version 1.4.0.
When the table already exists and if_exists is ‘fail’ (the default).
See also
Read a DataFrame from a table.
Notes
Timezone aware datetime columns will be written as Timestamp with timezone type with SQLAlchemy if supported by the database. Otherwise, the datetimes will be stored as timezone unaware timestamps local to the original timezone.
References
https://docs.sqlalchemy.org
https://www.python.org/dev/peps/pep-0249/
Examples
Create an in-memory SQLite database.
Create a table from scratch with 3 rows.
An sqlalchemy.engine.Connection can also be passed to con:
This is allowed to support operations that require that the same DBAPI connection is used for the entire operation.
Overwrite the table with just df2.
Specify the dtype (especially useful for integers with missing values). Notice that while pandas is forced to store the data as floating point, the database supports nullable integers. When fetching the data with Python, we get back integer scalars.


Render a string representation of the Series.
Buffer to write to.
String representation of NaN to use, default ‘NaN’.
Formatter function to apply to columns’ elements if they are floats, default None.
Add the Series header (index name).
Add index (row) labels, default True.
Add the Series length.
Add the Series dtype.
Add the Series name if not None.
Maximum number of rows to show before truncating. If None, show all.
The number of rows to display in a truncated repr (when number of rows is above max_rows).
String representation of Series if buf=None, otherwise None.


Cast to DatetimeIndex of Timestamps, at beginning of period.
Desired frequency.
Convention for converting period to timestamp; start of period vs. end.
Whether or not to return a copy.


Return an xarray object from the pandas object.
Data in the pandas structure converted to Dataset if the object is a DataFrame, or a DataArray if the object is a Series.
See also
Write DataFrame to an HDF5 file.
Write a DataFrame to the binary parquet format.
Notes
See the xarray docs
Examples


Call func on self producing a Series with the same axis shape as self.
Function to use for transforming the data. If a function, must either work when passed a Series or when passed to Series.apply. If func is both list-like and dict-like, dict-like behavior takes precedence.
Accepted combinations are:
function
string function name
list-like of functions and/or function names, e.g. [np.exp, 'sqrt']
dict-like of axis labels -> functions, function names or list-like of such.
Parameter needed for compatibility with DataFrame.
Positional arguments to pass to func.
Keyword arguments to pass to func.
A Series that must have the same length as self.
See also
Only perform aggregating type operations.
Invoke function on a Series.
Notes
Functions that mutate the passed object can produce unexpected behavior or errors and are not supported. See Mutating with User Defined Function (UDF) methods for more details.
Examples
Even though the resulting Series must have the same length as the input Series, it is possible to provide several input functions:
You can call transform on a GroupBy object:


Return the transpose, which is by definition self.


Return Floating division of series and other, element-wise (binary operator truediv).
Equivalent to series / other, but with support to substitute a fill_value for missing data in either one of the inputs.
Fill existing missing (NaN) values, and any new element needed for successful Series alignment, with this value before computation. If data in both corresponding Series locations is missing the result of filling (at that location) will be missing.
Broadcast across a level, matching Index values on the passed MultiIndex level.
The result of the operation.
See also
Reverse of the Floating division operator, see Python documentation for more details.
Examples


Truncate a Series or DataFrame before and after some index value.
This is a useful shorthand for boolean indexing based on index values above or below certain thresholds.
Truncate all rows before this index value.
Truncate all rows after this index value.
Axis to truncate. Truncates the index (rows) by default.
Return a copy of the truncated section.
The truncated Series or DataFrame.
See also
Select a subset of a DataFrame by label.
Select a subset of a DataFrame by position.
Notes
If the index being truncated contains only datetime values, before and after may be specified as strings instead of Timestamps.
Examples
The columns of a DataFrame can be truncated.
For Series, only rows can be truncated.
The index values in truncate can be datetimes or string dates.
Because the index is a DatetimeIndex containing only dates, we can specify before and after as strings. They will be coerced to Timestamps before truncation.
Note that truncate assumes a 0 value for any unspecified time component (midnight). This differs from partial string slicing, which returns any partially matching dates.


Shift the time index, using the index’s frequency if available.
Deprecated since version 1.1.0: Use shift instead.
Number of periods to move, can be positive or negative.
Increment to use from the tseries module or time rule expressed as a string (e.g. ‘EOM’).
Corresponds to the axis that contains the Index.
Notes
If freq is not specified then tries to use the freq or inferred_freq attributes of the index. If neither of those attributes exist, a ValueError is thrown


Convert tz-aware axis to target time zone.
If axis is a MultiIndex, convert a specific level. Otherwise must be None.
Also make a copy of the underlying data.
Object with time zone converted axis.
If the axis is tz-naive.


Localize tz-naive index of a Series or DataFrame to target time zone.
This operation localizes the Index. To localize the values in a timezone-naive Series, use Series.dt.tz_localize().
If axis ia a MultiIndex, localize a specific level. Otherwise must be None.
Also make a copy of the underlying data.
When clocks moved backward due to DST, ambiguous times may arise. For example in Central European Time (UTC+01), when going from 03:00 DST to 02:00 non-DST, 02:30:00 local time occurs both at 00:30:00 UTC and at 01:30:00 UTC. In such a situation, the ambiguous parameter dictates how ambiguous times should be handled.
‘infer’ will attempt to infer fall dst-transition hours based on order
bool-ndarray where True signifies a DST time, False designates a non-DST time (note that this flag is only applicable for ambiguous times)
‘NaT’ will return NaT where there are ambiguous times
‘raise’ will raise an AmbiguousTimeError if there are ambiguous times.
A nonexistent time does not exist in a particular timezone where clocks moved forward due to DST. Valid values are:
‘shift_forward’ will shift the nonexistent time forward to the closest existing time
‘shift_backward’ will shift the nonexistent time backward to the closest existing time
‘NaT’ will return NaT where there are nonexistent times
timedelta objects will shift nonexistent times by the timedelta
‘raise’ will raise an NonExistentTimeError if there are nonexistent times.
Same type as the input.
If the TimeSeries is tz-aware and tz is not None.
Examples
Localize local times:
Be careful with DST changes. When there is sequential data, pandas can infer the DST time:
In some cases, inferring the DST is impossible. In such cases, you can pass an ndarray to the ambiguous parameter to set the DST explicitly
If the DST transition causes nonexistent times, you can shift these dates forward or backward with a timedelta object or ‘shift_forward’ or ‘shift_backward’.


Return unique values of Series object.
Uniques are returned in order of appearance. Hash table-based unique, therefore does NOT sort.
The unique values returned as a NumPy array. See Notes.
See also
Top-level unique method for any 1-d array-like object.
Return Index with unique values from an Index object.
Notes
Returns the unique values as a NumPy array. In case of an extension-array backed Series, a new ExtensionArray of that type with just the unique values is returned. This includes
Categorical
Period
Datetime with Timezone
Interval
Sparse
IntegerNA
See Examples section.
Examples
An Categorical will return categories in the order of appearance and with the same dtype.


Unstack, also known as pivot, Series with MultiIndex to produce DataFrame.
Level(s) to unstack, can pass level name.
Value to use when replacing NaN values.
Unstacked Series.
Examples


Modify Series in place using values from passed Series.
Uses non-NA values from passed Series to make updates. Aligns on index.
Examples
If other contains NaNs the corresponding values are not updated in the original Series.
other can also be a non-Series object type that is coercible into a Series


Return a Series containing counts of unique values.
The resulting object will be in descending order so that the first element is the most frequently-occurring element. Excludes NA values by default.
If True then the object returned will contain the relative frequencies of the unique values.
Sort by frequencies.
Sort in ascending order.
Rather than count values, group them into half-open bins, a convenience for pd.cut, only works with numeric data.
Don’t include counts of NaN.
See also
Number of non-NA elements in a Series.
Number of non-NA elements in a DataFrame.
Equivalent method on DataFrames.
Examples
With normalize set to True, returns the relative frequency by dividing all values by the sum of values.
bins
Bins can be useful for going from a continuous variable to a categorical variable; instead of counting unique apparitions of values, divide the index in the specified number of half-open bins.
dropna
With dropna set to False we can also see NaN index values.


Return Series as ndarray or ndarray-like depending on the dtype.
Warning
We recommend using Series.array or Series.to_numpy(), depending on whether you need a reference to the underlying data or a NumPy array.
See also
Reference to the underlying data.
A NumPy array representing the underlying data.
Examples
Timezone aware datetime data is converted to UTC:


Return unbiased variance over requested axis.
Normalized by N-1 by default. This can be changed using the ddof argument.
Exclude NA/null values. If an entire row/column is NA, the result will be NA.
If the axis is a MultiIndex (hierarchical), count along a particular level, collapsing into a scalar.
Delta Degrees of Freedom. The divisor used in calculations is N - ddof, where N represents the number of elements.
Include only float, int, boolean columns. If None, will attempt to use everything, then use only numeric data. Not implemented for Series.
Examples
Alternatively, ddof=0 can be set to normalize by N instead of N-1:


Create a new view of the Series.
This function will return a new Series with a view of the same underlying values in memory, optionally reinterpreted with a new data type. The new data type must preserve the same size in bytes as to not cause index misalignment.
Data type object or one of their string representations.
A new Series object as a view of the same data in memory.
See also
Equivalent numpy function to create a new view of the same data in memory.
Notes
Series are instantiated with dtype=float64 by default. While numpy.ndarray.view() will return a view with the same data type as the original array, Series.view() (without specified dtype) will try using float64 and may fail if the original data type size in bytes is not the same.
Examples
The 8 bit signed integer representation of -1 is 0b11111111, but the same bytes represent 255 if read as an 8 bit unsigned integer:
The views share the same underlying values:


Replace values where the condition is False.
Where cond is True, keep the original value. Where False, replace with corresponding value from other. If cond is callable, it is computed on the Series/DataFrame and should return boolean Series/DataFrame or array. The callable must not change input Series/DataFrame (though pandas doesn’t check it).
Entries where cond is False are replaced with corresponding value from other. If other is callable, it is computed on the Series/DataFrame and should return scalar or Series/DataFrame. The callable must not change input Series/DataFrame (though pandas doesn’t check it).
Whether to perform the operation in place on the data.
Alignment axis if needed.
Alignment level if needed.
Note that currently this parameter won’t affect the results and will always coerce to a suitable dtype.
‘raise’ : allow exceptions to be raised.
‘ignore’ : suppress exceptions. On error return original object.
Try to cast the result back to the input type (if possible).
Deprecated since version 1.3.0: Manually cast back if necessary.
See also
Return an object of same shape as self.
Notes
The where method is an application of the if-then idiom. For each element in the calling DataFrame, if cond is True the element is used; otherwise the corresponding element from the DataFrame other is used.
The signature for DataFrame.where() differs from numpy.where(). Roughly df1.where(m, df2) is equivalent to np.where(m, df1, df2).
For further details and examples see the where documentation in indexing.
Examples


Return cross-section from the Series/DataFrame.
This method takes a key argument to select data at a particular level of a MultiIndex.
Label contained in the index, or partially in a MultiIndex.
Axis to retrieve cross-section on.
In case of a key partially contained in a MultiIndex, indicate which levels are used. Levels can be referred by label or position.
If False, returns object with same levels as self.
Cross-section from the original Series or DataFrame corresponding to the selected index levels.
See also
Access a group of rows and columns by label(s) or a boolean array.
Purely integer-location based indexing for selection by position.
Notes
xs can not be used to set values.
MultiIndex Slicers is a generic way to get/set values on any level or levels. It is a superset of xs functionality, see MultiIndex Slicers.
Examples
Get values at specified index
Get values at several indexes
Get values at specified index and level
Get values at several indexes and levels
Get values at specified column and axis


Sets the value of the specified option.
Available options:
compute.[use_bottleneck, use_numba, use_numexpr]
display.[chop_threshold, colheader_justify, column_space, date_dayfirst, date_yearfirst, encoding, expand_frame_repr, float_format]
display.html.[border, table_schema, use_mathjax]
display.[large_repr]
display.latex.[escape, longtable, multicolumn, multicolumn_format, multirow, repr]
display.[max_categories, max_columns, max_colwidth, max_dir_items, max_info_columns, max_info_rows, max_rows, max_seq_items, memory_usage, min_rows, multi_sparse, notebook_repr_html, pprint_nest_depth, precision, show_dimensions]
display.unicode.[ambiguous_as_wide, east_asian_width]
display.[width]
io.excel.ods.[reader, writer]
io.excel.xls.[reader, writer]
io.excel.xlsb.[reader]
io.excel.xlsm.[reader, writer]
io.excel.xlsx.[reader, writer]
io.hdf.[default_format, dropna_table]
io.parquet.[engine]
io.sql.[engine]
mode.[chained_assignment, data_manager, sim_interactive, string_storage, use_inf_as_na, use_inf_as_null]
plotting.[backend]
plotting.matplotlib.[register_converters]
styler.format.[decimal, escape, formatter, na_rep, precision, thousands]
styler.html.[mathjax]
styler.latex.[environment, hrules, multicol_align, multirow_align]
styler.render.[encoding, max_columns, max_elements, max_rows, repr]
styler.sparse.[columns, index]
Regexp which should match a single option. Note: partial matches are supported for convenience, but unless you use the full option name (e.g. x.y.z.option_name), your code may break in future versions if new options with similar names are introduced.
New value of option.
Notes
The available options with its descriptions:
Use the bottleneck library to accelerate if it is installed, the default is True Valid values: False,True [default: True] [currently: True]
Use the numba engine option for select operations if it is installed, the default is False Valid values: False,True [default: False] [currently: False]
Use the numexpr library to accelerate computation if it is installed, the default is True Valid values: False,True [default: True] [currently: True]
if set to a float value, all float values smaller then the given threshold will be displayed as exactly 0 by repr and friends. [default: None] [currently: None]
Controls the justification of column headers. used by DataFrameFormatter. [default: right] [currently: right]
[default: 12] [currently: 12]
When True, prints and parses dates with the day first, eg 20/01/2005 [default: False] [currently: False]
When True, prints and parses dates with the year first, eg 2005/01/20 [default: False] [currently: False]
Defaults to the detected encoding of the console. Specifies the encoding to be used for strings returned by to_string, these are generally strings meant to be displayed on the console. [default: utf-8] [currently: utf-8]
Whether to print out the full DataFrame repr for wide DataFrames across multiple lines, max_columns is still respected, but the output will wrap-around across multiple “pages” if its width exceeds display.width. [default: True] [currently: True]
The callable should accept a floating point number and return a string with the desired format of the number. This is used in some places like SeriesFormatter. See formats.format.EngFormatter for an example. [default: None] [currently: None]
A border=value attribute is inserted in the <table> tag for the DataFrame HTML repr. [default: 1] [currently: 1]
Whether to publish a Table Schema representation for frontends that support it. (default: False) [default: False] [currently: False]
When True, Jupyter notebook will process table contents using MathJax, rendering mathematical expressions enclosed by the dollar symbol. (default: True) [default: True] [currently: True]
For DataFrames exceeding max_rows/max_cols, the repr (and HTML repr) can show a truncated table (the default from 0.13), or switch to the view from df.info() (the behaviour in earlier versions of pandas). [default: truncate] [currently: truncate]
This specifies if the to_latex method of a Dataframe uses escapes special characters. Valid values: False,True [default: True] [currently: True]
This specifies if the to_latex method of a Dataframe uses the longtable format. Valid values: False,True [default: False] [currently: False]
This specifies if the to_latex method of a Dataframe uses multicolumns to pretty-print MultiIndex columns. Valid values: False,True [default: True] [currently: True]
This specifies if the to_latex method of a Dataframe uses multicolumns to pretty-print MultiIndex columns. Valid values: False,True [default: l] [currently: l]
This specifies if the to_latex method of a Dataframe uses multirows to pretty-print MultiIndex rows. Valid values: False,True [default: False] [currently: False]
Whether to produce a latex DataFrame representation for jupyter environments that support it. (default: False) [default: False] [currently: False]
This sets the maximum number of categories pandas should output when printing out a Categorical or a Series of dtype “category”. [default: 8] [currently: 8]
If max_cols is exceeded, switch to truncate view. Depending on large_repr, objects are either centrally truncated or printed as a summary view. ‘None’ value means unlimited.
In case python/IPython is running in a terminal and large_repr equals ‘truncate’ this can be set to 0 and pandas will auto-detect the width of the terminal and print a truncated object which fits the screen width. The IPython notebook, IPython qtconsole, or IDLE do not run in a terminal and hence it is not possible to do correct auto-detection. [default: 0] [currently: 0]
The maximum width in characters of a column in the repr of a pandas data structure. When the column overflows, a “…” placeholder is embedded in the output. A ‘None’ value means unlimited. [default: 50] [currently: 50]
The number of items that will be added to dir(…). ‘None’ value means unlimited. Because dir is cached, changing this option will not immediately affect already existing dataframes until a column is deleted or added.
This is for instance used to suggest columns from a dataframe to tab completion. [default: 100] [currently: 100]
max_info_columns is used in DataFrame.info method to decide if per column information will be printed. [default: 100] [currently: 100]
df.info() will usually show null-counts for each column. For large frames this can be quite slow. max_info_rows and max_info_cols limit this null check only to frames with smaller dimensions than specified. [default: 1690785] [currently: 1690785]
If max_rows is exceeded, switch to truncate view. Depending on large_repr, objects are either centrally truncated or printed as a summary view. ‘None’ value means unlimited.
In case python/IPython is running in a terminal and large_repr equals ‘truncate’ this can be set to 0 and pandas will auto-detect the height of the terminal and print a truncated object which fits the screen height. The IPython notebook, IPython qtconsole, or IDLE do not run in a terminal and hence it is not possible to do correct auto-detection. [default: 60] [currently: 60]
When pretty-printing a long sequence, no more then max_seq_items will be printed. If items are omitted, they will be denoted by the addition of “…” to the resulting string.
If set to None, the number of items to be printed is unlimited. [default: 100] [currently: 100]
This specifies if the memory usage of a DataFrame should be displayed when df.info() is called. Valid values True,False,’deep’ [default: True] [currently: True]
The numbers of rows to show in a truncated view (when max_rows is exceeded). Ignored when max_rows is set to None or 0. When set to None, follows the value of max_rows. [default: 10] [currently: 10]
“sparsify” MultiIndex display (don’t display repeated elements in outer levels within groups) [default: True] [currently: True]
When True, IPython notebook will use html representation for pandas objects (if it is available). [default: True] [currently: True]
Controls the number of nested levels to process when pretty-printing [default: 3] [currently: 3]
Floating point output precision in terms of number of places after the decimal, for regular formatting as well as scientific notation. Similar to precision in numpy.set_printoptions(). [default: 6] [currently: 6]
Whether to print out dimensions at the end of DataFrame repr. If ‘truncate’ is specified, only print out the dimensions if the frame is truncated (e.g. not display all rows and/or columns) [default: truncate] [currently: truncate]
Whether to use the Unicode East Asian Width to calculate the display text width. Enabling this may affect to the performance (default: False) [default: False] [currently: False]
Whether to use the Unicode East Asian Width to calculate the display text width. Enabling this may affect to the performance (default: False) [default: False] [currently: False]
Width of the display in characters. In case python/IPython is running in a terminal this can be set to None and pandas will correctly auto-detect the width. Note that the IPython notebook, IPython qtconsole, or IDLE do not run in a terminal and hence it is not possible to correctly detect the width. [default: 80] [currently: 80]
The default Excel reader engine for ‘ods’ files. Available options: auto, odf. [default: auto] [currently: auto]
The default Excel writer engine for ‘ods’ files. Available options: auto, odf. [default: auto] [currently: auto]
The default Excel reader engine for ‘xls’ files. Available options: auto, xlrd. [default: auto] [currently: auto]
The default Excel writer engine for ‘xls’ files. Available options: auto, xlwt. [default: auto] [currently: auto] (Deprecated, use `` instead.)
The default Excel reader engine for ‘xlsb’ files. Available options: auto, pyxlsb. [default: auto] [currently: auto]
The default Excel reader engine for ‘xlsm’ files. Available options: auto, xlrd, openpyxl. [default: auto] [currently: auto]
The default Excel writer engine for ‘xlsm’ files. Available options: auto, openpyxl. [default: auto] [currently: auto]
The default Excel reader engine for ‘xlsx’ files. Available options: auto, xlrd, openpyxl. [default: auto] [currently: auto]
The default Excel writer engine for ‘xlsx’ files. Available options: auto, openpyxl, xlsxwriter. [default: auto] [currently: auto]
default format writing format, if None, then put will default to ‘fixed’ and append will default to ‘table’ [default: None] [currently: None]
drop ALL nan rows when appending to a table [default: False] [currently: False]
The default parquet reader/writer engine. Available options: ‘auto’, ‘pyarrow’, ‘fastparquet’, the default is ‘auto’ [default: auto] [currently: auto]
The default sql reader/writer engine. Available options: ‘auto’, ‘sqlalchemy’, the default is ‘auto’ [default: auto] [currently: auto]
Raise an exception, warn, or no action if trying to use chained assignment, The default is warn [default: warn] [currently: warn]
Internal data manager type; can be “block” or “array”. Defaults to “block”, unless overridden by the ‘PANDAS_DATA_MANAGER’ environment variable (needs to be set before pandas is imported). [default: block] [currently: block]
Whether to simulate interactive mode for purposes of testing [default: False] [currently: False]
The default storage for StringDtype. [default: python] [currently: python]
True means treat None, NaN, INF, -INF as NA (old way), False means None and NaN are null, but INF, -INF are not NA (new way). [default: False] [currently: False]
use_inf_as_null had been deprecated and will be removed in a future version. Use use_inf_as_na instead. [default: False] [currently: False] (Deprecated, use mode.use_inf_as_na instead.)
The plotting backend to use. The default value is “matplotlib”, the backend provided with pandas. Other backends can be specified by providing the name of the module that implements the backend. [default: matplotlib] [currently: matplotlib]
Whether to register converters with matplotlib’s units registry for dates, times, datetimes, and Periods. Toggling to False will remove the converters, restoring any converters that pandas overwrote. [default: auto] [currently: auto]
The character representation for the decimal separator for floats and complex. [default: .] [currently: .]
Whether to escape certain characters according to the given context; html or latex. [default: None] [currently: None]
A formatter object to be used as default within Styler.format. [default: None] [currently: None]
The string representation for values identified as missing. [default: None] [currently: None]
The precision for floats and complex numbers. [default: 6] [currently: 6]
The character representation for thousands separator for floats, int and complex. [default: None] [currently: None]
If False will render special CSS classes to table attributes that indicate Mathjax will not be used in Jupyter Notebook. [default: True] [currently: True]
The environment to replace \begin{table}. If “longtable” is used results in a specific longtable environment format. [default: None] [currently: None]
Whether to add horizontal rules on top and bottom and below the headers. [default: False] [currently: False]
The specifier for horizontal alignment of sparsified LaTeX multicolumns. Pipe decorators can also be added to non-naive values to draw vertical rules, e.g. “|r” will draw a rule on the left side of right aligned merged cells. [default: r] [currently: r]
The specifier for vertical alignment of sparsified LaTeX multirows. [default: c] [currently: c]
The encoding used for output HTML and LaTeX files. [default: utf-8] [currently: utf-8]
The maximum number of columns that will be rendered. May still be reduced to satsify max_elements, which takes precedence. [default: None] [currently: None]
The maximum number of data-cell (<td>) elements that will be rendered before trimming will occur over columns, rows or both if needed. [default: 262144] [currently: 262144]
The maximum number of rows that will be rendered. May still be reduced to satsify max_elements, which takes precedence. [default: None] [currently: None]
Determine which output to use in Jupyter Notebook in {“html”, “latex”}. [default: html] [currently: html]
Whether to sparsify the display of hierarchical columns. Setting to False will display each explicit level element in a hierarchical key for each column. [default: True] [currently: True]
Whether to sparsify the display of a hierarchical index. Setting to False will display each explicit level element in a hierarchical key for each row. [default: True] [currently: True]


Provide useful information, important for bug reports.
It comprises info about hosting operation system, pandas version, and versions of other installed relative packages.
If False, outputs info in a human readable form to the console.
If str, it will be considered as a path to a file. Info will be written to that file in JSON format.
If True, outputs info in JSON format to the console.


Dtype for data stored in SparseArray.
This dtype implements the pandas ExtensionDtype interface.
The dtype of the underlying array storing the non-fill value values.
The scalar value not stored in the SparseArray. By default, this depends on dtype.
dtype
na_value
float
np.nan
int
0
bool
False
datetime64
pd.NaT
timedelta64
pd.NaT
The default value may be overridden by specifying a fill_value.
Attributes
None
Methods
None


Extension dtype for string data.
New in version 1.0.0.
Warning
StringDtype is considered experimental. The implementation and parts of the API may change without warning.
In particular, StringDtype.na_value may change to no longer be numpy.nan.
If not given, the value of pd.options.mode.string_storage.
Examples
Attributes
None
Methods
None


Check that left and right ExtensionArrays are equal.
The two arrays to compare.
Whether to check if the ExtensionArray dtypes are identical.
Optional index (shared by both left and right), used in output.
Specify comparison precision. Only used when check_exact is False. 5 digits (False) or 3 digits (True) after decimal points are compared. If int, then specify the digits to compare.
Deprecated since version 1.1.0: Use rtol and atol instead to define relative/absolute tolerance, respectively. Similar to math.isclose().
Whether to compare number exactly.
Relative tolerance. Only used when check_exact is False.
New in version 1.1.0.
Absolute tolerance. Only used when check_exact is False.
New in version 1.1.0.
Notes
Missing values are checked separately from valid values. A mask of missing values is computed for each and checked to match. The remaining all-valid values are cast to object dtype and checked.
Examples


Check that left and right DataFrame are equal.
This function is intended to compare two DataFrames and output any differences. Is is mostly intended for use in unit tests. Additional parameters allow varying the strictness of the equality checks performed.
First DataFrame to compare.
Second DataFrame to compare.
Whether to check the DataFrame dtype is identical.
Whether to check the Index class, dtype and inferred_type are identical.
Whether to check the columns class, dtype and inferred_type are identical. Is passed as the exact argument of assert_index_equal().
Whether to check the DataFrame class is identical.
Specify comparison precision. Only used when check_exact is False. 5 digits (False) or 3 digits (True) after decimal points are compared. If int, then specify the digits to compare.
When comparing two numbers, if the first number has magnitude less than 1e-5, we compare the two numbers directly and check whether they are equivalent within the specified precision. Otherwise, we compare the ratio of the second number to the first number and check whether it is equivalent to 1 within the specified precision.
Deprecated since version 1.1.0: Use rtol and atol instead to define relative/absolute tolerance, respectively. Similar to math.isclose().
Whether to check that the names attribute for both the index and column attributes of the DataFrame is identical.
Specify how to compare internal data. If False, compare by columns. If True, compare by blocks.
Whether to compare number exactly.
Compare datetime-like which is comparable ignoring dtype.
Whether to compare internal Categorical exactly.
If True, ignore the order of index & columns. Note: index labels must match their respective rows (same as in columns) - same labels must be with the same data.
Whether to check the freq attribute on a DatetimeIndex or TimedeltaIndex.
New in version 1.1.0.
Whether to check the flags attribute.
Relative tolerance. Only used when check_exact is False.
New in version 1.1.0.
Absolute tolerance. Only used when check_exact is False.
New in version 1.1.0.
Specify object name being compared, internally used to show appropriate assertion message.
See also
Equivalent method for asserting Series equality.
Check DataFrame equality.
Examples
This example shows comparing two DataFrames that are equal but with columns of differing dtypes.
df1 equals itself.
df1 differs from df2 as column ‘b’ is of a different type.
Attribute “dtype” are different [left]: int64 [right]: float64
Ignore differing dtypes in columns with check_dtype.


Check that left and right Index are equal.
Whether to check the Index class, dtype and inferred_type are identical. If ‘equiv’, then RangeIndex can be substituted for Int64Index as well.
Whether to check the names attribute.
Specify comparison precision. Only used when check_exact is False. 5 digits (False) or 3 digits (True) after decimal points are compared. If int, then specify the digits to compare.
Deprecated since version 1.1.0: Use rtol and atol instead to define relative/absolute tolerance, respectively. Similar to math.isclose().
Whether to compare number exactly.
Whether to compare internal Categorical exactly.
Whether to compare the order of index entries as well as their values. If True, both indexes must contain the same elements, in the same order. If False, both indexes must contain the same elements, but in any order.
New in version 1.2.0.
Relative tolerance. Only used when check_exact is False.
New in version 1.1.0.
Absolute tolerance. Only used when check_exact is False.
New in version 1.1.0.
Specify object name being compared, internally used to show appropriate assertion message.
Examples


Check that left and right Series are equal.
Whether to check the Series dtype is identical.
Whether to check the Index class, dtype and inferred_type are identical.
Whether to check the Series class is identical.
Specify comparison precision. Only used when check_exact is False. 5 digits (False) or 3 digits (True) after decimal points are compared. If int, then specify the digits to compare.
When comparing two numbers, if the first number has magnitude less than 1e-5, we compare the two numbers directly and check whether they are equivalent within the specified precision. Otherwise, we compare the ratio of the second number to the first number and check whether it is equivalent to 1 within the specified precision.
Deprecated since version 1.1.0: Use rtol and atol instead to define relative/absolute tolerance, respectively. Similar to math.isclose().
Whether to check the Series and Index names attribute.
Whether to compare number exactly.
Compare datetime-like which is comparable ignoring dtype.
Whether to compare internal Categorical exactly.
Whether to compare category order of internal Categoricals.
New in version 1.0.2.
Whether to check the freq attribute on a DatetimeIndex or TimedeltaIndex.
New in version 1.1.0.
Whether to check the flags attribute.
New in version 1.2.0.
Relative tolerance. Only used when check_exact is False.
New in version 1.1.0.
Absolute tolerance. Only used when check_exact is False.
New in version 1.1.0.
Specify object name being compared, internally used to show appropriate assertion message.
Whether to check index equivalence. If False, then compare only values.
New in version 1.3.0.
Examples


Represents a duration, the difference between two dates or times.
Timedelta is the pandas equivalent of python’s datetime.timedelta and is interchangeable with it in most cases.
Denote the unit of the input, if input is an integer.
Possible values:
‘W’, ‘D’, ‘T’, ‘S’, ‘L’, ‘U’, or ‘N’
‘days’ or ‘day’
‘hours’, ‘hour’, ‘hr’, or ‘h’
‘minutes’, ‘minute’, ‘min’, or ‘m’
‘seconds’, ‘second’, or ‘sec’
‘milliseconds’, ‘millisecond’, ‘millis’, or ‘milli’
‘microseconds’, ‘microsecond’, ‘micros’, or ‘micro’
‘nanoseconds’, ‘nanosecond’, ‘nanos’, ‘nano’, or ‘ns’.
Available kwargs: {days, seconds, microseconds, milliseconds, minutes, hours, weeks}. Values for construction in compat with datetime.timedelta. Numpy ints and floats will be coerced to python ints and floats.
Notes
The constructor may take in either both values of value and unit or kwargs as above. Either one of them must be used during initialization
The .value attribute is always in ns.
If the precision is higher than nanoseconds, the precision of the duration is truncated to nanoseconds.
Examples
Here we initialize Timedelta object with both value and unit
Here we initialize the Timedelta object with kwargs
We see that either way we get the same result
Attributes
asm8
Return a numpy timedelta64 array scalar view.
components
Return a components namedtuple-like.
days
Number of days.
delta
Return the timedelta in nanoseconds (ns), for internal compatibility.
microseconds
Number of microseconds (>= 0 and less than 1 second).
nanoseconds
Return the number of nanoseconds (n), where 0 <= n < 1 microsecond.
resolution_string
Return a string representing the lowest timedelta resolution.
seconds
Number of seconds (>= 0 and less than 1 day).
freq
is_populated
value
Methods
ceil(freq)
Return a new Timedelta ceiled to this resolution.
floor(freq)
Return a new Timedelta floored to this resolution.
isoformat
Format Timedelta as ISO 8601 Duration like P[n]Y[n]M[n]DT[n]H[n]M[n]S, where the [n] s are replaced by the values.
round(freq)
Round the Timedelta to the specified resolution.
to_numpy
Convert the Timedelta to a NumPy timedelta64.
to_pytimedelta
Convert a pandas Timedelta object into a python datetime.timedelta object.
to_timedelta64
Return a numpy.timedelta64 object with 'ns' precision.
total_seconds
Total seconds in the duration.
view
Array view compatibility.


Return a numpy timedelta64 array scalar view.
Provides access to the array scalar view (i.e. a combination of the value and the units) associated with the numpy.timedelta64().view(), including a 64-bit integer representation of the timedelta in nanoseconds (Python int compatible).
Array scalar view of the timedelta in nanoseconds.
Examples


Return a new Timedelta ceiled to this resolution.
Frequency string indicating the ceiling resolution.


Return the timedelta in nanoseconds (ns), for internal compatibility.
Timedelta in nanoseconds.
Examples


Return a new Timedelta floored to this resolution.
Frequency string indicating the flooring resolution.


Format Timedelta as ISO 8601 Duration like P[n]Y[n]M[n]DT[n]H[n]M[n]S, where the [n] s are replaced by the values. See https://en.wikipedia.org/wiki/ISO_8601#Durations.
See also
Function is used to convert the given Timestamp object into the ISO format.
Notes
The longest component is days, whose value may be larger than 365. Every component is always included, even if its value is 0. Pandas uses nanosecond precision, so up to 9 decimal places may be included in the seconds component. Trailing 0’s are removed from the seconds component after the decimal. We do not 0 pad components, so it’s …T5H…, not …T05H…
Examples


Number of microseconds (>= 0 and less than 1 second).


Return the number of nanoseconds (n), where 0 <= n < 1 microsecond.
Number of nanoseconds.
See also
Return all attributes with assigned values (i.e. days, hours, minutes, seconds, milliseconds, microseconds, nanoseconds).
Examples
Using string input
Using integer input


Return a string representing the lowest timedelta resolution.
Each timedelta has a defined resolution that represents the lowest OR most granular level of precision. Each level of resolution is represented by a short string as defined below:
Resolution: Return value
Days: ‘D’
Hours: ‘H’
Minutes: ‘T’
Seconds: ‘S’
Milliseconds: ‘L’
Microseconds: ‘U’
Nanoseconds: ‘N’
Timedelta resolution.
Examples


Round the Timedelta to the specified resolution.
Frequency string indicating the rounding resolution.


Number of seconds (>= 0 and less than 1 day).


Convert the Timedelta to a NumPy timedelta64.
New in version 0.25.0.
This is an alias method for Timedelta.to_timedelta64(). The dtype and copy parameters are available here only for compatibility. Their values will not affect the return value.
See also
Similar method for Series.


Convert a pandas Timedelta object into a python datetime.timedelta object.
Timedelta objects are internally saved as numpy datetime64[ns] dtype. Use to_pytimedelta() to convert to object dtype.
See also
Convert argument to Timedelta type.
Notes
Any nanosecond resolution will be lost.


Return a numpy.timedelta64 object with ‘ns’ precision.


Return a fixed frequency TimedeltaIndex, with day as the default frequency.
Left bound for generating timedeltas.
Right bound for generating timedeltas.
Number of periods to generate.
Frequency strings can have multiples, e.g. ‘5H’.
Name of the resulting TimedeltaIndex.
Make the interval closed with respect to the given frequency to the ‘left’, ‘right’, or both sides (None).
Notes
Of the four parameters start, end, periods, and freq, exactly three must be specified. If freq is omitted, the resulting TimedeltaIndex will have periods linearly spaced elements between start and end (closed on both sides).
To learn more about the frequency strings, please see this link.
Examples
The closed parameter specifies which endpoint is included. The default behavior is to include both endpoints.
The freq parameter specifies the frequency of the TimedeltaIndex. Only fixed frequencies can be passed, non-fixed frequencies such as ‘M’ (month end) will raise.
Specify start, end, and periods; the frequency is generated automatically (linearly spaced).


Immutable ndarray of timedelta64 data, represented internally as int64, and which can be boxed to timedelta objects.
Optional timedelta-like data to construct index with.
Which is an integer/float number.
One of pandas date offset strings or corresponding objects. The string ‘infer’ can be passed in order to set the frequency of the index as the inferred frequency upon creation.
Make a copy of input ndarray.
Name to be stored in the index.
See also
The base pandas Index type.
Represents a duration between two dates or times.
Index of datetime64 data.
Index of Period data.
Create a fixed-frequency TimedeltaIndex.
Notes
To learn more about the frequency strings, please see this link.
Attributes
days
Number of days for each element.
seconds
Number of seconds (>= 0 and less than 1 day) for each element.
microseconds
Number of microseconds (>= 0 and less than 1 second) for each element.
nanoseconds
Number of nanoseconds (>= 0 and less than 1 microsecond) for each element.
components
Return a dataframe of the components (days, hours, minutes, seconds, milliseconds, microseconds, nanoseconds) of the Timedeltas.
inferred_freq
Tries to return a string representing a frequency guess, generated by infer_freq.
Methods
to_pytimedelta(*args, **kwargs)
Return Timedelta Array/Index as object ndarray of datetime.timedelta objects.
to_series([index, name])
Create a Series with both index and values equal to the index keys.
round(*args, **kwargs)
Perform round operation on the data to the specified freq.
floor(*args, **kwargs)
Perform floor operation on the data to the specified freq.
ceil(*args, **kwargs)
Perform ceil operation on the data to the specified freq.
to_frame([index, name])
Create a DataFrame with a column containing the Index.
mean(*args, **kwargs)
Return the mean value of the Array.


Perform ceil operation on the data to the specified freq.
The frequency level to ceil the index to. Must be a fixed frequency like ‘S’ (second) not ‘ME’ (month end). See frequency aliases for a list of possible freq values.
Only relevant for DatetimeIndex:
‘infer’ will attempt to infer fall dst-transition hours based on order
bool-ndarray where True signifies a DST time, False designates a non-DST time (note that this flag is only applicable for ambiguous times)
‘NaT’ will return NaT where there are ambiguous times
‘raise’ will raise an AmbiguousTimeError if there are ambiguous times.
A nonexistent time does not exist in a particular timezone where clocks moved forward due to DST.
‘shift_forward’ will shift the nonexistent time forward to the closest existing time
‘shift_backward’ will shift the nonexistent time backward to the closest existing time
‘NaT’ will return NaT where there are nonexistent times
timedelta objects will shift nonexistent times by the timedelta
‘raise’ will raise an NonExistentTimeError if there are nonexistent times.
Index of the same type for a DatetimeIndex or TimedeltaIndex, or a Series with the same index for a Series.
Notes
If the timestamps have a timezone, ceiling will take place relative to the local (“wall”) time and re-localized to the same timezone. When ceiling near daylight savings time, use nonexistent and ambiguous to control the re-localization behavior.
Examples
DatetimeIndex
Series
When rounding near a daylight savings time transition, use ambiguous or nonexistent to control how the timestamp should be re-localized.


Return a dataframe of the components (days, hours, minutes, seconds, milliseconds, microseconds, nanoseconds) of the Timedeltas.


Perform floor operation on the data to the specified freq.
The frequency level to floor the index to. Must be a fixed frequency like ‘S’ (second) not ‘ME’ (month end). See frequency aliases for a list of possible freq values.
Only relevant for DatetimeIndex:
‘infer’ will attempt to infer fall dst-transition hours based on order
bool-ndarray where True signifies a DST time, False designates a non-DST time (note that this flag is only applicable for ambiguous times)
‘NaT’ will return NaT where there are ambiguous times
‘raise’ will raise an AmbiguousTimeError if there are ambiguous times.
A nonexistent time does not exist in a particular timezone where clocks moved forward due to DST.
‘shift_forward’ will shift the nonexistent time forward to the closest existing time
‘shift_backward’ will shift the nonexistent time backward to the closest existing time
‘NaT’ will return NaT where there are nonexistent times
timedelta objects will shift nonexistent times by the timedelta
‘raise’ will raise an NonExistentTimeError if there are nonexistent times.
Index of the same type for a DatetimeIndex or TimedeltaIndex, or a Series with the same index for a Series.
Notes
If the timestamps have a timezone, flooring will take place relative to the local (“wall”) time and re-localized to the same timezone. When flooring near daylight savings time, use nonexistent and ambiguous to control the re-localization behavior.
Examples
DatetimeIndex
Series
When rounding near a daylight savings time transition, use ambiguous or nonexistent to control how the timestamp should be re-localized.


Tries to return a string representing a frequency guess, generated by infer_freq. Returns None if it can’t autodetect the frequency.


Return the mean value of the Array.
New in version 0.25.0.
Whether to ignore any NaT elements.
Timestamp or Timedelta.
See also
Returns the average of array elements along a given axis.
Return the mean value in a Series.
Notes
mean is only defined for Datetime and Timedelta dtypes, not for Period.


Number of microseconds (>= 0 and less than 1 second) for each element.


Number of nanoseconds (>= 0 and less than 1 microsecond) for each element.


Perform round operation on the data to the specified freq.
The frequency level to round the index to. Must be a fixed frequency like ‘S’ (second) not ‘ME’ (month end). See frequency aliases for a list of possible freq values.
Only relevant for DatetimeIndex:
‘infer’ will attempt to infer fall dst-transition hours based on order
bool-ndarray where True signifies a DST time, False designates a non-DST time (note that this flag is only applicable for ambiguous times)
‘NaT’ will return NaT where there are ambiguous times
‘raise’ will raise an AmbiguousTimeError if there are ambiguous times.
A nonexistent time does not exist in a particular timezone where clocks moved forward due to DST.
‘shift_forward’ will shift the nonexistent time forward to the closest existing time
‘shift_backward’ will shift the nonexistent time backward to the closest existing time
‘NaT’ will return NaT where there are nonexistent times
timedelta objects will shift nonexistent times by the timedelta
‘raise’ will raise an NonExistentTimeError if there are nonexistent times.
Index of the same type for a DatetimeIndex or TimedeltaIndex, or a Series with the same index for a Series.
Notes
If the timestamps have a timezone, rounding will take place relative to the local (“wall”) time and re-localized to the same timezone. When rounding near daylight savings time, use nonexistent and ambiguous to control the re-localization behavior.
Examples
DatetimeIndex
Series
When rounding near a daylight savings time transition, use ambiguous or nonexistent to control how the timestamp should be re-localized.


Number of seconds (>= 0 and less than 1 day) for each element.


Create a DataFrame with a column containing the Index.
Set the index of the returned DataFrame as the original Index.
The passed name should substitute for the index name (if it has one).
DataFrame containing the original Index data.
See also
Convert an Index to a Series.
Convert Series to DataFrame.
Examples
By default, the original Index is reused. To enforce a new Index:
To override the name of the resulting column, specify name:


Return Timedelta Array/Index as object ndarray of datetime.timedelta objects.


Create a Series with both index and values equal to the index keys.
Useful with map for returning an indexer based on an index.
Index of resulting Series. If None, defaults to original index.
Name of resulting Series. If None, defaults to name of original index.
The dtype will be based on the type of the Index values.
See also
Convert an Index to a DataFrame.
Convert Series to DataFrame.
Examples
By default, the original Index and original name is reused.
To enforce a new Index, specify new labels to index:
To override the name of the resulting column, specify name:


Pandas replacement for python datetime.datetime object.
Timestamp is the pandas equivalent of python’s Datetime and is interchangeable with it in most cases. It’s the type used for the entries that make up a DatetimeIndex, and other timeseries oriented data structures in pandas.
Value to be converted to Timestamp.
Offset which Timestamp will have.
Time zone for time which Timestamp will have.
Unit used for conversion if ts_input is of type int or float. The valid values are ‘D’, ‘h’, ‘m’, ‘s’, ‘ms’, ‘us’, and ‘ns’. For example, ‘s’ means seconds and ‘ms’ means milliseconds.
Due to daylight saving time, one wall clock time can occur twice when shifting from summer to winter time; fold describes whether the datetime-like corresponds to the first (0) or the second time (1) the wall clock hits the ambiguous time.
New in version 1.1.0.
Notes
There are essentially three calling conventions for the constructor. The primary form accepts four parameters. They can be passed by position or keyword.
The other two forms mimic the parameters from datetime.datetime. They can be passed by either position or keyword, but not both mixed together.
Examples
Using the primary calling convention:
This converts a datetime-like string
This converts a float representing a Unix epoch in units of seconds
This converts an int representing a Unix-epoch in units of seconds and for a particular timezone
Using the other two forms that mimic the API for datetime.datetime:
Attributes
asm8
Return numpy datetime64 format in nanoseconds.
day_of_week
Return day of the week.
day_of_year
Return the day of the year.
dayofweek
Return day of the week.
dayofyear
Return the day of the year.
days_in_month
Return the number of days in the month.
daysinmonth
Return the number of days in the month.
freqstr
Return the total number of days in the month.
is_leap_year
Return True if year is a leap year.
is_month_end
Return True if date is last day of month.
is_month_start
Return True if date is first day of month.
is_quarter_end
Return True if date is last day of the quarter.
is_quarter_start
Return True if date is first day of the quarter.
is_year_end
Return True if date is last day of the year.
is_year_start
Return True if date is first day of the year.
quarter
Return the quarter of the year.
tz
Alias for tzinfo.
week
Return the week number of the year.
weekofyear
Return the week number of the year.
day
fold
freq
hour
microsecond
minute
month
nanosecond
second
tzinfo
value
year
Methods
astimezone(tz)
Convert timezone-aware Timestamp to another time zone.
ceil(freq[, ambiguous, nonexistent])
Return a new Timestamp ceiled to this resolution.
combine(date, time)
Combine date, time into datetime with same date and time fields.
ctime
Return ctime() style string.
date
Return date object with same year, month and day.
day_name
Return the day name of the Timestamp with specified locale.
dst
Return self.tzinfo.dst(self).
floor(freq[, ambiguous, nonexistent])
Return a new Timestamp floored to this resolution.
fromisocalendar
int, int, int -> Construct a date from the ISO year, week number and weekday.
fromisoformat
string -> datetime from datetime.isoformat() output
fromordinal(ordinal[, freq, tz])
Passed an ordinal, translate and convert to a ts.
fromtimestamp(ts)
Transform timestamp[, tz] to tz's local time from POSIX timestamp.
isocalendar
Return a 3-tuple containing ISO year, week number, and weekday.
isoformat
Return the time formatted according to ISO 8610.
isoweekday()
Return the day of the week represented by the date.
month_name
Return the month name of the Timestamp with specified locale.
normalize
Normalize Timestamp to midnight, preserving tz information.
now([tz])
Return new Timestamp object representing current time local to tz.
replace([year, month, day, hour, minute, ...])
Implements datetime.replace, handles nanoseconds.
round(freq[, ambiguous, nonexistent])
Round the Timestamp to the specified resolution.
strftime(format)
Return a string representing the given POSIX timestamp controlled by an explicit format string.
strptime(string, format)
Function is not implemented.
time
Return time object with same time but with tzinfo=None.
timestamp
Return POSIX timestamp as float.
timetuple
Return time tuple, compatible with time.localtime().
timetz
Return time object with same time and tzinfo.
to_datetime64
Return a numpy.datetime64 object with 'ns' precision.
to_julian_date()
Convert TimeStamp to a Julian Date.
to_numpy
Convert the Timestamp to a NumPy datetime64.
to_period
Return an period of which this timestamp is an observation.
to_pydatetime
Convert a Timestamp object to a native Python datetime object.
today(cls[, tz])
Return the current time in the local timezone.
toordinal
Return proleptic Gregorian ordinal.
tz_convert(tz)
Convert timezone-aware Timestamp to another time zone.
tz_localize(tz[, ambiguous, nonexistent])
Convert naive Timestamp to local time zone, or remove timezone from timezone-aware Timestamp.
tzname
Return self.tzinfo.tzname(self).
utcfromtimestamp(ts)
Construct a naive UTC datetime from a POSIX timestamp.
utcnow()
Return a new Timestamp representing UTC day and time.
utcoffset
Return self.tzinfo.utcoffset(self).
utctimetuple
Return UTC time tuple, compatible with time.localtime().
weekday()
Return the day of the week represented by the date.


Return numpy datetime64 format in nanoseconds.
Examples


Convert timezone-aware Timestamp to another time zone.
Time zone for time which Timestamp will be converted to. None will remove timezone holding UTC time.
If Timestamp is tz-naive.
Examples
Create a timestamp object with UTC timezone:
Change to Tokyo timezone:
Can also use astimezone:
Analogous for pd.NaT:


Return a new Timestamp ceiled to this resolution.
Frequency string indicating the ceiling resolution.
The behavior is as follows:
bool contains flags to determine if time is dst or not (note that this flag is only applicable for ambiguous fall dst dates).
‘NaT’ will return NaT for an ambiguous time.
‘raise’ will raise an AmbiguousTimeError for an ambiguous time.
A nonexistent time does not exist in a particular timezone where clocks moved forward due to DST.
‘shift_forward’ will shift the nonexistent time forward to the closest existing time.
‘shift_backward’ will shift the nonexistent time backward to the closest existing time.
‘NaT’ will return NaT where there are nonexistent times.
timedelta objects will shift nonexistent times by the timedelta.
‘raise’ will raise an NonExistentTimeError if there are nonexistent times.
Notes
If the Timestamp has a timezone, ceiling will take place relative to the local (“wall”) time and re-localized to the same timezone. When ceiling near daylight savings time, use nonexistent and ambiguous to control the re-localization behavior.
Examples
Create a timestamp object:
A timestamp can be ceiled using multiple frequency units:
freq can also be a multiple of a single unit, like ‘5T’ (i.e. 5 minutes):
or a combination of multiple units, like ‘1H30T’ (i.e. 1 hour and 30 minutes):
Analogous for pd.NaT:
When rounding near a daylight savings time transition, use ambiguous or nonexistent to control how the timestamp should be re-localized.


Combine date, time into datetime with same date and time fields.
Examples


Return date object with same year, month and day.


Return the day name of the Timestamp with specified locale.
Locale determining the language in which to return the day name.
Examples
Analogous for pd.NaT:


Return the number of days in the month.
Examples


Return a new Timestamp floored to this resolution.
Frequency string indicating the flooring resolution.
The behavior is as follows:
bool contains flags to determine if time is dst or not (note that this flag is only applicable for ambiguous fall dst dates).
‘NaT’ will return NaT for an ambiguous time.
‘raise’ will raise an AmbiguousTimeError for an ambiguous time.
A nonexistent time does not exist in a particular timezone where clocks moved forward due to DST.
‘shift_forward’ will shift the nonexistent time forward to the closest existing time.
‘shift_backward’ will shift the nonexistent time backward to the closest existing time.
‘NaT’ will return NaT where there are nonexistent times.
timedelta objects will shift nonexistent times by the timedelta.
‘raise’ will raise an NonExistentTimeError if there are nonexistent times.
Notes
If the Timestamp has a timezone, flooring will take place relative to the local (“wall”) time and re-localized to the same timezone. When flooring near daylight savings time, use nonexistent and ambiguous to control the re-localization behavior.
Examples
Create a timestamp object:
A timestamp can be floored using multiple frequency units:
freq can also be a multiple of a single unit, like ‘5T’ (i.e. 5 minutes):
or a combination of multiple units, like ‘1H30T’ (i.e. 1 hour and 30 minutes):
Analogous for pd.NaT:
When rounding near a daylight savings time transition, use ambiguous or nonexistent to control how the timestamp should be re-localized.


Return the total number of days in the month.


int, int, int -> Construct a date from the ISO year, week number and weekday.
This is the inverse of the date.isocalendar() function


string -> datetime from datetime.isoformat() output


Passed an ordinal, translate and convert to a ts. Note: by definition there cannot be any tz info on the ordinal itself.
Date corresponding to a proleptic Gregorian ordinal.
Offset to apply to the Timestamp.
Time zone for the Timestamp.
Examples


Transform timestamp[, tz] to tz’s local time from POSIX timestamp.
Examples
Note that the output may change depending on your local time.


Return True if year is a leap year.
Examples


Return True if date is last day of month.
Examples


Return True if date is first day of month.
Examples


Return True if date is last day of the quarter.
Examples


Return True if date is first day of the quarter.
Examples


Return True if date is last day of the year.
Examples


Return True if date is first day of the year.
Examples


Return a 3-tuple containing ISO year, week number, and weekday.


Return the time formatted according to ISO 8610.
The full format looks like ‘YYYY-MM-DD HH:MM:SS.mmmmmmnnn’. By default, the fractional part is omitted if self.microsecond == 0 and self.nanosecond == 0.
If self.tzinfo is not None, the UTC offset is also attached, giving giving a full format of ‘YYYY-MM-DD HH:MM:SS.mmmmmmnnn+HH:MM’.
String used as the separator between the date and time.
Specifies the number of additional terms of the time to include. The valid values are ‘auto’, ‘hours’, ‘minutes’, ‘seconds’, ‘milliseconds’, ‘microseconds’, and ‘nanoseconds’.
Examples


Return the day of the week represented by the date. Monday == 1 … Sunday == 7.


Return the month name of the Timestamp with specified locale.
Locale determining the language in which to return the month name.
Examples
Analogous for pd.NaT:


Normalize Timestamp to midnight, preserving tz information.
Examples


Return new Timestamp object representing current time local to tz.
Timezone to localize to.
Examples
Analogous for pd.NaT:


Return the quarter of the year.
Examples


Implements datetime.replace, handles nanoseconds.
Examples
Create a timestamp object:
Replace year and the hour:
Replace timezone (not a conversion):
Analogous for pd.NaT:


Round the Timestamp to the specified resolution.
Frequency string indicating the rounding resolution.
The behavior is as follows:
bool contains flags to determine if time is dst or not (note that this flag is only applicable for ambiguous fall dst dates).
‘NaT’ will return NaT for an ambiguous time.
‘raise’ will raise an AmbiguousTimeError for an ambiguous time.
A nonexistent time does not exist in a particular timezone where clocks moved forward due to DST.
‘shift_forward’ will shift the nonexistent time forward to the closest existing time.
‘shift_backward’ will shift the nonexistent time backward to the closest existing time.
‘NaT’ will return NaT where there are nonexistent times.
timedelta objects will shift nonexistent times by the timedelta.
‘raise’ will raise an NonExistentTimeError if there are nonexistent times.
Notes
If the Timestamp has a timezone, rounding will take place relative to the local (“wall”) time and re-localized to the same timezone. When rounding near daylight savings time, use nonexistent and ambiguous to control the re-localization behavior.
Examples
Create a timestamp object:
A timestamp can be rounded using multiple frequency units:
freq can also be a multiple of a single unit, like ‘5T’ (i.e. 5 minutes):
or a combination of multiple units, like ‘1H30T’ (i.e. 1 hour and 30 minutes):
Analogous for pd.NaT:
When rounding near a daylight savings time transition, use ambiguous or nonexistent to control how the timestamp should be re-localized.


Return a string representing the given POSIX timestamp controlled by an explicit format string.
Format string to convert Timestamp to string. See strftime documentation for more information on the format string: https://docs.python.org/3/library/datetime.html#strftime-and-strptime-behavior.
Examples


Function is not implemented. Use pd.to_datetime().


Return time object with same time but with tzinfo=None.


Return POSIX timestamp as float.
Examples


Return time tuple, compatible with time.localtime().


Return time object with same time and tzinfo.


Return a numpy.datetime64 object with ‘ns’ precision.


Convert TimeStamp to a Julian Date. 0 Julian date is noon January 1, 4713 BC.
Examples


Convert the Timestamp to a NumPy datetime64.
New in version 0.25.0.
This is an alias method for Timestamp.to_datetime64(). The dtype and copy parameters are available here only for compatibility. Their values will not affect the return value.
See also
Similar method for DatetimeIndex.
Examples
Analogous for pd.NaT:


Return an period of which this timestamp is an observation.
Examples


Convert a Timestamp object to a native Python datetime object.
If warn=True, issue a warning if nanoseconds is nonzero.
Examples
Analogous for pd.NaT:


Return the current time in the local timezone. This differs from datetime.today() in that it can be localized to a passed timezone.
Timezone to localize to.
Examples
Analogous for pd.NaT:


Return proleptic Gregorian ordinal. January 1 of year 1 is day 1.


Convert timezone-aware Timestamp to another time zone.
Time zone for time which Timestamp will be converted to. None will remove timezone holding UTC time.
If Timestamp is tz-naive.
Examples
Create a timestamp object with UTC timezone:
Change to Tokyo timezone:
Can also use astimezone:
Analogous for pd.NaT:


Convert naive Timestamp to local time zone, or remove timezone from timezone-aware Timestamp.
Time zone for time which Timestamp will be converted to. None will remove timezone holding local time.
When clocks moved backward due to DST, ambiguous times may arise. For example in Central European Time (UTC+01), when going from 03:00 DST to 02:00 non-DST, 02:30:00 local time occurs both at 00:30:00 UTC and at 01:30:00 UTC. In such a situation, the ambiguous parameter dictates how ambiguous times should be handled.
The behavior is as follows:
bool contains flags to determine if time is dst or not (note that this flag is only applicable for ambiguous fall dst dates).
‘NaT’ will return NaT for an ambiguous time.
‘raise’ will raise an AmbiguousTimeError for an ambiguous time.
A nonexistent time does not exist in a particular timezone where clocks moved forward due to DST.
The behavior is as follows:
‘shift_forward’ will shift the nonexistent time forward to the closest existing time.
‘shift_backward’ will shift the nonexistent time backward to the closest existing time.
‘NaT’ will return NaT where there are nonexistent times.
timedelta objects will shift nonexistent times by the timedelta.
‘raise’ will raise an NonExistentTimeError if there are nonexistent times.
If the Timestamp is tz-aware and tz is not None.
Examples
Create a naive timestamp object:
Add ‘Europe/Stockholm’ as timezone:
Analogous for pd.NaT:


Construct a naive UTC datetime from a POSIX timestamp.
Examples


Return a new Timestamp representing UTC day and time.
Examples


Return UTC time tuple, compatible with time.localtime().


Return the week number of the year.
Examples


Return the day of the week represented by the date. Monday == 0 … Sunday == 6.


Convert argument to datetime.
This function converts a scalar, array-like, Series or DataFrame/dict-like to a pandas datetime object.
The object to convert to a datetime. If a DataFrame is provided, the method expects minimally the following columns: "year", "month", "day".
If 'raise', then invalid parsing will raise an exception.
If 'coerce', then invalid parsing will be set as NaT.
If 'ignore', then invalid parsing will return the input.
Specify a date parse order if arg is str or is list-like. If True, parses dates with the day first, e.g. "10/11/12" is parsed as 2012-11-10.
Warning
dayfirst=True is not strict, but will prefer to parse with day first. If a delimited date string cannot be parsed in accordance with the given dayfirst option, e.g. to_datetime(['31-12-2021']), then a warning will be shown.
Specify a date parse order if arg is str or is list-like.
If True parses dates with the year first, e.g. "10/11/12" is parsed as 2010-11-12.
If both dayfirst and yearfirst are True, yearfirst is preceded (same as dateutil).
Warning
yearfirst=True is not strict, but will prefer to parse with year first.
Control timezone-related parsing, localization and conversion.
If True, the function always returns a timezone-aware UTC-localized Timestamp, Series or DatetimeIndex. To do this, timezone-naive inputs are localized as UTC, while timezone-aware inputs are converted to UTC.
If False (default), inputs will not be coerced to UTC. Timezone-naive inputs will remain naive, while timezone-aware ones will keep their time offsets. Limitations exist for mixed offsets (typically, daylight savings), see Examples section for details.
See also: pandas general documentation about timezone conversion and localization.
The strftime to parse time, e.g. "%d/%m/%Y". Note that "%f" will parse all the way up to nanoseconds. See strftime documentation for more information on choices.
Control how format is used:
If True, require an exact format match.
If False, allow the format to match anywhere in the target string.
The unit of the arg (D,s,ms,us,ns) denote the unit, which is an integer or float number. This will be based off the origin. Example, with unit='ms' and origin='unix' (the default), this would calculate the number of milliseconds to the unix epoch start.
If True and no format is given, attempt to infer the format of the datetime strings based on the first non-NaN element, and if it can be inferred, switch to a faster method of parsing them. In some cases this can increase the parsing speed by ~5-10x.
Define the reference date. The numeric values would be parsed as number of units (defined by unit) since this reference date.
If 'unix' (or POSIX) time; origin is set to 1970-01-01.
If 'julian', unit must be 'D', and origin is set to beginning of Julian Calendar. Julian day number 0 is assigned to the day starting at noon on January 1, 4713 BC.
If Timestamp convertible, origin is set to Timestamp identified by origin.
If True, use a cache of unique, converted dates to apply the datetime conversion. May produce significant speed-up when parsing duplicate date strings, especially ones with timezone offsets. The cache is only used when there are at least 50 values. The presence of out-of-bounds values will render the cache unusable and may slow down parsing.
Changed in version 0.25.0: changed default value from False to True.
If parsing succeeded. Return type depends on input (types in parenthesis correspond to fallback in case of unsuccessful timezone or out-of-range timestamp parsing):
scalar: Timestamp (or datetime.datetime)
array-like: DatetimeIndex (or Series with object dtype containing datetime.datetime)
Series: Series of datetime64 dtype (or Series of object dtype containing datetime.datetime)
DataFrame: Series of datetime64 dtype (or Series of object dtype containing datetime.datetime)
When parsing a date from string fails.
When another datetime conversion error happens. For example when one of ‘year’, ‘month’, day’ columns is missing in a DataFrame, or when a Timezone-aware datetime.datetime is found in an array-like of mixed time offsets, and utc=False.
See also
Cast argument to a specified dtype.
Convert argument to timedelta.
Convert dtypes.
Notes
Many input types are supported, and lead to different output types:
scalars can be int, float, str, datetime object (from stdlib datetime module or numpy). They are converted to Timestamp when possible, otherwise they are converted to datetime.datetime. None/NaN/null scalars are converted to NaT.
array-like can contain int, float, str, datetime objects. They are converted to DatetimeIndex when possible, otherwise they are converted to Index with object dtype, containing datetime.datetime. None/NaN/null entries are converted to NaT in both cases.
Series are converted to Series with datetime64 dtype when possible, otherwise they are converted to Series with object dtype, containing datetime.datetime. None/NaN/null entries are converted to NaT in both cases.
DataFrame/dict-like are converted to Series with datetime64 dtype. For each row a datetime is created from assembling the various dataframe columns. Column keys can be common abbreviations like [‘year’, ‘month’, ‘day’, ‘minute’, ‘second’, ‘ms’, ‘us’, ‘ns’]) or plurals of the same.
The following causes are responsible for datetime.datetime objects being returned (possibly inside an Index or a Series with object dtype) instead of a proper pandas designated type (Timestamp, DatetimeIndex or Series with datetime64 dtype):
when any input element is before Timestamp.min or after Timestamp.max, see timestamp limitations.
when utc=False (default) and the input is an array-like or Series containing mixed naive/aware datetime, or aware with mixed time offsets. Note that this happens in the (quite frequent) situation when the timezone has a daylight savings policy. In that case you may wish to use utc=True.
Examples
Handling various input formats
Assembling a datetime from multiple columns of a DataFrame. The keys can be common abbreviations like [‘year’, ‘month’, ‘day’, ‘minute’, ‘second’, ‘ms’, ‘us’, ‘ns’]) or plurals of the same
Passing infer_datetime_format=True can often-times speedup a parsing if its not an ISO8601 format exactly, but in a regular format.
Using a unix epoch time
Warning
For float arg, precision rounding might happen. To prevent unexpected behavior use a fixed-width exact type.
Using a non-unix epoch origin
Non-convertible date/times
If a date does not meet the timestamp limitations, passing errors='ignore' will return the original input instead of raising any exception.
Passing errors='coerce' will force an out-of-bounds date to NaT, in addition to forcing non-dates (or non-parseable dates) to NaT.
Timezones and time offsets
The default behaviour (utc=False) is as follows:
Timezone-naive inputs are converted to timezone-naive DatetimeIndex:
Timezone-aware inputs with constant time offset are converted to timezone-aware DatetimeIndex:
However, timezone-aware inputs with mixed time offsets (for example issued from a timezone with daylight savings, such as Europe/Paris) are not successfully converted to a DatetimeIndex. Instead a simple Index containing datetime.datetime objects is returned:
A mix of timezone-aware and timezone-naive inputs is converted to a timezone-aware DatetimeIndex if the offsets of the timezone-aware are constant:
Finally, mixing timezone-aware strings and datetime.datetime always raises an error, even if the elements all have the same time offset.
Setting utc=True solves most of the above issues:
Timezone-naive inputs are localized as UTC
Timezone-aware inputs are converted to UTC (the output represents the exact same datetime, but viewed from the UTC time offset +00:00).
Inputs can contain both naive and aware, string or datetime, the above rules still apply


Convert argument to a numeric type.
The default return dtype is float64 or int64 depending on the data supplied. Use the downcast parameter to obtain other dtypes.
Please note that precision loss may occur if really large numbers are passed in. Due to the internal limitations of ndarray, if numbers smaller than -9223372036854775808 (np.iinfo(np.int64).min) or larger than 18446744073709551615 (np.iinfo(np.uint64).max) are passed in, it is very likely they will be converted to float so that they can stored in an ndarray. These warnings apply similarly to Series since it internally leverages ndarray.
Argument to be converted.
If ‘raise’, then invalid parsing will raise an exception.
If ‘coerce’, then invalid parsing will be set as NaN.
If ‘ignore’, then invalid parsing will return the input.
Can be ‘integer’, ‘signed’, ‘unsigned’, or ‘float’. If not None, and if the data has been successfully cast to a numerical dtype (or if the data was numeric to begin with), downcast that resulting data to the smallest numerical dtype possible according to the following rules:
‘integer’ or ‘signed’: smallest signed int dtype (min.: np.int8)
‘unsigned’: smallest unsigned int dtype (min.: np.uint8)
‘float’: smallest float dtype (min.: np.float32)
As this behaviour is separate from the core conversion to numeric values, any errors raised during the downcasting will be surfaced regardless of the value of the ‘errors’ input.
In addition, downcasting will only occur if the size of the resulting data’s dtype is strictly larger than the dtype it is to be cast to, so if none of the dtypes checked satisfy that specification, no downcasting will be performed on the data.
Numeric if parsing succeeded. Return type depends on input. Series if Series, otherwise ndarray.
See also
Cast argument to a specified dtype.
Convert argument to datetime.
Convert argument to timedelta.
Cast a numpy array to a specified type.
Convert dtypes.
Examples
Take separate series and convert to numeric, coercing when told to
Downcasting of nullable integer and floating dtypes is supported:


Convert argument to timedelta.
Timedeltas are absolute differences in times, expressed in difference units (e.g. days, hours, minutes, seconds). This method converts an argument from a recognized timedelta format / value into a Timedelta type.
The data to be converted to timedelta.
Deprecated since version 1.2: Strings with units ‘M’, ‘Y’ and ‘y’ do not represent unambiguous timedelta values and will be removed in a future version
Denotes the unit of the arg for numeric arg. Defaults to "ns".
Possible values:
‘W’
‘D’ / ‘days’ / ‘day’
‘hours’ / ‘hour’ / ‘hr’ / ‘h’
‘m’ / ‘minute’ / ‘min’ / ‘minutes’ / ‘T’
‘S’ / ‘seconds’ / ‘sec’ / ‘second’
‘ms’ / ‘milliseconds’ / ‘millisecond’ / ‘milli’ / ‘millis’ / ‘L’
‘us’ / ‘microseconds’ / ‘microsecond’ / ‘micro’ / ‘micros’ / ‘U’
‘ns’ / ‘nanoseconds’ / ‘nano’ / ‘nanos’ / ‘nanosecond’ / ‘N’
Changed in version 1.1.0: Must not be specified when arg context strings and errors="raise".
If ‘raise’, then invalid parsing will raise an exception.
If ‘coerce’, then invalid parsing will be set as NaT.
If ‘ignore’, then invalid parsing will return the input.
If parsing succeeded. Return type depends on input:
list-like: TimedeltaIndex of timedelta64 dtype
Series: Series of timedelta64 dtype
scalar: Timedelta
See also
Cast argument to a specified dtype.
Convert argument to datetime.
Convert dtypes.
Notes
If the precision is higher than nanoseconds, the precision of the duration is truncated to nanoseconds for string inputs.
Examples
Parsing a single string to a Timedelta:
Parsing a list or array of strings:
Converting numbers by specifying the unit keyword argument:


Return DateOffset object from string or tuple representation or datetime.timedelta object.
If freq is an invalid frequency
See also
Standard kind of date increment used for a date range.
Examples


DateOffset increments between the first business day of each Quarter.
startingMonth = 1 corresponds to dates like 1/01/2007, 4/01/2007, … startingMonth = 2 corresponds to dates like 2/01/2007, 5/01/2007, … startingMonth = 3 corresponds to dates like 3/01/2007, 6/01/2007, …
Examples
Attributes
base
Returns a copy of the calling offset object with n=1 and all other attributes equal.
freqstr
kwds
n
name
nanos
normalize
rule_code
startingMonth
Methods
__call__(*args, **kwargs)
Call self as a function.
rollback
Roll provided date backward to next offset only if not on offset.
rollforward
Roll provided date forward to next offset only if not on offset.
apply
apply_index
copy
isAnchored
is_anchored
is_month_end
is_month_start
is_on_offset
is_quarter_end
is_quarter_start
is_year_end
is_year_start
onOffset


Returns a copy of the calling offset object with n=1 and all other attributes equal.


Roll provided date backward to next offset only if not on offset.
Rolled timestamp if not on offset, otherwise unchanged timestamp.


Roll provided date forward to next offset only if not on offset.
Rolled timestamp if not on offset, otherwise unchanged timestamp.


DateOffset increments between the last business day of each Quarter.
startingMonth = 1 corresponds to dates like 1/31/2007, 4/30/2007, … startingMonth = 2 corresponds to dates like 2/28/2007, 5/31/2007, … startingMonth = 3 corresponds to dates like 3/30/2007, 6/29/2007, …
Examples
Attributes
base
Returns a copy of the calling offset object with n=1 and all other attributes equal.
freqstr
kwds
n
name
nanos
normalize
rule_code
startingMonth
Methods
__call__(*args, **kwargs)
Call self as a function.
rollback
Roll provided date backward to next offset only if not on offset.
rollforward
Roll provided date forward to next offset only if not on offset.
apply
apply_index
copy
isAnchored
is_anchored
is_month_end
is_month_start
is_on_offset
is_quarter_end
is_quarter_start
is_year_end
is_year_start
onOffset


DateOffset subclass representing possibly n business days.
Attributes
base
Returns a copy of the calling offset object with n=1 and all other attributes equal.
offset
Alias for self._offset.
calendar
freqstr
holidays
kwds
n
name
nanos
normalize
rule_code
weekmask
Methods
__call__(*args, **kwargs)
Call self as a function.
rollback
Roll provided date backward to next offset only if not on offset.
rollforward
Roll provided date forward to next offset only if not on offset.
apply
apply_index
copy
isAnchored
is_anchored
is_month_end
is_month_start
is_on_offset
is_quarter_end
is_quarter_start
is_year_end
is_year_start
onOffset


DateOffset subclass representing possibly n business hours.
The number of months represented.
Normalize start/end dates to midnight before generating date range.
Weekmask of valid business days, passed to numpy.busdaycalendar.
Start time of your custom business hour in 24h format.
End time of your custom business hour in 24h format.
Attributes
base
Returns a copy of the calling offset object with n=1 and all other attributes equal.
next_bday
Used for moving to next business day.
offset
Alias for self._offset.
calendar
end
freqstr
holidays
kwds
n
name
nanos
normalize
rule_code
start
weekmask
Methods
__call__(*args, **kwargs)
Call self as a function.
rollback(other)
Roll provided date backward to next offset only if not on offset.
rollforward(other)
Roll provided date forward to next offset only if not on offset.
apply
apply_index
copy
isAnchored
is_anchored
is_month_end
is_month_start
is_on_offset
is_quarter_end
is_quarter_start
is_year_end
is_year_start
onOffset


Roll provided date backward to next offset only if not on offset.


Roll provided date forward to next offset only if not on offset.


DateOffset of one month at the first business day.
Examples
Attributes
base
Returns a copy of the calling offset object with n=1 and all other attributes equal.
freqstr
kwds
n
name
nanos
normalize
rule_code
Methods
__call__(*args, **kwargs)
Call self as a function.
rollback
Roll provided date backward to next offset only if not on offset.
rollforward
Roll provided date forward to next offset only if not on offset.
apply
apply_index
copy
isAnchored
is_anchored
is_month_end
is_month_start
is_on_offset
is_quarter_end
is_quarter_start
is_year_end
is_year_start
onOffset


DateOffset increments between the last business day of the month.
Examples
Attributes
base
Returns a copy of the calling offset object with n=1 and all other attributes equal.
freqstr
kwds
n
name
nanos
normalize
rule_code
Methods
__call__(*args, **kwargs)
Call self as a function.
rollback
Roll provided date backward to next offset only if not on offset.
rollforward
Roll provided date forward to next offset only if not on offset.
apply
apply_index
copy
isAnchored
is_anchored
is_month_end
is_month_start
is_on_offset
is_quarter_end
is_quarter_start
is_year_end
is_year_start
onOffset


DateOffset increments between the first business day of the year.
Examples
Attributes
base
Returns a copy of the calling offset object with n=1 and all other attributes equal.
freqstr
kwds
month
n
name
nanos
normalize
rule_code
Methods
__call__(*args, **kwargs)
Call self as a function.
rollback
Roll provided date backward to next offset only if not on offset.
rollforward
Roll provided date forward to next offset only if not on offset.
apply
apply_index
copy
isAnchored
is_anchored
is_month_end
is_month_start
is_on_offset
is_quarter_end
is_quarter_start
is_year_end
is_year_start
onOffset


DateOffset increments between the last business day of the year.
Examples
Attributes
base
Returns a copy of the calling offset object with n=1 and all other attributes equal.
freqstr
kwds
month
n
name
nanos
normalize
rule_code
Methods
__call__(*args, **kwargs)
Call self as a function.
rollback
Roll provided date backward to next offset only if not on offset.
rollforward
Roll provided date forward to next offset only if not on offset.
apply
apply_index
copy
isAnchored
is_anchored
is_month_end
is_month_start
is_on_offset
is_quarter_end
is_quarter_start
is_year_end
is_year_start
onOffset


DateOffset subclass representing custom business days excluding holidays.
Normalize start/end dates to midnight before generating date range.
Weekmask of valid business days, passed to numpy.busdaycalendar.
List/array of dates to exclude from the set of valid business days, passed to numpy.busdaycalendar.
Attributes
base
Returns a copy of the calling offset object with n=1 and all other attributes equal.
offset
Alias for self._offset.
calendar
freqstr
holidays
kwds
n
name
nanos
normalize
rule_code
weekmask
Methods
__call__(*args, **kwargs)
Call self as a function.
rollback
Roll provided date backward to next offset only if not on offset.
rollforward
Roll provided date forward to next offset only if not on offset.
apply
apply_index
copy
isAnchored
is_anchored
is_month_end
is_month_start
is_on_offset
is_quarter_end
is_quarter_start
is_year_end
is_year_start
onOffset