Upload folder using huggingface_hub (part 10)
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
Files changed (50)
- .gitattributes+3
- .venv/lib/python3.12/site-packages/pandas/io/__pycache__/parquet.cpython-312.pycAdded
- .venv/lib/python3.12/site-packages/pandas/io/__pycache__/pickle.cpython-312.pycAdded
- .venv/lib/python3.12/site-packages/pandas/io/__pycache__/pytables.cpython-312.pycAdded+3
- .venv/lib/python3.12/site-packages/pandas/io/__pycache__/spss.cpython-312.pycAdded
- .venv/lib/python3.12/site-packages/pandas/io/__pycache__/sql.cpython-312.pycAdded+3
- .venv/lib/python3.12/site-packages/pandas/io/__pycache__/stata.cpython-312.pycAdded+3
- .venv/lib/python3.12/site-packages/pandas/io/__pycache__/xml.cpython-312.pycAdded
- .venv/lib/python3.12/site-packages/pandas/io/_util.pyAdded+310
- .venv/lib/python3.12/site-packages/pandas/io/api.pyAdded+65
- .venv/lib/python3.12/site-packages/pandas/io/clipboard/__init__.pyAdded+747
- .venv/lib/python3.12/site-packages/pandas/io/clipboards.pyAdded+200
- .venv/lib/python3.12/site-packages/pandas/io/common.pyAdded+1332
- .venv/lib/python3.12/site-packages/pandas/io/excel/__init__.pyAdded+19
- .venv/lib/python3.12/site-packages/pandas/io/excel/__pycache__/__init__.cpython-312.pycAdded
- .venv/lib/python3.12/site-packages/pandas/io/excel/__pycache__/_base.cpython-312.pycAdded
- .venv/lib/python3.12/site-packages/pandas/io/excel/__pycache__/_calamine.cpython-312.pycAdded
- .venv/lib/python3.12/site-packages/pandas/io/excel/__pycache__/_odfreader.cpython-312.pycAdded
- .venv/lib/python3.12/site-packages/pandas/io/excel/__pycache__/_odswriter.cpython-312.pycAdded
- .venv/lib/python3.12/site-packages/pandas/io/excel/__pycache__/_openpyxl.cpython-312.pycAdded
- .venv/lib/python3.12/site-packages/pandas/io/excel/__pycache__/_pyxlsb.cpython-312.pycAdded
- .venv/lib/python3.12/site-packages/pandas/io/excel/__pycache__/_util.cpython-312.pycAdded
- .venv/lib/python3.12/site-packages/pandas/io/excel/__pycache__/_xlrd.cpython-312.pycAdded
- .venv/lib/python3.12/site-packages/pandas/io/excel/__pycache__/_xlsxwriter.cpython-312.pycAdded
- .venv/lib/python3.12/site-packages/pandas/io/excel/_base.pyAdded+1871
- .venv/lib/python3.12/site-packages/pandas/io/excel/_calamine.pyAdded+129
- .venv/lib/python3.12/site-packages/pandas/io/excel/_odfreader.pyAdded+249
- .venv/lib/python3.12/site-packages/pandas/io/excel/_odswriter.pyAdded+362
- .venv/lib/python3.12/site-packages/pandas/io/excel/_openpyxl.pyAdded+646
- .venv/lib/python3.12/site-packages/pandas/io/excel/_pyxlsb.pyAdded+131
- .venv/lib/python3.12/site-packages/pandas/io/excel/_util.pyAdded+328
- .venv/lib/python3.12/site-packages/pandas/io/excel/_xlrd.pyAdded+147
- .venv/lib/python3.12/site-packages/pandas/io/excel/_xlsxwriter.pyAdded+288
- .venv/lib/python3.12/site-packages/pandas/io/feather_format.pyAdded+205
- .venv/lib/python3.12/site-packages/pandas/io/formats/__init__.pyAdded+9
- .venv/lib/python3.12/site-packages/pandas/io/formats/__pycache__/__init__.cpython-312.pycAdded
- .venv/lib/python3.12/site-packages/pandas/io/formats/__pycache__/console.cpython-312.pycAdded
- .venv/lib/python3.12/site-packages/pandas/io/formats/__pycache__/format.cpython-312.pycAdded
- .venv/lib/python3.12/site-packages/pandas/io/formats/__pycache__/info.cpython-312.pycAdded
- .venv/lib/python3.12/site-packages/pandas/io/formats/__pycache__/printing.cpython-312.pycAdded
- .venv/lib/python3.12/site-packages/pandas/io/formats/_color_data.pyAdded+157
- .venv/lib/python3.12/site-packages/pandas/io/formats/console.pyAdded+95
- .venv/lib/python3.12/site-packages/pandas/io/formats/css.pyAdded+425
- .venv/lib/python3.12/site-packages/pandas/io/formats/csvs.pyAdded+336
- .venv/lib/python3.12/site-packages/pandas/io/formats/excel.pyAdded+1023
- .venv/lib/python3.12/site-packages/pandas/io/formats/format.pyAdded+2080
- .venv/lib/python3.12/site-packages/pandas/io/formats/html.pyAdded+657
- .venv/lib/python3.12/site-packages/pandas/io/formats/info.pyAdded+943
- .venv/lib/python3.12/site-packages/pandas/io/formats/printing.pyAdded+587
- .venv/lib/python3.12/site-packages/pandas/io/formats/string.pyAdded+207
126 unmodified lines127128129126 unmodified lines.venv/lib/python3.12/site-packages/pandas/core/reshape/__pycache__/merge.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text.venv/lib/python3.12/site-packages/pandas/core/strings/__pycache__/accessor.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text.venv/lib/python3.12/site-packages/pandas/core/window/__pycache__/rolling.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text126 unmodified lines127128129130131132126 unmodified lines.venv/lib/python3.12/site-packages/pandas/core/reshape/__pycache__/merge.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text.venv/lib/python3.12/site-packages/pandas/core/strings/__pycache__/accessor.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text.venv/lib/python3.12/site-packages/pandas/core/window/__pycache__/rolling.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text.venv/lib/python3.12/site-packages/pandas/io/__pycache__/pytables.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text.venv/lib/python3.12/site-packages/pandas/io/__pycache__/sql.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text.venv/lib/python3.12/site-packages/pandas/io/__pycache__/stata.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
123version https://git-lfs.github.com/spec/v1oid sha256:9e8c6651055fdbbe5d1efde2dcffe969bf4b40e034522e4a37574c9deaf684dbsize 212568123version https://git-lfs.github.com/spec/v1oid sha256:4fff49fc0fe3cf9de4e3eba4eea2aafd56e632591ca6b3402ee3cc7e6f657f39size 111077123version https://git-lfs.github.com/spec/v1oid sha256:3190846969ab4b84be1302e6a8ac97d10d67f2e02342b2a0dca618f23171fde9size 168735123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310from __future__ import annotations
import datetime as dtfrom typing import ( TYPE_CHECKING, Literal, cast,)import zoneinfo
import numpy as np
from pandas._config import using_string_dtype
from pandas._libs import libfrom pandas._libs.tslibs import timezonesfrom pandas.compat import ( pa_version_under18p0, pa_version_under19p0,)from pandas.compat._optional import import_optional_dependency
from pandas.core.dtypes.common import pandas_dtype
import pandas as pd
if TYPE_CHECKING: from collections.abc import ( Callable, Hashable, Sequence, )
import pyarrow
from pandas._typing import ( DtypeArg, DtypeBackend, )
pytz = import_optional_dependency("pytz", errors="ignore")
def _arrow_dtype_mapping() -> dict: pa = import_optional_dependency("pyarrow") return { pa.int8(): pd.Int8Dtype(), pa.int16(): pd.Int16Dtype(), pa.int32(): pd.Int32Dtype(), pa.int64(): pd.Int64Dtype(), pa.uint8(): pd.UInt8Dtype(), pa.uint16(): pd.UInt16Dtype(), pa.uint32(): pd.UInt32Dtype(), pa.uint64(): pd.UInt64Dtype(), pa.bool_(): pd.BooleanDtype(), pa.string(): pd.StringDtype(), pa.float32(): pd.Float32Dtype(), pa.float64(): pd.Float64Dtype(), pa.string(): pd.StringDtype(), pa.large_string(): pd.StringDtype(), }
def _arrow_string_types_mapper() -> Callable: pa = import_optional_dependency("pyarrow")
mapping = { pa.string(): pd.StringDtype(na_value=np.nan), pa.large_string(): pd.StringDtype(na_value=np.nan), } if not pa_version_under18p0: mapping[pa.string_view()] = pd.StringDtype(na_value=np.nan)
return mapping.get
def arrow_table_to_pandas( table: pyarrow.Table, dtype_backend: DtypeBackend | Literal["numpy"] | lib.NoDefault = lib.no_default, null_to_int64: bool = False, to_pandas_kwargs: dict | None = None, dtype: DtypeArg | None = None, names: Sequence[Hashable] | None = None,) -> pd.DataFrame: pa = import_optional_dependency("pyarrow")
to_pandas_kwargs = {} if to_pandas_kwargs is None else to_pandas_kwargs
types_mapper: type[pd.ArrowDtype] | None | Callable if dtype_backend == "numpy_nullable": mapping = _arrow_dtype_mapping() if null_to_int64: # Modify the default mapping to also map null to Int64 # (to match other engines - only for CSV parser) mapping[pa.null()] = pd.Int64Dtype() types_mapper = mapping.get elif dtype_backend == "pyarrow": types_mapper = pd.ArrowDtype elif using_string_dtype(): if pa_version_under19p0: types_mapper = _arrow_string_types_mapper() elif dtype is not None: # GH#56136 Avoid lossy conversion to float64 # We'll convert to numpy below if types_mapper = { pa.int8(): pd.Int8Dtype(), pa.int16(): pd.Int16Dtype(), pa.int32(): pd.Int32Dtype(), pa.int64(): pd.Int64Dtype(), }.get else: types_mapper = None elif dtype_backend is lib.no_default or dtype_backend == "numpy": if dtype is not None: # GH#56136 Avoid lossy conversion to float64 # We'll convert to numpy below if types_mapper = { pa.int8(): pd.Int8Dtype(), pa.int16(): pd.Int16Dtype(), pa.int32(): pd.Int32Dtype(), pa.int64(): pd.Int64Dtype(), }.get else: types_mapper = None else: raise NotImplementedError
df = table.to_pandas(types_mapper=types_mapper, **to_pandas_kwargs) df = _post_convert_dtypes(df, dtype_backend, dtype, names) df = _normalize_timezone_dtypes(df) return df
def _post_convert_dtypes( df: pd.DataFrame, dtype_backend: DtypeBackend | Literal["numpy"] | lib.NoDefault, dtype: DtypeArg | None, names: Sequence[Hashable] | None,) -> pd.DataFrame: if dtype is not None and ( dtype_backend is lib.no_default or dtype_backend == "numpy" ): # GH#56136 apply any user-provided dtype, and convert any IntegerDtype # columns the user didn't explicitly ask for. if isinstance(dtype, dict): if names is not None: df.columns = names
cmp_dtypes = { pd.Int8Dtype(), pd.Int16Dtype(), pd.Int32Dtype(), pd.Int64Dtype(), } for col in df.columns: if col not in dtype and df[col].dtype in cmp_dtypes: # Any key that the user didn't explicitly specify # that got converted to IntegerDtype now gets converted # to numpy dtype. dtype[col] = df[col].dtype.numpy_dtype
# Ignore non-existent columns from dtype mapping # like other parsers do dtype = { key: pandas_dtype(dtype[key]) for key in dtype if key in df.columns }
else: dtype = pandas_dtype(dtype)
try: df = df.astype(dtype) except TypeError as err: # GH#44901 reraise to keep api consistent raise ValueError(str(err)) from err
if ( not using_string_dtype() and dtype != "str" and (dtype_backend is lib.no_default or dtype_backend == "numpy") ): # Convert any StringDtype columns back to object dtype (pyarrow always # uses string dtype even when the infer_string option is False) for i in range(len(df.columns)): new_col = _maybe_convert_string_to_object(df.iloc[:, i]) if new_col is not None: df.isetitem(i, new_col)
new_idx = _maybe_convert_string_index_to_object(df.index) if new_idx is not None: df.index = new_idx new_cols = _maybe_convert_string_index_to_object(df.columns) if new_cols is not None: df.columns = new_cols
return df
def _maybe_convert_string_to_object( data: pd.Series | pd.Index,) -> pd.Series | pd.Index | None: if isinstance(data.dtype, pd.StringDtype) and data.dtype.na_value is np.nan: return data.astype("object").fillna(None) elif isinstance(data.dtype, pd.CategoricalDtype): cat_dtype = data.dtype.categories.dtype if isinstance(cat_dtype, pd.StringDtype) and cat_dtype.na_value is np.nan: cat_dtype = pd.CategoricalDtype( categories=data.dtype.categories.astype("object"), ordered=data.dtype.ordered, ) return data.astype(cat_dtype)
# no conversion needed return None
def _maybe_convert_string_index_to_object(index: pd.Index) -> pd.Index | None: if isinstance(index, pd.MultiIndex): if any( isinstance(level.dtype, pd.StringDtype) and level.dtype.na_value is np.nan for level in index.levels ): new_levels = [] for level in index.levels: new_level = _maybe_convert_string_to_object(level) if new_level is not None: new_levels.append(new_level) else: new_levels.append(level) return index.set_levels(new_levels) return None
else: return cast("pd.Index | None", _maybe_convert_string_to_object(index))
def _normalize_pytz_timezone(tz: dt.tzinfo) -> dt.tzinfo: """ If the input tz is a pytz timezone, attempt to convert it to "default" tzinfo object (zoneinfo or datetime.timezone). """ if not type(tz).__module__.startswith("pytz"): # isinstance(col.dtype.tz, pytz.BaseTzInfo) does not included # fixed offsets return tz
if timezones.is_utc(tz): return dt.timezone.utc
if tz.zone is not None: # type: ignore[attr-defined] try: return zoneinfo.ZoneInfo(tz.zone) # type: ignore[attr-defined] except Exception: # some pytz timezones might not be available for zoneinfo pass
if timezones.is_fixed_offset(tz): # Convert pytz fixed offset to datetime.timezone try: offset = tz.utcoffset(None) if offset is not None: return dt.timezone(offset) except Exception: pass
return tz
def _normalize_timezone_index(index: pd.Index) -> pd.Index: if isinstance(index, pd.MultiIndex): if any(isinstance(level.dtype, pd.DatetimeTZDtype) for level in index.levels): levels = [_normalize_timezone_index(level) for level in index.levels] return index.set_levels(levels)
return index
if isinstance(index.dtype, pd.DatetimeTZDtype): normalized_tz = _normalize_pytz_timezone(index.dtype.tz) if normalized_tz is not index.dtype.tz: return index.tz_convert(normalized_tz) # type: ignore[attr-defined]
return index
def _normalize_timezone_dtypes(df: pd.DataFrame) -> pd.DataFrame: """ PyArrow uses pytz by default for timezones, but pandas uses zoneinfo / datetime.timezone since pandas 3.0.
TODO: Starting with pyarrow 25, it will use zoneinfo by default, and then this normalization can be skipped (https://github.com/apache/arrow/pull/49694). """ if pytz is not None: # Convert any pytz timezones to zoneinfo / fixed offset timezones if any( isinstance(dtype, pd.DatetimeTZDtype) for dtype in df._mgr.get_unique_dtypes() ): col_indices = df._select_dtypes_indices(pd.DatetimeTZDtype) for i in col_indices: col = df.iloc[:, i] normalized_tz = _normalize_pytz_timezone(col.dtype.tz) if normalized_tz is not col.dtype.tz: df.isetitem(i, col.dt.tz_convert(normalized_tz))
df.index = _normalize_timezone_index(df.index) df.columns = _normalize_timezone_index(df.columns)
return df1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465"""Data I/O API"""
from pandas.io.clipboards import read_clipboardfrom pandas.io.excel import ( ExcelFile, ExcelWriter, read_excel,)from pandas.io.feather_format import read_featherfrom pandas.io.html import read_htmlfrom pandas.io.iceberg import read_icebergfrom pandas.io.json import read_jsonfrom pandas.io.orc import read_orcfrom pandas.io.parquet import read_parquetfrom pandas.io.parsers import ( read_csv, read_fwf, read_table,)from pandas.io.pickle import ( read_pickle, to_pickle,)from pandas.io.pytables import ( HDFStore, read_hdf,)from pandas.io.sas import read_sasfrom pandas.io.spss import read_spssfrom pandas.io.sql import ( read_sql, read_sql_query, read_sql_table,)from pandas.io.stata import read_statafrom pandas.io.xml import read_xml
__all__ = [ "ExcelFile", "ExcelWriter", "HDFStore", "read_clipboard", "read_csv", "read_excel", "read_feather", "read_fwf", "read_hdf", "read_html", "read_iceberg", "read_json", "read_orc", "read_parquet", "read_pickle", "read_sas", "read_spss", "read_sql", "read_sql_query", "read_sql_table", "read_stata", "read_table", "read_xml", "to_pickle",]123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747"""Pyperclip
A cross-platform clipboard module for Python,with copy & paste functions for plain text.By Al Sweigart al@inventwithpython.comLicence at LICENSES/PYPERCLIP_LICENSE
Usage: import pyperclip pyperclip.copy('The text to be copied to the clipboard.') spam = pyperclip.paste()
if not pyperclip.is_available(): print("Copy functionality unavailable!")
On Windows, no additional modules are needed.On Mac, the pyobjc module is used, falling back to the pbcopy and pbpaste cli commands. (These commands should come with OS X.).On Linux, install xclip, xsel, or wl-clipboard (for "wayland" sessions) viapackage manager.For example, in Debian: sudo apt-get install xclip sudo apt-get install xsel sudo apt-get install wl-clipboard
Otherwise on Linux, you will need the PyQt5 modules installed.
This module does not work with PyGObject yet.
Cygwin is currently not supported.
Security Note: This module runs programs with these names: - pbcopy - pbpaste - xclip - xsel - wl-copy/wl-paste - klipper - qdbusA malicious user could rename or add programs with these names, trickingPyperclip into running them with whatever permissions the Python process has.
"""
__version__ = "1.8.2"
import contextlibimport ctypesfrom ctypes import ( c_size_t, c_wchar, c_wchar_p, get_errno, sizeof,)import osimport platformfrom shutil import which as _executable_existsimport subprocessimport timeimport warnings
from pandas.errors import ( PyperclipException, PyperclipWindowsException,)from pandas.util._exceptions import find_stack_level
# `import PyQt4` sys.exit()s if DISPLAY is not in the environment.# Thus, we need to detect the presence of $DISPLAY manually# and not load PyQt4 if it is absent.HAS_DISPLAY = os.getenv("DISPLAY")
EXCEPT_MSG = """ Pyperclip could not find a copy/paste mechanism for your system. For more information, please visit https://pyperclip.readthedocs.io/en/latest/index.html#not-implemented-error """
ENCODING = "utf-8"
class PyperclipTimeoutException(PyperclipException): pass
def _stringifyText(text) -> str: acceptedTypes = (str, int, float, bool) if not isinstance(text, acceptedTypes): raise PyperclipException( f"only str, int, float, and bool values " f"can be copied to the clipboard, not {type(text).__name__}" ) return str(text)
def init_osx_pbcopy_clipboard(): def copy_osx_pbcopy(text): text = _stringifyText(text) # Converts non-str values to str. with subprocess.Popen( ["pbcopy", "w"], stdin=subprocess.PIPE, close_fds=True ) as p: p.communicate(input=text.encode(ENCODING))
def paste_osx_pbcopy(): with subprocess.Popen( ["pbpaste", "r"], stdout=subprocess.PIPE, close_fds=True ) as p: stdout = p.communicate()[0] return stdout.decode(ENCODING)
return copy_osx_pbcopy, paste_osx_pbcopy
def init_osx_pyobjc_clipboard(): def copy_osx_pyobjc(text): """Copy string argument to clipboard""" text = _stringifyText(text) # Converts non-str values to str. newStr = Foundation.NSString.stringWithString_(text).nsstring() newData = newStr.dataUsingEncoding_(Foundation.NSUTF8StringEncoding) board = AppKit.NSPasteboard.generalPasteboard() board.declareTypes_owner_([AppKit.NSStringPboardType], None) board.setData_forType_(newData, AppKit.NSStringPboardType)
def paste_osx_pyobjc(): """Returns contents of clipboard""" board = AppKit.NSPasteboard.generalPasteboard() content = board.stringForType_(AppKit.NSStringPboardType) return content
return copy_osx_pyobjc, paste_osx_pyobjc
def init_qt_clipboard(): global QApplication # $DISPLAY should exist
# Try to import from qtpy, but if that fails try PyQt5 then PyQt4 try: from qtpy.QtWidgets import QApplication except ImportError: try: from PyQt5.QtWidgets import QApplication except ImportError: from PyQt4.QtGui import QApplication
app = QApplication.instance() if app is None: app = QApplication([])
def copy_qt(text): text = _stringifyText(text) # Converts non-str values to str. cb = app.clipboard() cb.setText(text)
def paste_qt() -> str: cb = app.clipboard() return str(cb.text())
return copy_qt, paste_qt
def init_xclip_clipboard(): DEFAULT_SELECTION = "c" PRIMARY_SELECTION = "p"
def copy_xclip(text, primary=False): text = _stringifyText(text) # Converts non-str values to str. selection = DEFAULT_SELECTION if primary: selection = PRIMARY_SELECTION with subprocess.Popen( ["xclip", "-selection", selection], stdin=subprocess.PIPE, close_fds=True ) as p: p.communicate(input=text.encode(ENCODING))
def paste_xclip(primary=False): selection = DEFAULT_SELECTION if primary: selection = PRIMARY_SELECTION with subprocess.Popen( ["xclip", "-selection", selection, "-o"], stdout=subprocess.PIPE, stderr=subprocess.PIPE, close_fds=True, ) as p: stdout = p.communicate()[0] # Intentionally ignore extraneous output on stderr when clipboard is empty return stdout.decode(ENCODING)
return copy_xclip, paste_xclip
def init_xsel_clipboard(): DEFAULT_SELECTION = "-b" PRIMARY_SELECTION = "-p"
def copy_xsel(text, primary=False): text = _stringifyText(text) # Converts non-str values to str. selection_flag = DEFAULT_SELECTION if primary: selection_flag = PRIMARY_SELECTION with subprocess.Popen( ["xsel", selection_flag, "-i"], stdin=subprocess.PIPE, close_fds=True ) as p: p.communicate(input=text.encode(ENCODING))
def paste_xsel(primary=False): selection_flag = DEFAULT_SELECTION if primary: selection_flag = PRIMARY_SELECTION with subprocess.Popen( ["xsel", selection_flag, "-o"], stdout=subprocess.PIPE, close_fds=True ) as p: stdout = p.communicate()[0] return stdout.decode(ENCODING)
return copy_xsel, paste_xsel
def init_wl_clipboard(): PRIMARY_SELECTION = "-p"
def copy_wl(text, primary=False): text = _stringifyText(text) # Converts non-str values to str. args = ["wl-copy"] if primary: args.append(PRIMARY_SELECTION) if not text: args.append("--clear") subprocess.check_call(args, close_fds=True) else: p = subprocess.Popen(args, stdin=subprocess.PIPE, close_fds=True) p.communicate(input=text.encode(ENCODING))
def paste_wl(primary=False): args = ["wl-paste", "-n"] if primary: args.append(PRIMARY_SELECTION) p = subprocess.Popen(args, stdout=subprocess.PIPE, close_fds=True) stdout, _stderr = p.communicate() return stdout.decode(ENCODING)
return copy_wl, paste_wl
def init_klipper_clipboard(): def copy_klipper(text): text = _stringifyText(text) # Converts non-str values to str. with subprocess.Popen( [ "qdbus", "org.kde.klipper", "/klipper", "setClipboardContents", text.encode(ENCODING), ], stdin=subprocess.PIPE, close_fds=True, ) as p: p.communicate(input=None)
def paste_klipper(): with subprocess.Popen( ["qdbus", "org.kde.klipper", "/klipper", "getClipboardContents"], stdout=subprocess.PIPE, close_fds=True, ) as p: stdout = p.communicate()[0]
# Workaround for https://bugs.kde.org/show_bug.cgi?id=342874 # TODO: https://github.com/asweigart/pyperclip/issues/43 clipboardContents = stdout.decode(ENCODING) # even if blank, Klipper will append a newline at the end assert len(clipboardContents) > 0 # make sure that newline is there assert clipboardContents.endswith("\n") if clipboardContents.endswith("\n"): clipboardContents = clipboardContents[:-1] return clipboardContents
return copy_klipper, paste_klipper
def init_dev_clipboard_clipboard(): def copy_dev_clipboard(text): text = _stringifyText(text) # Converts non-str values to str. if text == "": warnings.warn( "Pyperclip cannot copy a blank string to the clipboard on Cygwin. " "This is effectively a no-op.", stacklevel=find_stack_level(), ) if "\r" in text: warnings.warn( "Pyperclip cannot handle \\r characters on Cygwin.", stacklevel=find_stack_level(), )
with open("/dev/clipboard", "w", encoding="utf-8") as fd: fd.write(text)
def paste_dev_clipboard() -> str: with open("/dev/clipboard", encoding="utf-8") as fd: content = fd.read() return content
return copy_dev_clipboard, paste_dev_clipboard
def init_no_clipboard(): class ClipboardUnavailable: def __call__(self, *args, **kwargs): raise PyperclipException(EXCEPT_MSG)
def __bool__(self) -> bool: return False
return ClipboardUnavailable(), ClipboardUnavailable()
# Windows-related clipboard functions:class CheckedCall: def __init__(self, f) -> None: super().__setattr__("f", f)
def __call__(self, *args): ret = self.f(*args) if not ret and get_errno(): raise PyperclipWindowsException("Error calling " + self.f.__name__) return ret
def __setattr__(self, key, value): setattr(self.f, key, value)
def init_windows_clipboard(): global HGLOBAL, LPVOID, DWORD, LPCSTR, INT global HWND, HINSTANCE, HMENU, BOOL, UINT, HANDLE from ctypes.wintypes import ( BOOL, DWORD, HANDLE, HGLOBAL, HINSTANCE, HMENU, HWND, INT, LPCSTR, LPVOID, UINT, )
windll = ctypes.windll msvcrt = ctypes.CDLL("msvcrt")
safeCreateWindowExA = CheckedCall(windll.user32.CreateWindowExA) safeCreateWindowExA.argtypes = [ DWORD, LPCSTR, LPCSTR, DWORD, INT, INT, INT, INT, HWND, HMENU, HINSTANCE, LPVOID, ] safeCreateWindowExA.restype = HWND
safeDestroyWindow = CheckedCall(windll.user32.DestroyWindow) safeDestroyWindow.argtypes = [HWND] safeDestroyWindow.restype = BOOL
OpenClipboard = windll.user32.OpenClipboard OpenClipboard.argtypes = [HWND] OpenClipboard.restype = BOOL
safeCloseClipboard = CheckedCall(windll.user32.CloseClipboard) safeCloseClipboard.argtypes = [] safeCloseClipboard.restype = BOOL
safeEmptyClipboard = CheckedCall(windll.user32.EmptyClipboard) safeEmptyClipboard.argtypes = [] safeEmptyClipboard.restype = BOOL
safeGetClipboardData = CheckedCall(windll.user32.GetClipboardData) safeGetClipboardData.argtypes = [UINT] safeGetClipboardData.restype = HANDLE
safeSetClipboardData = CheckedCall(windll.user32.SetClipboardData) safeSetClipboardData.argtypes = [UINT, HANDLE] safeSetClipboardData.restype = HANDLE
safeGlobalAlloc = CheckedCall(windll.kernel32.GlobalAlloc) safeGlobalAlloc.argtypes = [UINT, c_size_t] safeGlobalAlloc.restype = HGLOBAL
safeGlobalLock = CheckedCall(windll.kernel32.GlobalLock) safeGlobalLock.argtypes = [HGLOBAL] safeGlobalLock.restype = LPVOID
safeGlobalUnlock = CheckedCall(windll.kernel32.GlobalUnlock) safeGlobalUnlock.argtypes = [HGLOBAL] safeGlobalUnlock.restype = BOOL
wcslen = CheckedCall(msvcrt.wcslen) wcslen.argtypes = [c_wchar_p] wcslen.restype = UINT
GMEM_MOVEABLE = 0x0002 CF_UNICODETEXT = 13
@contextlib.contextmanager def window(): """ Context that provides a valid Windows hwnd. """ # we really just need the hwnd, so setting "STATIC" # as predefined lpClass is just fine. hwnd = safeCreateWindowExA( 0, b"STATIC", None, 0, 0, 0, 0, 0, None, None, None, None ) try: yield hwnd finally: safeDestroyWindow(hwnd)
@contextlib.contextmanager def clipboard(hwnd): """ Context manager that opens the clipboard and prevents other applications from modifying the clipboard content. """ # We may not get the clipboard handle immediately because # some other application is accessing it (?) # We try for at least 500ms to get the clipboard. t = time.time() + 0.5 success = False while time.time() < t: success = OpenClipboard(hwnd) if success: break time.sleep(0.01) if not success: raise PyperclipWindowsException("Error calling OpenClipboard")
try: yield finally: safeCloseClipboard()
def copy_windows(text): # This function is heavily based on # http://msdn.com/ms649016#_win32_Copying_Information_to_the_Clipboard
text = _stringifyText(text) # Converts non-str values to str.
with window() as hwnd: # http://msdn.com/ms649048 # If an application calls OpenClipboard with hwnd set to NULL, # EmptyClipboard sets the clipboard owner to NULL; # this causes SetClipboardData to fail. # => We need a valid hwnd to copy something. with clipboard(hwnd): safeEmptyClipboard()
if text: # http://msdn.com/ms649051 # If the hMem parameter identifies a memory object, # the object must have been allocated using the # function with the GMEM_MOVEABLE flag. count = wcslen(text) + 1 handle = safeGlobalAlloc(GMEM_MOVEABLE, count * sizeof(c_wchar)) locked_handle = safeGlobalLock(handle)
ctypes.memmove( c_wchar_p(locked_handle), c_wchar_p(text), count * sizeof(c_wchar), )
safeGlobalUnlock(handle) safeSetClipboardData(CF_UNICODETEXT, handle)
def paste_windows(): with clipboard(None): handle = safeGetClipboardData(CF_UNICODETEXT) if not handle: # GetClipboardData may return NULL with errno == NO_ERROR # if the clipboard is empty. # (Also, it may return a handle to an empty buffer, # but technically that's not empty) return "" return c_wchar_p(handle).value
return copy_windows, paste_windows
def init_wsl_clipboard(): def copy_wsl(text): text = _stringifyText(text) # Converts non-str values to str. with subprocess.Popen(["clip.exe"], stdin=subprocess.PIPE, close_fds=True) as p: p.communicate(input=text.encode(ENCODING))
def paste_wsl(): with subprocess.Popen( ["powershell.exe", "-command", "Get-Clipboard"], stdout=subprocess.PIPE, stderr=subprocess.PIPE, close_fds=True, ) as p: stdout = p.communicate()[0] # WSL appends "\r\n" to the contents. return stdout[:-2].decode(ENCODING)
return copy_wsl, paste_wsl
# Automatic detection of clipboard mechanisms# and importing is done in determine_clipboard():def determine_clipboard(): """ Determine the OS/platform and set the copy() and paste() functions accordingly. """ global Foundation, AppKit, qtpy, PyQt4, PyQt5
# Setup for the CYGWIN platform: if ( "cygwin" in platform.system().lower() ): # Cygwin has a variety of values returned by platform.system(), # such as 'CYGWIN_NT-6.1' # FIXME(pyperclip#55): pyperclip currently does not support Cygwin, # see https://github.com/asweigart/pyperclip/issues/55 if os.path.exists("/dev/clipboard"): warnings.warn( "Pyperclip's support for Cygwin is not perfect, " "see https://github.com/asweigart/pyperclip/issues/55", stacklevel=find_stack_level(), ) return init_dev_clipboard_clipboard()
# Setup for the WINDOWS platform: elif os.name == "nt" or platform.system() == "Windows": return init_windows_clipboard()
if platform.system() == "Linux": if _executable_exists("wslconfig.exe"): return init_wsl_clipboard()
# Setup for the macOS platform: if os.name == "mac" or platform.system() == "Darwin": try: import AppKit import Foundation # check if pyobjc is installed except ImportError: return init_osx_pbcopy_clipboard() else: return init_osx_pyobjc_clipboard()
# Setup for the LINUX platform: if HAS_DISPLAY: if os.environ.get("WAYLAND_DISPLAY") and _executable_exists("wl-copy"): return init_wl_clipboard() if _executable_exists("xsel"): return init_xsel_clipboard() if _executable_exists("xclip"): return init_xclip_clipboard() if _executable_exists("klipper") and _executable_exists("qdbus"): return init_klipper_clipboard()
try: # qtpy is a small abstraction layer that lets you write applications # using a single api call to either PyQt or PySide. # https://pypi.python.org/project/QtPy import qtpy # check if qtpy is installed except ImportError: # If qtpy isn't installed, fall back on importing PyQt4. try: import PyQt5 # check if PyQt5 is installed except ImportError: try: import PyQt4 # check if PyQt4 is installed except ImportError: pass # We want to fail fast for all non-ImportError exceptions. else: return init_qt_clipboard() else: return init_qt_clipboard() else: return init_qt_clipboard()
return init_no_clipboard()
def set_clipboard(clipboard): """ Explicitly sets the clipboard mechanism. The "clipboard mechanism" is how the copy() and paste() functions interact with the operating system to implement the copy/paste feature. The clipboard parameter must be one of: - pbcopy - pyobjc (default on macOS) - qt - xclip - xsel - klipper - windows (default on Windows) - no (this is what is set when no clipboard mechanism can be found) """ global copy, paste
clipboard_types = { "pbcopy": init_osx_pbcopy_clipboard, "pyobjc": init_osx_pyobjc_clipboard, "qt": init_qt_clipboard, # TODO - split this into 'qtpy', 'pyqt4', and 'pyqt5' "xclip": init_xclip_clipboard, "xsel": init_xsel_clipboard, "wl-clipboard": init_wl_clipboard, "klipper": init_klipper_clipboard, "windows": init_windows_clipboard, "no": init_no_clipboard, }
if clipboard not in clipboard_types: allowed_clipboard_types = [repr(_) for _ in clipboard_types] raise ValueError( f"Argument must be one of {', '.join(allowed_clipboard_types)}" )
# Sets pyperclip's copy() and paste() functions: copy, paste = clipboard_types[clipboard]()
def lazy_load_stub_copy(text): """ A stub function for copy(), which will load the real copy() function when called so that the real copy() function is used for later calls.
This allows users to import pyperclip without having determine_clipboard() automatically run, which will automatically select a clipboard mechanism. This could be a problem if it selects, say, the memory-heavy PyQt4 module but the user was just going to immediately call set_clipboard() to use a different clipboard mechanism.
The lazy loading this stub function implements gives the user a chance to call set_clipboard() to pick another clipboard mechanism. Or, if the user simply calls copy() or paste() without calling set_clipboard() first, will fall back on whatever clipboard mechanism that determine_clipboard() automatically chooses. """ global copy, paste copy, paste = determine_clipboard() return copy(text)
def lazy_load_stub_paste(): """ A stub function for paste(), which will load the real paste() function when called so that the real paste() function is used for later calls.
This allows users to import pyperclip without having determine_clipboard() automatically run, which will automatically select a clipboard mechanism. This could be a problem if it selects, say, the memory-heavy PyQt4 module but the user was just going to immediately call set_clipboard() to use a different clipboard mechanism.
The lazy loading this stub function implements gives the user a chance to call set_clipboard() to pick another clipboard mechanism. Or, if the user simply calls copy() or paste() without calling set_clipboard() first, will fall back on whatever clipboard mechanism that determine_clipboard() automatically chooses. """ global copy, paste copy, paste = determine_clipboard() return paste()
def is_available() -> bool: return copy != lazy_load_stub_copy and paste != lazy_load_stub_paste
# Initially, copy() and paste() are set to lazy loading wrappers which will# set `copy` and `paste` to real functions the first time they're used, unless# set_clipboard() or determine_clipboard() is called first.copy, paste = lazy_load_stub_copy, lazy_load_stub_paste
def waitForPaste(timeout=None): """This function call blocks until a non-empty text string exists on the clipboard. It returns this text.
This function raises PyperclipTimeoutException if timeout was set to a number of seconds that has elapsed without non-empty text being put on the clipboard.""" startTime = time.time() while True: clipboardText = paste() if clipboardText != "": return clipboardText time.sleep(0.01)
if timeout is not None and time.time() > startTime + timeout: raise PyperclipTimeoutException( "waitForPaste() timed out after " + str(timeout) + " seconds." )
def waitForNewPaste(timeout=None): """This function call blocks until a new text string exists on the clipboard that is different from the text that was there when the function was first called. It returns this text.
This function raises PyperclipTimeoutException if timeout was set to a number of seconds that has elapsed without non-empty text being put on the clipboard.""" startTime = time.time() originalText = paste() while True: currentText = paste() if currentText != originalText: return currentText time.sleep(0.01)
if timeout is not None and time.time() > startTime + timeout: raise PyperclipTimeoutException( "waitForNewPaste() timed out after " + str(timeout) + " seconds." )
__all__ = [ "copy", "paste", "waitForPaste", "waitForNewPaste", "set_clipboard", "determine_clipboard",]
# pandas aliasesclipboard_get = pasteclipboard_set = copy123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200"""io on the clipboard"""
from __future__ import annotations
from io import StringIOfrom typing import TYPE_CHECKINGimport warnings
from pandas._libs import libfrom pandas.util._decorators import set_modulefrom pandas.util._exceptions import find_stack_levelfrom pandas.util._validators import check_dtype_backend
from pandas.core.dtypes.generic import ABCDataFrame
from pandas import ( get_option, option_context,)
if TYPE_CHECKING: from pandas._typing import DtypeBackend
@set_module("pandas")def read_clipboard( sep: str = r"\s+", dtype_backend: DtypeBackend | lib.NoDefault = lib.no_default, **kwargs,): # pragma: no cover r""" Read text from clipboard and pass to :func:`~pandas.read_csv`.
Parses clipboard contents similar to how CSV files are parsed using :func:`~pandas.read_csv`.
Parameters ---------- sep : str, default '\\s+' A string or regex delimiter. The default of ``'\\s+'`` denotes one or more whitespace characters.
dtype_backend : {'numpy_nullable', 'pyarrow'} Back-end data type applied to the resultant :class:`DataFrame` (still experimental). If not specified, the default behavior is to not use nullable data types. If specified, the behavior is as follows:
* ``"numpy_nullable"``: returns nullable-dtype-backed :class:`DataFrame` * ``"pyarrow"``: returns pyarrow-backed nullable :class:`ArrowDtype` :class:`DataFrame`
.. versionadded:: 2.0
**kwargs See :func:`~pandas.read_csv` for the full argument list.
Returns ------- DataFrame A parsed :class:`~pandas.DataFrame` object.
See Also -------- DataFrame.to_clipboard : Copy object to the system clipboard. read_csv : Read a comma-separated values (csv) file into DataFrame. read_fwf : Read a table of fixed-width formatted lines into DataFrame.
Examples -------- >>> df = pd.DataFrame([[1, 2, 3], [4, 5, 6]], columns=["A", "B", "C"]) >>> df.to_clipboard() # doctest: +SKIP >>> pd.read_clipboard() # doctest: +SKIP A B C 0 1 2 3 1 4 5 6 """ encoding = kwargs.pop("encoding", "utf-8")
# only utf-8 is valid for passed value because that's what clipboard # supports if encoding is not None and encoding.lower().replace("-", "") != "utf8": raise NotImplementedError("reading from clipboard only supports utf-8 encoding")
check_dtype_backend(dtype_backend)
from pandas.io.clipboard import clipboard_get from pandas.io.parsers import read_csv
text = clipboard_get()
# Try to decode (if needed, as "text" might already be a string here). try: text = text.decode(kwargs.get("encoding") or get_option("display.encoding")) except AttributeError: pass
# Excel copies into clipboard with \t separation # inspect no more then the 10 first lines, if they # all contain an equal number (>0) of tabs, infer # that this came from excel and set 'sep' accordingly lines = text[:10000].split("\n")[:-1][:10]
# Need to remove leading white space, since read_csv # accepts: # a b # 0 1 2 # 1 3 4
counts = {x.lstrip(" ").count("\t") for x in lines} if len(lines) > 1 and len(counts) == 1 and counts.pop() != 0: sep = "\t" # check the number of leading tabs in the first line # to account for index columns index_length = len(lines[0]) - len(lines[0].lstrip(" \t")) if index_length != 0: kwargs.setdefault("index_col", list(range(index_length)))
elif not isinstance(sep, str): raise ValueError(f"{sep=} must be a string")
# Regex separator currently only works with python engine. # Default to python if separator is multi-character (regex) if len(sep) > 1 and kwargs.get("engine") is None: kwargs["engine"] = "python" elif len(sep) > 1 and kwargs.get("engine") == "c": warnings.warn( "read_clipboard with regex separator does not work properly with c engine.", stacklevel=find_stack_level(), )
return read_csv(StringIO(text), sep=sep, dtype_backend=dtype_backend, **kwargs)
def to_clipboard( obj, excel: bool | None = True, sep: str | None = None, **kwargs) -> None: # pragma: no cover """ Attempt to write text representation of object to the system clipboard The clipboard can be then pasted into Excel for example.
Parameters ---------- obj : the object to write to the clipboard excel : bool, defaults to True if True, use the provided separator, writing in a csv format for allowing easy pasting into excel. if False, write a string representation of the object to the clipboard sep : optional, defaults to tab other keywords are passed to to_csv
Notes ----- Requirements for your platform - Linux: xclip, or xsel (with PyQt4 modules) - Windows: - OS X: """ encoding = kwargs.pop("encoding", "utf-8")
# testing if an invalid encoding is passed to clipboard if encoding is not None and encoding.lower().replace("-", "") != "utf8": raise ValueError("clipboard only supports utf-8 encoding")
from pandas.io.clipboard import clipboard_set
if excel is None: excel = True
if excel: try: if sep is None: sep = "\t" buf = StringIO()
# clipboard_set (pyperclip) expects unicode obj.to_csv(buf, sep=sep, encoding="utf-8", **kwargs) text = buf.getvalue()
clipboard_set(text) return except TypeError: warnings.warn( "to_clipboard in excel mode requires a single character separator.", stacklevel=find_stack_level(), ) elif sep is not None: warnings.warn( "to_clipboard with excel=False ignores the sep argument.", stacklevel=find_stack_level(), )
if isinstance(obj, ABCDataFrame): # str(df) has various unhelpful defaults, like truncation with option_context("display.max_colwidth", None): objstr = obj.to_string(**kwargs) else: objstr = str(obj) clipboard_set(objstr)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332"""Common I/O API utilities"""
from __future__ import annotations
from abc import ( ABC, abstractmethod,)import codecsfrom collections import defaultdictfrom collections.abc import ( Hashable, Mapping, Sequence,)import dataclassesimport functoolsimport gzipfrom io import ( BufferedIOBase, BytesIO, RawIOBase, StringIO, TextIOBase, TextIOWrapper,)import mmapimport osfrom pathlib import Pathimport reimport tarfilefrom typing import ( IO, TYPE_CHECKING, Any, AnyStr, DefaultDict, Generic, Literal, TypeVar, cast, overload,)from urllib.parse import ( urljoin, urlparse as parse_url, uses_netloc, uses_params, uses_relative,)import warningsimport zipfile
from pandas._typing import ( BaseBuffer, ReadCsvBuffer,)from pandas.compat._optional import import_optional_dependencyfrom pandas.util._exceptions import find_stack_level
from pandas.core.dtypes.common import ( is_bool, is_file_like, is_integer, is_list_like,)from pandas.core.dtypes.generic import ABCMultiIndex
_VALID_URLS = set(uses_relative + uses_netloc + uses_params)_VALID_URLS.discard("")_FSSPEC_URL_PATTERN = re.compile(r"^[A-Za-z][A-Za-z0-9+\-+.]*(::[A-Za-z0-9+\-+.]+)*://")
BaseBufferT = TypeVar("BaseBufferT", bound=BaseBuffer)
if TYPE_CHECKING: from types import TracebackType
from pandas._typing import ( CompressionDict, CompressionOptions, FilePath, ReadBuffer, StorageOptions, WriteBuffer, )
from pandas import MultiIndex
@dataclasses.dataclassclass IOArgs: """ Return value of io/common.py:_get_filepath_or_buffer. """
filepath_or_buffer: str | BaseBuffer encoding: str mode: str compression: CompressionDict should_close: bool = False close_handles: list[Any] = dataclasses.field(default_factory=list)
@dataclasses.dataclassclass IOHandles(Generic[AnyStr]): """ Return value of io/common.py:get_handle
Can be used as a context manager.
This is used to easily close created buffers and to handle corner cases when TextIOWrapper is inserted.
handle: The file handle to be used. created_handles: All file handles that are created by get_handle is_wrapped: Whether a TextIOWrapper needs to be detached. """
# handle might not implement the IO-interface handle: IO[AnyStr] compression: CompressionDict created_handles: list[IO[bytes] | IO[str]] = dataclasses.field(default_factory=list) is_wrapped: bool = False
def close(self) -> None: """ Close all created buffers.
Note: If a TextIOWrapper was inserted, it is flushed and detached to avoid closing the potentially user-created buffer. """ if self.is_wrapped: assert isinstance(self.handle, TextIOWrapper) self.handle.flush() self.handle.detach() self.created_handles.remove(self.handle) for handle in self.created_handles: handle.close() self.created_handles = [] self.is_wrapped = False
def __enter__(self) -> IOHandles[AnyStr]: return self
def __exit__( self, exc_type: type[BaseException] | None, exc_value: BaseException | None, traceback: TracebackType | None, ) -> None: self.close()
def is_url(url: object) -> bool: """ Check to see if a URL has a valid protocol.
Parameters ---------- url : str or unicode
Returns ------- isurl : bool If `url` has a valid protocol return True otherwise False. """ if not isinstance(url, str): return False return parse_url(url).scheme in _VALID_URLS
@overloaddef _expand_user(filepath_or_buffer: str) -> str: ...
@overloaddef _expand_user(filepath_or_buffer: BaseBufferT) -> BaseBufferT: ...
def _expand_user(filepath_or_buffer: str | BaseBufferT) -> str | BaseBufferT: """ Return the argument with an initial component of ~ or ~user replaced by that user's home directory.
Parameters ---------- filepath_or_buffer : object to be converted if possible
Returns ------- expanded_filepath_or_buffer : an expanded filepath or the input if not expandable """ if isinstance(filepath_or_buffer, str): return os.path.expanduser(filepath_or_buffer) return filepath_or_buffer
def validate_header_arg(header: object) -> None: if header is None: return if is_integer(header): header = cast(int, header) if header < 0: # GH 27779 raise ValueError( "Passing negative integer to header is invalid. " "For no header, use header=None instead" ) return if is_list_like(header, allow_sets=False): header = cast(Sequence, header) if not all(map(is_integer, header)): raise ValueError("header must be integer or list of integers") if any(i < 0 for i in header): raise ValueError("cannot specify multi-index header with negative integers") return if is_bool(header): raise TypeError( "Passing a bool to header is invalid. Use header=None for no header or " "header=int or list-like of ints to specify " "the row(s) making up the column names" ) # GH 16338 raise ValueError("header must be integer or list of integers")
@overloaddef stringify_path( filepath_or_buffer: FilePath, convert_file_like: bool = ...) -> str: ...
@overloaddef stringify_path( filepath_or_buffer: BaseBufferT, convert_file_like: bool = ...) -> BaseBufferT: ...
def stringify_path( filepath_or_buffer: FilePath | BaseBufferT, convert_file_like: bool = False,) -> str | BaseBufferT: """ Attempt to convert a path-like object to a string.
Parameters ---------- filepath_or_buffer : object to be converted
Returns ------- str_filepath_or_buffer : maybe a string version of the object
Notes ----- Objects supporting the fspath protocol are coerced according to its __fspath__ method.
Any other object is passed through unchanged, which includes bytes, strings, buffers, or anything else that's not even path-like. """ if not convert_file_like and is_file_like(filepath_or_buffer): # GH 38125: some fsspec objects implement os.PathLike but have already opened a # file. This prevents opening the file a second time. infer_compression calls # this function with convert_file_like=True to infer the compression. return cast(BaseBufferT, filepath_or_buffer)
if isinstance(filepath_or_buffer, os.PathLike): filepath_or_buffer = filepath_or_buffer.__fspath__() return _expand_user(filepath_or_buffer)
def urlopen(*args: Any, **kwargs: Any) -> Any: """ Lazy-import wrapper for stdlib urlopen, as that imports a big chunk of the stdlib. """ import urllib.request
return urllib.request.urlopen(*args, **kwargs) # noqa: TID251
def is_fsspec_url(url: FilePath | BaseBuffer) -> bool: """ Returns true if the given URL looks like something fsspec can handle """ return ( isinstance(url, str) and bool(_FSSPEC_URL_PATTERN.match(url)) and not url.startswith(("http://", "https://")) )
def _get_filepath_or_buffer( filepath_or_buffer: FilePath | BaseBuffer, encoding: str = "utf-8", compression: CompressionOptions | None = None, mode: str = "r", storage_options: StorageOptions | None = None,) -> IOArgs: """ If the filepath_or_buffer is a url, translate and return the buffer. Otherwise passthrough.
Parameters ---------- filepath_or_buffer : a url, filepath (str or pathlib.Path), or buffer
compression : str or dict, default 'infer' For on-the-fly compression of the output data. If 'infer' and 'filepath_or_buffer' is path-like, then detect compression from the following extensions: '.gz', '.bz2', '.zip', '.xz', '.zst', '.tar', '.tar.gz', '.tar.xz' or '.tar.bz2' (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'``, ``'xz'``, ``'tar'``} and other key-value pairs are forwarded to ``zipfile.ZipFile``, ``gzip.GzipFile``, ``bz2.BZ2File``, ``zstandard.ZstdCompressor``, ``lzma.LZMAFile`` or ``tarfile.TarFile``, 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}``.
encoding : the encoding to use to decode bytes, default is 'utf-8' mode : str, optional
storage_options : dict, optional 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.request.Request`` as header options. For other URLs (e.g. starting with "s3://", and "gcs://") the key-value pairs are forwarded to ``fsspec.open``. Please see ``fsspec`` and ``urllib`` for more details, and for more examples on storage options refer `here <https://pandas.pydata.org/docs/user_guide/io.html? highlight=storage_options#reading-writing-remote-files>`_.
Returns the dataclass IOArgs. """ filepath_or_buffer = stringify_path(filepath_or_buffer)
# handle compression dict compression_method, compression = get_compression_method(compression) compression_method = infer_compression(filepath_or_buffer, compression_method)
# GH21227 internal compression is not used for non-binary handles. if compression_method and hasattr(filepath_or_buffer, "write") and "b" not in mode: warnings.warn( "compression has no effect when passing a non-binary object as input.", RuntimeWarning, stacklevel=find_stack_level(), ) compression_method = None
compression = dict(compression, method=compression_method)
# bz2 and xz do not write the byte order mark for utf-16 and utf-32 # print a warning when writing such files if ( "w" in mode and compression_method in ["bz2", "xz"] and encoding in ["utf-16", "utf-32"] ): warnings.warn( f"{compression} will not write the byte order mark for {encoding}", UnicodeWarning, stacklevel=find_stack_level(), )
if "a" in mode and compression_method in ["zip", "tar"]: # GH56778 warnings.warn( "zip and tar do not support mode 'a' properly. " "This combination will result in multiple files with same name " "being added to the archive.", RuntimeWarning, stacklevel=find_stack_level(), )
# Use binary mode when converting path-like objects to file-like objects (fsspec) # except when text mode is explicitly requested. The original mode is returned if # fsspec is not used. fsspec_mode = mode if "t" not in fsspec_mode and "b" not in fsspec_mode: fsspec_mode += "b"
if isinstance(filepath_or_buffer, str) and is_url(filepath_or_buffer): # TODO: fsspec can also handle HTTP via requests, but leaving this # unchanged. using fsspec appears to break the ability to infer if the # server responded with gzipped data storage_options = storage_options or {}
# waiting until now for importing to match intended lazy logic of # urlopen function defined elsewhere in this module import urllib.request
# assuming storage_options is to be interpreted as headers req_info = urllib.request.Request(filepath_or_buffer, headers=storage_options) with urlopen(req_info) as req: content_encoding = req.headers.get("Content-Encoding", None) if content_encoding == "gzip": # Override compression based on Content-Encoding header compression = {"method": "gzip"} reader = BytesIO(req.read()) return IOArgs( filepath_or_buffer=reader, encoding=encoding, compression=compression, should_close=True, mode=fsspec_mode, )
if is_fsspec_url(filepath_or_buffer): assert isinstance( filepath_or_buffer, str ) # just to appease mypy for this branch # two special-case s3-like protocols; these have special meaning in Hadoop, # but are equivalent to just "s3" from fsspec's point of view # cc #11071 if filepath_or_buffer.startswith("s3a://"): filepath_or_buffer = filepath_or_buffer.replace("s3a://", "s3://") if filepath_or_buffer.startswith("s3n://"): filepath_or_buffer = filepath_or_buffer.replace("s3n://", "s3://") fsspec = import_optional_dependency("fsspec")
# If botocore is installed we fallback to reading with anon=True # to allow reads from public buckets err_types_to_retry_with_anon: list[Any] = [] try: import_optional_dependency("botocore") from botocore.exceptions import ( ClientError, NoCredentialsError, )
err_types_to_retry_with_anon = [ ClientError, NoCredentialsError, PermissionError, ] except ImportError: pass
try: open_file = fsspec.open( filepath_or_buffer, mode=fsspec_mode, **(storage_options or {}) ) file_obj = open_file.open() # GH 34626 Reads from Public Buckets without Credentials needs anon=True except tuple(err_types_to_retry_with_anon): if storage_options is None: storage_options = {"anon": True} else: # don't mutate user input. storage_options = dict(storage_options) storage_options["anon"] = True open_file = fsspec.open( filepath_or_buffer, mode=fsspec_mode, **(storage_options or {}) ) file_obj = open_file.open()
return IOArgs( filepath_or_buffer=file_obj, encoding=encoding, compression=compression, close_handles=[open_file], should_close=True, mode=fsspec_mode, ) elif storage_options: raise ValueError( "storage_options passed with file object or non-fsspec file path" )
if isinstance(filepath_or_buffer, (str, bytes, mmap.mmap)): return IOArgs( filepath_or_buffer=_expand_user(filepath_or_buffer), encoding=encoding, compression=compression, should_close=False, mode=mode, )
# is_file_like requires (read | write) & __iter__ but __iter__ is only # needed for read_csv(engine=python) if not ( hasattr(filepath_or_buffer, "read") or hasattr(filepath_or_buffer, "write") ): msg = f"Invalid file path or buffer object type: {type(filepath_or_buffer)}" raise ValueError(msg)
return IOArgs( filepath_or_buffer=filepath_or_buffer, encoding=encoding, compression=compression, should_close=False, mode=mode, )
def file_path_to_url(path: str) -> str: """ converts an absolute native path to a FILE URL.
Parameters ---------- path : a path in native format
Returns ------- a valid FILE URL """ # lazify expensive import (~30ms) from urllib.request import pathname2url
return urljoin("file:", pathname2url(path))
extension_to_compression = { ".tar": "tar", ".tar.gz": "tar", ".tar.bz2": "tar", ".tar.xz": "tar", ".gz": "gzip", ".bz2": "bz2", ".zip": "zip", ".xz": "xz", ".zst": "zstd",}_supported_compressions = set(extension_to_compression.values())
def get_compression_method( compression: CompressionOptions,) -> tuple[str | None, CompressionDict]: """ Simplifies a compression argument to a compression method string and a mapping containing additional arguments.
Parameters ---------- compression : str or mapping If string, specifies the compression method. If mapping, value at key 'method' specifies compression method.
Returns ------- tuple of ({compression method}, Optional[str] {compression arguments}, Dict[str, Any])
Raises ------ ValueError on mapping missing 'method' key """ compression_method: str | None if isinstance(compression, Mapping): compression_args = dict(compression) try: compression_method = compression_args.pop("method") except KeyError as err: raise ValueError("If mapping, compression must have key 'method'") from err else: compression_args = {} compression_method = compression return compression_method, compression_args
def infer_compression( filepath_or_buffer: FilePath | BaseBuffer, compression: str | None) -> str | None: """ Get the compression method for filepath_or_buffer. If compression='infer', the inferred compression method is returned. Otherwise, the input compression method is returned unchanged, unless it's invalid, in which case an error is raised.
Parameters ---------- filepath_or_buffer : str or file handle File path or object.
compression : str or dict, default 'infer' For on-the-fly compression of the output data. If 'infer' and 'filepath_or_buffer' is path-like, then detect compression from the following extensions: '.gz', '.bz2', '.zip', '.xz', '.zst', '.tar', '.tar.gz', '.tar.xz' or '.tar.bz2' (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'``, ``'xz'``, ``'tar'``} and other key-value pairs are forwarded to ``zipfile.ZipFile``, ``gzip.GzipFile``, ``bz2.BZ2File``, ``zstandard.ZstdCompressor``, ``lzma.LZMAFile`` or ``tarfile.TarFile``, 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}``.
Returns ------- string or None
Raises ------ ValueError on invalid compression specified. """ if compression is None: return None
# Infer compression if compression == "infer": # Convert all path types (e.g. pathlib.Path) to strings if isinstance(filepath_or_buffer, str) and "::" in filepath_or_buffer: # chained URLs contain :: filepath_or_buffer = filepath_or_buffer.split("::")[0] filepath_or_buffer = stringify_path(filepath_or_buffer, convert_file_like=True) if not isinstance(filepath_or_buffer, str): # Cannot infer compression of a buffer, assume no compression return None
# Infer compression from the filename/URL extension for extension, compression in extension_to_compression.items(): if filepath_or_buffer.lower().endswith(extension): return compression return None
# Compression has been specified. Check that it's valid if compression in _supported_compressions: return compression
valid = ["infer", None, *sorted(_supported_compressions)] msg = ( f"Unrecognized compression type: {compression}\n" f"Valid compression types are {valid}" ) raise ValueError(msg)
def check_parent_directory(path: Path | str) -> None: """ Check if parent directory of a file exists, raise OSError if it does not
Parameters ---------- path: Path or str Path to check parent directory of """ parent = Path(path).parent if not parent.is_dir(): raise OSError(rf"Cannot save file into a non-existent directory: '{parent}'")
@overloaddef get_handle( path_or_buf: FilePath | BaseBuffer, mode: str, *, encoding: str | None = ..., compression: CompressionOptions = ..., memory_map: bool = ..., is_text: Literal[False], errors: str | None = ..., storage_options: StorageOptions = ...,) -> IOHandles[bytes]: ...
@overloaddef get_handle( path_or_buf: FilePath | BaseBuffer, mode: str, *, encoding: str | None = ..., compression: CompressionOptions = ..., memory_map: bool = ..., is_text: Literal[True] = ..., errors: str | None = ..., storage_options: StorageOptions = ...,) -> IOHandles[str]: ...
@overloaddef get_handle( path_or_buf: FilePath | BaseBuffer, mode: str, *, encoding: str | None = ..., compression: CompressionOptions = ..., memory_map: bool = ..., is_text: bool = ..., errors: str | None = ..., storage_options: StorageOptions = ...,) -> IOHandles[str] | IOHandles[bytes]: ...
def get_handle( path_or_buf: FilePath | BaseBuffer, mode: str, *, encoding: str | None = None, compression: CompressionOptions | None = None, memory_map: bool = False, is_text: bool = True, errors: str | None = None, storage_options: StorageOptions | None = None,) -> IOHandles[str] | IOHandles[bytes]: """ Get file handle for given path/buffer and mode.
Parameters ---------- path_or_buf : str or file handle File path or object. mode : str Mode to open path_or_buf with. encoding : str or None Encoding to use. compression : str or dict, default 'infer' For on-the-fly compression of the output data. If 'infer' and 'path_or_buf' is path-like, then detect compression from the following extensions: '.gz', '.bz2', '.zip', '.xz', '.zst', '.tar', '.tar.gz', '.tar.xz' or '.tar.bz2' (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'``, ``'xz'``, ``'tar'``} and other key-value pairs are forwarded to ``zipfile.ZipFile``, ``gzip.GzipFile``, ``bz2.BZ2File``, ``zstandard.ZstdCompressor``, ``lzma.LZMAFile`` or ``tarfile.TarFile``, 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}``.
May be a dict with key 'method' as compression mode and other keys as compression options if compression mode is 'zip'.
Passing compression options as keys in dict is supported for compression modes 'gzip', 'bz2', 'zstd' and 'zip'.
memory_map : bool, default False See parsers._parser_params for more information. Only used by read_csv. is_text : bool, default True Whether the type of the content passed to the file/buffer is string or bytes. This is not the same as `"b" not in mode`. If a string content is passed to a binary file/buffer, a wrapper is inserted. errors : str, default 'strict' Specifies how encoding and decoding errors are to be handled. See the errors argument for :func:`open` for a full list of options. storage_options: StorageOptions = None Passed to _get_filepath_or_buffer
Returns the dataclass IOHandles """ # Windows does not default to utf-8. Set to utf-8 for a consistent behavior encoding = encoding or "utf-8"
errors = errors or "strict"
# read_csv does not know whether the buffer is opened in binary/text mode if _is_binary_mode(path_or_buf, mode) and "b" not in mode: mode += "b"
# validate encoding and errors codecs.lookup(encoding) if isinstance(errors, str): codecs.lookup_error(errors)
# open URLs ioargs = _get_filepath_or_buffer( path_or_buf, encoding=encoding, compression=compression, mode=mode, storage_options=storage_options, )
handle = ioargs.filepath_or_buffer handles: list[BaseBuffer]
# memory mapping needs to be the first step # only used for read_csv handle, memory_map, handles = _maybe_memory_map(handle, memory_map)
is_path = isinstance(handle, str) compression_args = dict(ioargs.compression) compression = compression_args.pop("method")
# Only for write methods if "r" not in mode and is_path: check_parent_directory(str(handle))
if compression: if compression != "zstd": # compression libraries do not like an explicit text-mode ioargs.mode = ioargs.mode.replace("t", "") elif compression == "zstd" and "b" not in ioargs.mode: # python-zstandard defaults to text mode, but we always expect # compression libraries to use binary mode. ioargs.mode += "b"
# GZ Compression if compression == "gzip": if isinstance(handle, str): # error: Incompatible types in assignment (expression has type # "GzipFile", variable has type "Union[str, BaseBuffer]") handle = gzip.GzipFile( # type: ignore[assignment] filename=handle, mode=ioargs.mode, **compression_args, ) else: handle = gzip.GzipFile( # No overload variant of "GzipFile" matches argument types # "Union[str, BaseBuffer]", "str", "Dict[str, Any]" fileobj=handle, # type: ignore[call-overload] mode=ioargs.mode, **compression_args, )
# BZ Compression elif compression == "bz2": import bz2
# Overload of "BZ2File" to handle pickle protocol 5 # "Union[str, BaseBuffer]", "str", "Dict[str, Any]" handle = bz2.BZ2File( # type: ignore[call-overload] handle, mode=ioargs.mode, **compression_args, )
# ZIP Compression elif compression == "zip": # error: Argument 1 to "_BytesZipFile" has incompatible type # "Union[str, BaseBuffer]"; expected "Union[Union[str, PathLike[str]], # ReadBuffer[bytes], WriteBuffer[bytes]]" handle = _BytesZipFile( handle, # type: ignore[arg-type] ioargs.mode, **compression_args, ) if handle.buffer.mode == "r": handles.append(handle) zip_names = handle.buffer.namelist() if len(zip_names) == 1: handle = handle.buffer.open(zip_names.pop()) elif not zip_names: raise ValueError(f"Zero files found in ZIP file {path_or_buf}") else: raise ValueError( "Multiple files found in ZIP file. " f"Only one file per ZIP: {zip_names}" )
# TAR Encoding elif compression == "tar": compression_args.setdefault("mode", ioargs.mode) if isinstance(handle, str): handle = _BytesTarFile(name=handle, **compression_args) else: # error: Argument "fileobj" to "_BytesTarFile" has incompatible # type "BaseBuffer"; expected "Union[ReadBuffer[bytes], # WriteBuffer[bytes], None]" handle = _BytesTarFile( fileobj=handle, # type: ignore[arg-type] **compression_args, ) assert isinstance(handle, _BytesTarFile) if "r" in handle.buffer.mode: handles.append(handle) files = handle.buffer.getnames() if len(files) == 1: file = handle.buffer.extractfile(files[0]) assert file is not None handle = file elif not files: raise ValueError(f"Zero files found in TAR archive {path_or_buf}") else: raise ValueError( "Multiple files found in TAR archive. " f"Only one file per TAR archive: {files}" )
# XZ Compression elif compression == "xz": # error: Argument 1 to "LZMAFile" has incompatible type "Union[str, # BaseBuffer]"; expected "Optional[Union[Union[str, bytes, PathLike[str], # PathLike[bytes]], IO[bytes]], None]" import lzma
handle = lzma.LZMAFile( handle, # type: ignore[arg-type] ioargs.mode, **compression_args, )
# Zstd Compression elif compression == "zstd": zstd = import_optional_dependency("zstandard") if "r" in ioargs.mode: open_args = {"dctx": zstd.ZstdDecompressor(**compression_args)} else: open_args = {"cctx": zstd.ZstdCompressor(**compression_args)} handle = zstd.open( handle, mode=ioargs.mode, **open_args, )
# Unrecognized Compression else: msg = f"Unrecognized compression type: {compression}" raise ValueError(msg)
assert not isinstance(handle, str) handles.append(handle)
elif isinstance(handle, str): # Check whether the filename is to be opened in binary mode. # Binary mode does not support 'encoding' and 'newline'. if ioargs.encoding and "b" not in ioargs.mode: # Encoding handle = open( handle, ioargs.mode, encoding=ioargs.encoding, errors=errors, newline="", ) else: # Binary mode handle = open(handle, ioargs.mode) handles.append(handle)
# Convert BytesIO or file objects passed with an encoding is_wrapped = False if not is_text and ioargs.mode == "rb" and isinstance(handle, TextIOBase): # not added to handles as it does not open/buffer resources handle = _BytesIOWrapper( handle, encoding=ioargs.encoding, ) elif is_text and ( compression or memory_map or _is_binary_mode(handle, ioargs.mode) ): if ( not hasattr(handle, "readable") or not hasattr(handle, "writable") or not hasattr(handle, "seekable") ): handle = _IOWrapper(handle) # error: Value of type variable "_BufferT_co" of "TextIOWrapper" cannot # be "_IOWrapper | BaseBuffer" [type-var] handle = TextIOWrapper( handle, # type: ignore[type-var] encoding=ioargs.encoding, errors=errors, newline="", ) handles.append(handle) # only marked as wrapped when the caller provided a handle is_wrapped = not ( isinstance(ioargs.filepath_or_buffer, str) or ioargs.should_close )
if "r" in ioargs.mode and not hasattr(handle, "read"): raise TypeError( "Expected file path name or file-like object, " f"got {type(ioargs.filepath_or_buffer)} type" )
handles.reverse() # close the most recently added buffer first if ioargs.should_close: assert not isinstance(ioargs.filepath_or_buffer, str) handles.append(ioargs.filepath_or_buffer) handles.extend(ioargs.close_handles)
return IOHandles( # error: Argument "handle" to "IOHandles" has incompatible type # "Union[TextIOWrapper, GzipFile, BaseBuffer, typing.IO[bytes], # typing.IO[Any]]"; expected "pandas._typing.IO[Any]" handle=handle, # type: ignore[arg-type] # error: Argument "created_handles" to "IOHandles" has incompatible type # "List[BaseBuffer]"; expected "List[Union[IO[bytes], IO[str]]]" created_handles=handles, # type: ignore[arg-type] is_wrapped=is_wrapped, compression=ioargs.compression, )
class _BufferedWriter(BytesIO, ABC): """ Some objects do not support multiple .write() calls (TarFile and ZipFile). This wrapper writes to the underlying buffer on close. """
buffer = BytesIO()
@abstractmethod def write_to_buffer(self) -> None: ...
def close(self) -> None: if self.closed: # already closed return if self.getbuffer().nbytes: # write to buffer self.seek(0) with self.buffer: self.write_to_buffer() else: self.buffer.close() super().close()
class _BytesTarFile(_BufferedWriter): def __init__( self, name: str | None = None, mode: Literal["r", "a", "w", "x"] = "r", fileobj: ReadBuffer[bytes] | WriteBuffer[bytes] | None = None, archive_name: str | None = None, **kwargs: Any, ) -> None: super().__init__() self.archive_name = archive_name self.name = name # error: No overload variant of "open" of "TarFile" matches argument # types "str | None", "str", "ReadBuffer[bytes] | WriteBuffer[bytes] | None", # "dict[str, Any]" # error: Incompatible types in assignment (expression has type "TarFile", # base class "_BufferedWriter" defined the type as "BytesIO") self.buffer: tarfile.TarFile = tarfile.TarFile.open( # type: ignore[call-overload, assignment] name=name, mode=self.extend_mode(mode), fileobj=fileobj, **kwargs, )
def extend_mode(self, mode: str) -> str: mode = mode.replace("b", "") if mode != "w": return mode if self.name is not None: suffix = Path(self.name).suffix if suffix in (".gz", ".xz", ".bz2"): mode = f"{mode}:{suffix[1:]}" return mode
def infer_filename(self) -> str | None: """ If an explicit archive_name is not given, we still want the file inside the zip file not to be named something.tar, because that causes confusion (GH39465). """ if self.name is None: return None
filename = Path(self.name) if filename.suffix == ".tar": return filename.with_suffix("").name elif filename.suffix in (".tar.gz", ".tar.bz2", ".tar.xz"): return filename.with_suffix("").with_suffix("").name return filename.name
def write_to_buffer(self) -> None: # TarFile needs a non-empty string archive_name = self.archive_name or self.infer_filename() or "tar" tarinfo = tarfile.TarInfo(name=archive_name) tarinfo.size = len(self.getvalue()) self.buffer.addfile(tarinfo, self)
class _BytesZipFile(_BufferedWriter): def __init__( self, file: FilePath | ReadBuffer[bytes] | WriteBuffer[bytes], mode: str, archive_name: str | None = None, **kwargs: Any, ) -> None: super().__init__() mode = mode.replace("b", "") self.archive_name = archive_name
kwargs.setdefault("compression", zipfile.ZIP_DEFLATED) # error: No overload variant of "ZipFile" matches argument types # "str | PathLike[str] | ReadBuffer[bytes] | WriteBuffer[bytes]", # "str", "dict[str, Any]" # error: Incompatible types in assignment (expression has type "ZipFile", # base class "_BufferedWriter" defined the type as "BytesIO") self.buffer: zipfile.ZipFile = zipfile.ZipFile( # type: ignore[call-overload, assignment] file, mode, **kwargs )
def infer_filename(self) -> str | None: """ If an explicit archive_name is not given, we still want the file inside the zip file not to be named something.zip, because that causes confusion (GH39465). """ if isinstance(self.buffer.filename, (os.PathLike, str)): filename = Path(self.buffer.filename) if filename.suffix == ".zip": return filename.with_suffix("").name return filename.name return None
def write_to_buffer(self) -> None: # ZipFile needs a non-empty string archive_name = self.archive_name or self.infer_filename() or "zip" self.buffer.writestr(archive_name, self.getvalue())
class _IOWrapper: # TextIOWrapper is overly strict: it request that the buffer has seekable, readable, # and writable. If we have a read-only buffer, we shouldn't need writable and vice # versa. Some buffers, are seek/read/writ-able but they do not have the "-able" # methods, e.g., tempfile.SpooledTemporaryFile. # If a buffer does not have the above "-able" methods, we simple assume they are # seek/read/writ-able. def __init__(self, buffer: BaseBuffer) -> None: self.buffer = buffer
def __getattr__(self, name: str) -> Any: return getattr(self.buffer, name)
def readable(self) -> bool: if hasattr(self.buffer, "readable"): return self.buffer.readable() return True
def seekable(self) -> bool: if hasattr(self.buffer, "seekable"): return self.buffer.seekable() return True
def writable(self) -> bool: if hasattr(self.buffer, "writable"): return self.buffer.writable() return True
class _BytesIOWrapper: # Wrapper that wraps a StringIO buffer and reads bytes from it # Created for compat with pyarrow read_csv def __init__(self, buffer: StringIO | TextIOBase, encoding: str = "utf-8") -> None: self.buffer = buffer self.encoding = encoding # Because a character can be represented by more than 1 byte, # it is possible that reading will produce more bytes than n # We store the extra bytes in this overflow variable, and append the # overflow to the front of the bytestring the next time reading is performed self.overflow = b""
def __getattr__(self, attr: str) -> Any: return getattr(self.buffer, attr)
def read(self, n: int | None = -1) -> bytes: assert self.buffer is not None bytestring = self.buffer.read(n).encode(self.encoding) # When n=-1/n greater than remaining bytes: Read entire file/rest of file combined_bytestring = self.overflow + bytestring if n is None or n < 0 or n >= len(combined_bytestring): self.overflow = b"" return combined_bytestring else: to_return = combined_bytestring[:n] self.overflow = combined_bytestring[n:] return to_return
def _maybe_memory_map( handle: str | BaseBuffer, memory_map: bool) -> tuple[str | BaseBuffer, bool, list[BaseBuffer]]: """Try to memory map file/buffer.""" handles: list[BaseBuffer] = [] memory_map &= hasattr(handle, "fileno") or isinstance(handle, str) if not memory_map: return handle, memory_map, handles
# mmap used by only read_csv handle = cast(ReadCsvBuffer, handle)
# need to open the file first if isinstance(handle, str): handle = open(handle, "rb") handles.append(handle)
try: # open mmap and adds *-able # error: Argument 1 to "_IOWrapper" has incompatible type "mmap"; # expected "BaseBuffer" wrapped = _IOWrapper( mmap.mmap( handle.fileno(), 0, access=mmap.ACCESS_READ, # type: ignore[arg-type] ) ) finally: for handle in reversed(handles): # error: "BaseBuffer" has no attribute "close" handle.close() # type: ignore[attr-defined]
return wrapped, memory_map, [wrapped]
def file_exists(filepath_or_buffer: FilePath | BaseBuffer) -> bool: """Test whether file exists.""" exists = False filepath_or_buffer = stringify_path(filepath_or_buffer) if not isinstance(filepath_or_buffer, str): return exists try: exists = os.path.exists(filepath_or_buffer) # gh-5874: if the filepath is too long will raise here except (TypeError, ValueError): pass return exists
def _is_binary_mode(handle: FilePath | BaseBuffer, mode: str) -> bool: """Whether the handle is opened in binary mode""" # specified by user if "t" in mode or "b" in mode: return "b" in mode
# exceptions text_classes = ( # classes that expect string but have 'b' in mode codecs.StreamWriter, codecs.StreamReader, codecs.StreamReaderWriter, ) if issubclass(type(handle), text_classes): return False
return isinstance(handle, _get_binary_io_classes()) or "b" in getattr( handle, "mode", mode )
@functools.lru_cachedef _get_binary_io_classes() -> tuple[type, ...]: """IO classes that that expect bytes""" binary_classes: tuple[type, ...] = (BufferedIOBase, RawIOBase)
# python-zstandard doesn't use any of the builtin base classes; instead we # have to use the `zstd.ZstdDecompressionReader` class for isinstance checks. # Unfortunately `zstd.ZstdDecompressionReader` isn't exposed by python-zstandard # so we have to get it from a `zstd.ZstdDecompressor` instance. # See also https://github.com/indygreg/python-zstandard/pull/165. zstd = import_optional_dependency("zstandard", errors="ignore") if zstd is not None: with zstd.ZstdDecompressor().stream_reader(b"") as reader: binary_classes += (type(reader),)
return binary_classes
def is_potential_multi_index( columns: Sequence[Hashable] | MultiIndex, index_col: bool | Sequence[int] | None = None,) -> bool: """ Check whether or not the `columns` parameter could be converted into a MultiIndex.
Parameters ---------- columns : array-like Object which may or may not be convertible into a MultiIndex index_col : None, bool or list, optional Column or columns to use as the (possibly hierarchical) index
Returns ------- bool : Whether or not columns could become a MultiIndex """ if index_col is None or isinstance(index_col, bool): index_columns = set() else: index_columns = set(index_col)
return bool( len(columns) and not isinstance(columns, ABCMultiIndex) and all(isinstance(c, tuple) for c in columns if c not in index_columns) )
def dedup_names( names: Sequence[Hashable], is_potential_multiindex: bool) -> Sequence[Hashable]: """ Rename column names if duplicates exist.
Currently the renaming is done by appending a period and an autonumeric, but a custom pattern may be supported in the future.
Examples -------- >>> dedup_names(["x", "y", "x", "x"], is_potential_multiindex=False) ['x', 'y', 'x.1', 'x.2'] """ names = list(names) # so we can index counts: DefaultDict[Hashable, int] = defaultdict(int)
for i, col in enumerate(names): cur_count = counts[col]
while cur_count > 0: counts[col] = cur_count + 1
if is_potential_multiindex: # for mypy assert isinstance(col, tuple) col = (*col[:-1], f"{col[-1]}.{cur_count}") else: col = f"{col}.{cur_count}" cur_count = counts[col]
names[i] = col counts[col] = cur_count + 1
return names12345678910111213141516171819from pandas.io.excel._base import ( ExcelFile, ExcelWriter, read_excel,)from pandas.io.excel._odswriter import ODSWriter as _ODSWriterfrom pandas.io.excel._openpyxl import OpenpyxlWriter as _OpenpyxlWriterfrom pandas.io.excel._util import register_writerfrom pandas.io.excel._xlsxwriter import XlsxWriter as _XlsxWriter
__all__ = ["ExcelFile", "ExcelWriter", "read_excel"]
register_writer(_OpenpyxlWriter)
register_writer(_XlsxWriter)
register_writer(_ODSWriter)12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871from __future__ import annotations
from collections.abc import ( Callable, Hashable, Iterable, Mapping, Sequence,)import datetimefrom decimal import Decimalfrom functools import partialimport osfrom typing import ( IO, TYPE_CHECKING, Any, Generic, Literal, Self, TypeVar, Union, cast, overload,)import warningsimport zipfile
from pandas._config import config
from pandas._libs import libfrom pandas.compat._optional import ( get_version, import_optional_dependency,)from pandas.errors import EmptyDataErrorfrom pandas.util._decorators import ( set_module,)from pandas.util._exceptions import find_stack_levelfrom pandas.util._validators import check_dtype_backend
from pandas.core.dtypes.common import ( is_bool, is_decimal, is_file_like, is_float, is_integer, is_list_like,)
from pandas.core.frame import DataFramefrom pandas.util.version import Version
from pandas.io.common import ( IOHandles, get_handle, stringify_path, validate_header_arg,)from pandas.io.excel._util import ( fill_mi_header, get_default_engine, get_writer, maybe_convert_usecols, pop_header_name,)from pandas.io.parsers import TextParserfrom pandas.io.parsers.readers import validate_integer
if TYPE_CHECKING: from types import TracebackType
from pandas._typing import ( DtypeArg, DtypeBackend, ExcelWriterIfSheetExists, FilePath, HashableT, IntStrT, ReadBuffer, SequenceNotStr, StorageOptions, WriteExcelBuffer, )
@overloaddef read_excel( io, # sheet name is str or int -> DataFrame sheet_name: str | int = ..., *, header: int | Sequence[int] | None = ..., names: SequenceNotStr[Hashable] | range | None = ..., index_col: int | str | Sequence[int] | None = ..., usecols: int | str | Sequence[int] | Sequence[str] | Callable[[HashableT], bool] | None = ..., dtype: DtypeArg | None = ..., engine: Literal["xlrd", "openpyxl", "odf", "pyxlsb", "calamine"] | None = ..., converters: dict[str, Callable] | dict[int, Callable] | None = ..., true_values: Iterable[Hashable] | None = ..., false_values: Iterable[Hashable] | None = ..., skiprows: Sequence[int] | int | Callable[[int], object] | None = ..., nrows: int | None = ..., na_values=..., keep_default_na: bool = ..., na_filter: bool = ..., verbose: bool = ..., parse_dates: list | dict | bool = ..., date_format: dict[Hashable, str] | str | None = ..., thousands: str | None = ..., decimal: str = ..., comment: str | None = ..., skipfooter: int = ..., storage_options: StorageOptions = ..., dtype_backend: DtypeBackend | lib.NoDefault = ...,) -> DataFrame: ...
@overloaddef read_excel( io, # sheet name is list or None -> dict[IntStrT, DataFrame] sheet_name: list[IntStrT] | None, *, header: int | Sequence[int] | None = ..., names: SequenceNotStr[Hashable] | range | None = ..., index_col: int | str | Sequence[int] | None = ..., usecols: int | str | Sequence[int] | Sequence[str] | Callable[[HashableT], bool] | None = ..., dtype: DtypeArg | None = ..., engine: Literal["xlrd", "openpyxl", "odf", "pyxlsb", "calamine"] | None = ..., converters: dict[str, Callable] | dict[int, Callable] | None = ..., true_values: Iterable[Hashable] | None = ..., false_values: Iterable[Hashable] | None = ..., skiprows: Sequence[int] | int | Callable[[int], object] | None = ..., nrows: int | None = ..., na_values=..., keep_default_na: bool = ..., na_filter: bool = ..., verbose: bool = ..., parse_dates: list | dict | bool = ..., date_format: dict[Hashable, str] | str | None = ..., thousands: str | None = ..., decimal: str = ..., comment: str | None = ..., skipfooter: int = ..., storage_options: StorageOptions = ..., dtype_backend: DtypeBackend | lib.NoDefault = ...,) -> dict[IntStrT, DataFrame]: ...
@set_module("pandas")def read_excel( io, sheet_name: str | int | list[IntStrT] | None = 0, *, header: int | Sequence[int] | None = 0, names: SequenceNotStr[Hashable] | range | None = None, index_col: int | str | Sequence[int] | None = None, usecols: int | str | Sequence[int] | Sequence[str] | Callable[[HashableT], bool] | None = None, dtype: DtypeArg | None = None, engine: Literal["xlrd", "openpyxl", "odf", "pyxlsb", "calamine"] | None = None, converters: dict[str, Callable] | dict[int, Callable] | None = None, true_values: Iterable[Hashable] | None = None, false_values: Iterable[Hashable] | None = None, skiprows: Sequence[int] | int | Callable[[int], object] | None = None, nrows: int | None = None, na_values=None, keep_default_na: bool = True, na_filter: bool = True, verbose: bool = False, parse_dates: list | dict | bool = False, date_format: dict[Hashable, str] | str | None = None, thousands: str | None = None, decimal: str = ".", comment: str | None = None, skipfooter: int = 0, storage_options: StorageOptions | None = None, dtype_backend: DtypeBackend | lib.NoDefault = lib.no_default, engine_kwargs: dict | None = None,) -> DataFrame | dict[IntStrT, DataFrame]: """ Read an Excel file into a ``DataFrame``.
Supports `xls`, `xlsx`, `xlsm`, `xlsb`, `odf`, `ods` and `odt` file extensions read from a local filesystem or URL. Supports an option to read a single sheet or a list of sheets.
Parameters ---------- io : str, ExcelFile, xlrd.Book, path object, or file-like object Any valid string path is acceptable. The string could be a URL. Valid URL schemes include http, ftp, s3, and file. For file URLs, a host is expected. A local file could be: ``file://localhost/path/to/table.xlsx``.
If you want to pass in a path object, pandas accepts any ``os.PathLike``.
By file-like object, we refer to objects with a ``read()`` method, such as a file handle (e.g. via builtin ``open`` function) or ``StringIO``.
sheet_name : str, int, list, or None, default 0 Strings are used for sheet names. Integers are used in zero-indexed sheet positions (chart sheets do not count as a sheet position). Lists of strings/integers are used to request multiple sheets. When ``None``, will return a dictionary containing DataFrames for each sheet.
Available cases:
* Defaults to ``0``: 1st sheet as a `DataFrame` * ``1``: 2nd sheet as a `DataFrame` * ``"Sheet1"``: Load sheet with name "Sheet1" * ``[0, 1, "Sheet5"]``: Load first, second and sheet named "Sheet5" as a dict of `DataFrame` * ``None``: Returns a dictionary containing DataFrames for each sheet.
header : int, list of int, default 0 Row (0-indexed) to use for the column labels of the parsed DataFrame. If a list of integers is passed those row positions will be combined into a ``MultiIndex``. Use None if there is no header. names : array-like, default None List of column names to use. If file contains no header row, then you should explicitly pass header=None. index_col : int, str, list of int, default None Column (0-indexed) to use as the row labels of the DataFrame. Pass None if there is no such column. If a list is passed, those columns will be combined into a ``MultiIndex``. If a subset of data is selected with ``usecols``, index_col is based on the subset.
Missing values will be forward filled to allow roundtripping with ``to_excel`` for ``merged_cells=True``. To avoid forward filling the missing values use ``set_index`` after reading the data instead of ``index_col``. usecols : str, list-like, or callable, default None * If None, then parse all columns. * If str, then indicates comma separated list of Excel column letters and column ranges (e.g. "A:E" or "A,C,E:F"). Ranges are inclusive of both sides. * If list of int, then indicates list of column numbers to be parsed (0-indexed). * If list of string, then indicates list of column names to be parsed. * If callable, then evaluate each column name against it and parse the column if the callable returns ``True``.
Returns a subset of the columns according to behavior above. dtype : Type name or dict of column -> type, default None Data type for data or columns. E.g. {'a': np.float64, 'b': np.int32} Use ``object`` to preserve data as stored in Excel and not interpret dtype, which will necessarily result in ``object`` dtype. If converters are specified, they will be applied INSTEAD of dtype conversion. If you use ``None``, it will infer the dtype of each column based on the data. engine : {'openpyxl', 'calamine', 'odf', 'pyxlsb', 'xlrd'}, default None If io is not a buffer or path, this must be set to identify io. Engine compatibility :
- ``openpyxl`` supports newer Excel file formats. - ``calamine`` supports Excel (.xls, .xlsx, .xlsm, .xlsb) and OpenDocument (.ods) file formats. - ``odf`` supports OpenDocument file formats (.odf, .ods, .odt). - ``pyxlsb`` supports Binary Excel files. - ``xlrd`` supports old-style Excel files (.xls).
When ``engine=None``, the following logic will be used to determine the engine:
- If ``path_or_buffer`` is an OpenDocument format (.odf, .ods, .odt), then `odf <https://pypi.org/project/odfpy/>`_ will be used. - Otherwise if ``path_or_buffer`` is an xls format, ``xlrd`` will be used. - Otherwise if ``path_or_buffer`` is in xlsb format, ``pyxlsb`` will be used. - Otherwise ``openpyxl`` will be used.
converters : dict, default None Dict of functions for converting values in certain columns. Keys can either be integers or column labels, values are functions that take one input argument, the Excel cell content, and return the transformed content. true_values : list, default None Values to consider as True. false_values : list, default None Values to consider as False. skiprows : list-like, int, or callable, optional Line numbers to skip (0-indexed) or number of lines to skip (int) at the start of the file. If callable, the callable function will be evaluated against the row indices, returning True if the row should be skipped and False otherwise. An example of a valid callable argument would be ``lambda x: x in [0, 2]``. nrows : int, default None Number of rows to parse. Does not include header rows. na_values : scalar, str, list-like, or dict, default None Additional strings to recognize as NA/NaN. If dict passed, specific per-column NA values. By default the following values are interpreted as NaN: '', '#N/A', '#N/A N/A', '#NA', '-1.#IND', '-1.#QNAN', '-NaN', '-nan', '1.#IND', '1.#QNAN', '<NA>', 'N/A', 'NA', 'NULL', 'NaN', 'None', 'n/a', 'nan', 'null'. keep_default_na : bool, default True Whether or not to include the default NaN values when parsing the data. Depending on whether ``na_values`` is passed in, the behavior is as follows:
* If ``keep_default_na`` is True, and ``na_values`` are specified, ``na_values`` is appended to the default NaN values used for parsing. * If ``keep_default_na`` is True, and ``na_values`` are not specified, only the default NaN values are used for parsing. * If ``keep_default_na`` is False, and ``na_values`` are specified, only the NaN values specified ``na_values`` are used for parsing. * If ``keep_default_na`` is False, and ``na_values`` are not specified, no strings will be parsed as NaN.
Note that if `na_filter` is passed in as False, the ``keep_default_na`` and ``na_values`` parameters will be ignored. na_filter : bool, default True Detect missing value markers (empty strings and the value of na_values). In data without any NAs, passing ``na_filter=False`` can improve the performance of reading a large file. verbose : bool, default False Indicate number of NA values placed in non-numeric columns. parse_dates : bool, list-like, or dict, default False The behavior is as follows:
* ``bool``. If True -> try parsing the index. * ``list`` of int or names. e.g. If [1, 2, 3] -> try parsing columns 1, 2, 3 each as a separate date column. * ``list`` of lists. e.g. If [[1, 3]] -> combine columns 1 and 3 and parse as a single date column. * ``dict``, e.g. {'foo' : [1, 3]} -> parse columns 1, 3 as date and call result 'foo'
If a column or index contains an unparsable date, the entire column or index will be returned unaltered as an object data type. If you don`t want to parse some cells as date just change their type in Excel to "Text". For non-standard datetime parsing, use ``pd.to_datetime`` after ``pd.read_excel``.
Note: A fast-path exists for iso8601-formatted dates. date_format : str or dict of column -> format, default ``None`` If used in conjunction with ``parse_dates``, will parse dates according to this format. For anything more complex, please read in as ``object`` and then apply :func:`to_datetime` as-needed.
.. versionadded:: 2.0.0
thousands : str, default None Thousands separator for parsing string columns to numeric. Note that this parameter is only necessary for columns stored as TEXT in Excel, any numeric columns will automatically be parsed, regardless of display format. decimal : str, default '.' Character to recognize as decimal point for parsing string columns to numeric. Note that this parameter is only necessary for columns stored as TEXT in Excel, any numeric columns will automatically be parsed, regardless of display format.(e.g. use ',' for European data). comment : str, default None Comments out remainder of line. Pass a character or characters to this argument to indicate comments in the input file. Any data between the comment string and the end of the current line is ignored. skipfooter : int, default 0 Rows at the end to skip (0-indexed). storage_options : dict, optional 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.request.Request`` as header options. For other URLs (e.g. starting with "s3://", and "gcs://") the key-value pairs are forwarded to ``fsspec.open``. Please see ``fsspec`` and ``urllib`` for more details, and for more examples on storage options refer `here <https://pandas.pydata.org/docs/user_guide/io.html? highlight=storage_options#reading-writing-remote-files>`_.
dtype_backend : {'numpy_nullable', 'pyarrow'} Back-end data type applied to the resultant :class:`DataFrame` (still experimental). If not specified, the default behavior is to not use nullable data types. If specified, the behavior is as follows:
* ``"numpy_nullable"``: returns nullable-dtype-backed :class:`DataFrame` * ``"pyarrow"``: returns pyarrow-backed nullable
:class:`ArrowDtype` :class:`DataFrame`
.. versionadded:: 2.0
engine_kwargs : dict, optional Arbitrary keyword arguments passed to excel engine.
Returns ------- DataFrame or dict of DataFrames DataFrame from the passed in Excel file. See notes in sheet_name argument for more information on when a dict of DataFrames is returned.
See Also -------- DataFrame.to_excel : Write DataFrame to an Excel file. DataFrame.to_csv : Write DataFrame to a comma-separated values (csv) file. read_csv : Read a comma-separated values (csv) file into DataFrame. read_fwf : Read a table of fixed-width formatted lines into DataFrame.
Notes ----- For specific information on the methods used for each Excel engine, refer to the pandas :ref:`user guide <io.excel_reader>`
Examples -------- The file can be read using the file name as string or an open file object:
>>> pd.read_excel("tmp.xlsx", index_col=0) # doctest: +SKIP Name Value 0 string1 1 1 string2 2 2 #Comment 3
>>> pd.read_excel(open("tmp.xlsx", "rb"), sheet_name="Sheet3") # doctest: +SKIP Unnamed: 0 Name Value 0 0 string1 1 1 1 string2 2 2 2 #Comment 3
Index and header can be specified via the `index_col` and `header` arguments
>>> pd.read_excel("tmp.xlsx", index_col=None, header=None) # doctest: +SKIP 0 1 2 0 NaN Name Value 1 0.0 string1 1 2 1.0 string2 2 3 2.0 #Comment 3
Column types are inferred but can be explicitly specified
>>> pd.read_excel( ... "tmp.xlsx", index_col=0, dtype={"Name": str, "Value": float} ... ) # doctest: +SKIP Name Value 0 string1 1.0 1 string2 2.0 2 #Comment 3.0
True, False, and NA values, and thousands separators have defaults, but can be explicitly specified, too. Supply the values you would like as strings or lists of strings!
>>> pd.read_excel( ... "tmp.xlsx", index_col=0, na_values=["string1", "string2"] ... ) # doctest: +SKIP Name Value 0 NaN 1 1 NaN 2 2 #Comment 3
Comment lines in the excel input file can be skipped using the ``comment`` kwarg.
>>> pd.read_excel("tmp.xlsx", index_col=0, comment="#") # doctest: +SKIP Name Value 0 string1 1.0 1 string2 2.0 2 None NaN """ check_dtype_backend(dtype_backend) should_close = False if engine_kwargs is None: engine_kwargs = {}
if not isinstance(io, ExcelFile): should_close = True io = ExcelFile( io, storage_options=storage_options, engine=engine, engine_kwargs=engine_kwargs, ) elif engine and engine != io.engine: raise ValueError( "Engine should not be specified when passing " "an ExcelFile - ExcelFile already has the engine set" )
try: data = io.parse( sheet_name=sheet_name, header=header, names=names, index_col=index_col, usecols=usecols, dtype=dtype, converters=converters, true_values=true_values, false_values=false_values, skiprows=skiprows, nrows=nrows, na_values=na_values, keep_default_na=keep_default_na, na_filter=na_filter, verbose=verbose, parse_dates=parse_dates, date_format=date_format, thousands=thousands, decimal=decimal, comment=comment, skipfooter=skipfooter, dtype_backend=dtype_backend, ) finally: # make sure to close opened file handles if should_close: io.close() return data
_WorkbookT = TypeVar("_WorkbookT")
class BaseExcelReader(Generic[_WorkbookT]): book: _WorkbookT
def __init__( self, filepath_or_buffer, storage_options: StorageOptions | None = None, engine_kwargs: dict | None = None, ) -> None: if engine_kwargs is None: engine_kwargs = {}
self.handles = IOHandles( handle=filepath_or_buffer, compression={"method": None} ) if not isinstance(filepath_or_buffer, (ExcelFile, self._workbook_class)): self.handles = get_handle( filepath_or_buffer, "rb", storage_options=storage_options, is_text=False )
if isinstance(self.handles.handle, self._workbook_class): self.book = self.handles.handle elif hasattr(self.handles.handle, "read"): # N.B. xlrd.Book has a read attribute too self.handles.handle.seek(0) try: self.book = self.load_workbook(self.handles.handle, engine_kwargs) except Exception: self.close() raise else: raise ValueError( "Must explicitly set engine if not passing in buffer or path for io." )
@property def _workbook_class(self) -> type[_WorkbookT]: raise NotImplementedError
def load_workbook(self, filepath_or_buffer, engine_kwargs) -> _WorkbookT: raise NotImplementedError
def close(self) -> None: if hasattr(self, "book"): if hasattr(self.book, "close"): # pyxlsb: opens a TemporaryFile # openpyxl: https://stackoverflow.com/questions/31416842/ # openpyxl-does-not-close-excel-workbook-in-read-only-mode self.book.close() elif hasattr(self.book, "release_resources"): # xlrd # https://github.com/python-excel/xlrd/blob/2.0.1/xlrd/book.py#L548 self.book.release_resources() self.handles.close()
@property def sheet_names(self) -> list[str]: raise NotImplementedError
def get_sheet_by_name(self, name: str): raise NotImplementedError
def get_sheet_by_index(self, index: int): raise NotImplementedError
def get_sheet_data(self, sheet, rows: int | None = None): raise NotImplementedError
def raise_if_bad_sheet_by_index(self, index: int) -> None: n_sheets = len(self.sheet_names) if index >= n_sheets: raise ValueError( f"Worksheet index {index} is invalid, {n_sheets} worksheets found" )
def raise_if_bad_sheet_by_name(self, name: str) -> None: if name not in self.sheet_names: raise ValueError(f"Worksheet named '{name}' not found")
def _check_skiprows_func( self, skiprows: Callable, rows_to_use: int, ) -> int: """ Determine how many file rows are required to obtain `nrows` data rows when `skiprows` is a function.
Parameters ---------- skiprows : function The function passed to read_excel by the user. rows_to_use : int The number of rows that will be needed for the header and the data.
Returns ------- int """ i = 0 rows_used_so_far = 0 while rows_used_so_far < rows_to_use: if not skiprows(i): rows_used_so_far += 1 i += 1 return i
def _calc_rows( self, header: int | Sequence[int] | None, index_col: int | Sequence[int] | None, skiprows: Sequence[int] | int | Callable[[int], object] | None, nrows: int | None, ) -> int | None: """ If nrows specified, find the number of rows needed from the file, otherwise return None.
Parameters ---------- header : int, list of int, or None See read_excel docstring. index_col : int, str, list of int, or None See read_excel docstring. skiprows : list-like, int, callable, or None See read_excel docstring. nrows : int or None See read_excel docstring.
Returns ------- int or None """ if nrows is None: return None if header is None: header_rows = 1 elif is_integer(header): header = cast(int, header) header_rows = 1 + header else: header = cast(Sequence, header) header_rows = 1 + header[-1] # If there is a MultiIndex header and an index then there is also # a row containing just the index name(s) if is_list_like(header) and index_col is not None: header = cast(Sequence, header) if len(header) > 1: header_rows += 1 if skiprows is None: return header_rows + nrows if is_integer(skiprows): skiprows = cast(int, skiprows) return header_rows + nrows + skiprows if is_list_like(skiprows):
def f(skiprows: Sequence, x: int) -> bool: return x in skiprows
skiprows = cast(Sequence, skiprows) return self._check_skiprows_func(partial(f, skiprows), header_rows + nrows) if callable(skiprows): return self._check_skiprows_func( skiprows, header_rows + nrows, ) # else unexpected skiprows type: read_excel will not optimize # the number of rows read from file return None
def parse( self, sheet_name: str | int | list[int] | list[str] | None = 0, header: int | Sequence[int] | None = 0, names: SequenceNotStr[Hashable] | range | None = None, index_col: int | Sequence[int] | None = None, usecols=None, dtype: DtypeArg | None = None, true_values: Iterable[Hashable] | None = None, false_values: Iterable[Hashable] | None = None, skiprows: Sequence[int] | int | Callable[[int], object] | None = None, nrows: int | None = None, na_values=None, verbose: bool = False, parse_dates: list | dict | bool = False, date_format: dict[Hashable, str] | str | None = None, thousands: str | None = None, decimal: str = ".", comment: str | None = None, skipfooter: int = 0, dtype_backend: DtypeBackend | lib.NoDefault = lib.no_default, **kwds, ): validate_header_arg(header) validate_integer("nrows", nrows)
ret_dict = False
# Keep sheetname to maintain backwards compatibility. sheets: list[int] | list[str] if isinstance(sheet_name, list): sheets = sheet_name ret_dict = True elif sheet_name is None: sheets = self.sheet_names ret_dict = True elif isinstance(sheet_name, str): sheets = [sheet_name] else: sheets = [sheet_name]
# handle same-type duplicates. sheets = cast(Union[list[int], list[str]], list(dict.fromkeys(sheets).keys()))
output = {}
last_sheetname = None for asheetname in sheets: last_sheetname = asheetname if verbose: print(f"Reading sheet {asheetname}")
if isinstance(asheetname, str): sheet = self.get_sheet_by_name(asheetname) else: # assume an integer if not a string sheet = self.get_sheet_by_index(asheetname)
file_rows_needed = self._calc_rows(header, index_col, skiprows, nrows) data = self.get_sheet_data(sheet, file_rows_needed) if hasattr(sheet, "close"): # pyxlsb opens two TemporaryFiles sheet.close() usecols = maybe_convert_usecols(usecols)
if not data: output[asheetname] = DataFrame() continue
output = self._parse_sheet( data=data, output=output, asheetname=asheetname, header=header, names=names, index_col=index_col, usecols=usecols, dtype=dtype, skiprows=skiprows, nrows=nrows, true_values=true_values, false_values=false_values, na_values=na_values, parse_dates=parse_dates, date_format=date_format, thousands=thousands, decimal=decimal, comment=comment, skipfooter=skipfooter, dtype_backend=dtype_backend, **kwds, )
if last_sheetname is None: raise ValueError("Sheet name is an empty list")
if ret_dict: return output else: return output[last_sheetname]
def _parse_sheet( self, data: list, output: dict, asheetname: str | int | None = None, header: int | Sequence[int] | None = 0, names: SequenceNotStr[Hashable] | range | None = None, index_col: int | Sequence[int] | None = None, usecols=None, dtype: DtypeArg | None = None, skiprows: Sequence[int] | int | Callable[[int], object] | None = None, nrows: int | None = None, true_values: Iterable[Hashable] | None = None, false_values: Iterable[Hashable] | None = None, na_values=None, parse_dates: list | dict | bool = False, date_format: dict[Hashable, str] | str | None = None, thousands: str | None = None, decimal: str = ".", comment: str | None = None, skipfooter: int = 0, dtype_backend: DtypeBackend | lib.NoDefault = lib.no_default, **kwds, ): is_list_header = False is_len_one_list_header = False if is_list_like(header): assert isinstance(header, Sequence) is_list_header = True if len(header) == 1: is_len_one_list_header = True
if is_len_one_list_header: header = cast(Sequence[int], header)[0]
# forward fill and pull out names for MultiIndex column header_names = None if header is not None and is_list_like(header): assert isinstance(header, Sequence)
header_names = [] control_row = [True] * len(data[0])
for row in header: if is_integer(skiprows): assert isinstance(skiprows, int) row += skiprows
if row > len(data) - 1: raise ValueError( f"header index {row} exceeds maximum index " f"{len(data) - 1} of data.", )
data[row], control_row = fill_mi_header(data[row], control_row)
if index_col is not None: header_name, _ = pop_header_name(data[row], index_col) header_names.append(header_name)
# If there is a MultiIndex header and an index then there is also # a row containing just the index name(s) has_index_names = False if is_list_header and not is_len_one_list_header and index_col is not None: index_col_set: set[int] if isinstance(index_col, int): index_col_set = {index_col} else: assert isinstance(index_col, Sequence) index_col_set = set(index_col)
# We have to handle mi without names. If any of the entries in the data # columns are not empty, this is a regular row assert isinstance(header, Sequence) if len(header) < len(data): potential_index_names = data[len(header)] has_index_names = all( x == "" or x is None for i, x in enumerate(potential_index_names) if not control_row[i] and i not in index_col_set )
if is_list_like(index_col): # Forward fill values for MultiIndex index. if header is None: offset = 0 elif isinstance(header, int): offset = 1 + header else: offset = 1 + max(header)
# GH34673: if MultiIndex names present and not defined in the header, # offset needs to be incremented so that forward filling starts # from the first MI value instead of the name if has_index_names: offset += 1
# Check if we have an empty dataset # before trying to collect data. if offset < len(data): assert isinstance(index_col, Sequence)
for col in index_col: last = data[offset][col]
for row in range(offset + 1, len(data)): if data[row][col] == "" or data[row][col] is None: data[row][col] = last else: last = data[row][col]
# GH 12292 : error when read one empty column from excel file try: parser = TextParser( data, names=names, header=header, index_col=index_col, has_index_names=has_index_names, dtype=dtype, true_values=true_values, false_values=false_values, skiprows=skiprows, nrows=nrows, na_values=na_values, skip_blank_lines=False, # GH 39808 parse_dates=parse_dates, date_format=date_format, thousands=thousands, decimal=decimal, comment=comment, skipfooter=skipfooter, usecols=usecols, dtype_backend=dtype_backend, **kwds, )
output[asheetname] = parser.read(nrows=nrows)
if header_names: output[asheetname].columns = output[asheetname].columns.set_names( header_names )
except EmptyDataError: # No Data, return an empty DataFrame output[asheetname] = DataFrame()
except Exception as err: err.args = (f"{err.args[0]} (sheet: {asheetname})", *err.args[1:]) raise err
return output
@set_module("pandas")class ExcelWriter(Generic[_WorkbookT]): """ Class for writing DataFrame objects into excel sheets.
Default is to use:
* `xlsxwriter <https://pypi.org/project/XlsxWriter/>`__ for xlsx files if xlsxwriter is installed otherwise `openpyxl <https://pypi.org/project/openpyxl/>`__ * `odf <https://pypi.org/project/odfpy/>`__ for ods files
See :meth:`DataFrame.to_excel` for typical usage.
The writer should be used as a context manager. Otherwise, call `close()` to save and close any opened file handles.
Parameters ---------- path : str or typing.BinaryIO Path to xls or xlsx or ods file. engine : str (optional) Engine to use for writing. If None, defaults to ``io.excel.<extension>.writer``. NOTE: can only be passed as a keyword argument. date_format : str, default None Format string for dates written into Excel files (e.g. 'YYYY-MM-DD'). datetime_format : str, default None Format string for datetime objects written into Excel files. (e.g. 'YYYY-MM-DD HH:MM:SS'). mode : {'w', 'a'}, default 'w' File mode to use (write or append). Append does not work with fsspec URLs. storage_options : dict, optional 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.request.Request`` as header options. For other URLs (e.g. starting with "s3://", and "gcs://") the key-value pairs are forwarded to ``fsspec.open``. Please see ``fsspec`` and ``urllib`` for more details, and for more examples on storage options refer `here <https://pandas.pydata.org/docs/user_guide/io.html? highlight=storage_options#reading-writing-remote-files>`_.
if_sheet_exists : {'error', 'new', 'replace', 'overlay'}, default 'error' How to behave when trying to write to a sheet that already exists (append mode only).
* error: raise a ValueError. * new: Create a new sheet, with a name determined by the engine. * replace: Delete the contents of the sheet before writing to it. * overlay: Write contents to the existing sheet without first removing, but possibly over top of, the existing contents.
engine_kwargs : dict, optional Keyword arguments to be passed into the engine. These will be passed to the following functions of the respective engines:
* xlsxwriter: ``xlsxwriter.Workbook(file, **engine_kwargs)`` * openpyxl (write mode): ``openpyxl.Workbook(**engine_kwargs)`` * openpyxl (append mode): ``openpyxl.load_workbook(file, **engine_kwargs)`` * odf: ``odf.opendocument.OpenDocumentSpreadsheet(**engine_kwargs)``
See Also -------- read_excel : Read an Excel sheet values (xlsx) file into DataFrame. read_csv : Read a comma-separated values (csv) file into DataFrame. read_fwf : Read a table of fixed-width formatted lines into DataFrame.
Notes ----- For compatibility with CSV writers, ExcelWriter serializes lists and dicts to strings before writing.
Examples -------- Default usage:
>>> df = pd.DataFrame([["ABC", "XYZ"]], columns=["Foo", "Bar"]) # doctest: +SKIP >>> with pd.ExcelWriter("path_to_file.xlsx") as writer: ... df.to_excel(writer) # doctest: +SKIP
To write to separate sheets in a single file:
>>> df1 = pd.DataFrame([["AAA", "BBB"]], columns=["Spam", "Egg"]) # doctest: +SKIP >>> df2 = pd.DataFrame([["ABC", "XYZ"]], columns=["Foo", "Bar"]) # doctest: +SKIP >>> with pd.ExcelWriter("path_to_file.xlsx") as writer: ... df1.to_excel(writer, sheet_name="Sheet1") # doctest: +SKIP ... df2.to_excel(writer, sheet_name="Sheet2") # doctest: +SKIP
You can set the date format or datetime format:
>>> from datetime import date, datetime # doctest: +SKIP >>> df = pd.DataFrame( ... [ ... [date(2014, 1, 31), date(1999, 9, 24)], ... [datetime(1998, 5, 26, 23, 33, 4), datetime(2014, 2, 28, 13, 5, 13)], ... ], ... index=["Date", "Datetime"], ... columns=["X", "Y"], ... ) # doctest: +SKIP >>> with pd.ExcelWriter( ... "path_to_file.xlsx", ... date_format="YYYY-MM-DD", ... datetime_format="YYYY-MM-DD HH:MM:SS", ... ) as writer: ... df.to_excel(writer) # doctest: +SKIP
You can also append to an existing Excel file:
>>> with pd.ExcelWriter("path_to_file.xlsx", mode="a", engine="openpyxl") as writer: ... df.to_excel(writer, sheet_name="Sheet3") # doctest: +SKIP
Here, the `if_sheet_exists` parameter can be set to replace a sheet if it already exists:
>>> with pd.ExcelWriter( ... "path_to_file.xlsx", ... mode="a", ... engine="openpyxl", ... if_sheet_exists="replace", ... ) as writer: ... df.to_excel(writer, sheet_name="Sheet1") # doctest: +SKIP
You can also write multiple DataFrames to a single sheet. Note that the ``if_sheet_exists`` parameter needs to be set to ``overlay``:
>>> with pd.ExcelWriter( ... "path_to_file.xlsx", ... mode="a", ... engine="openpyxl", ... if_sheet_exists="overlay", ... ) as writer: ... df1.to_excel(writer, sheet_name="Sheet1") ... df2.to_excel(writer, sheet_name="Sheet1", startcol=3) # doctest: +SKIP
You can store Excel file in RAM:
>>> import io >>> df = pd.DataFrame([["ABC", "XYZ"]], columns=["Foo", "Bar"]) >>> buffer = io.BytesIO() >>> with pd.ExcelWriter(buffer) as writer: ... df.to_excel(writer)
You can pack Excel file into zip archive:
>>> import zipfile # doctest: +SKIP >>> df = pd.DataFrame([["ABC", "XYZ"]], columns=["Foo", "Bar"]) # doctest: +SKIP >>> with zipfile.ZipFile("path_to_file.zip", "w") as zf: ... with zf.open("filename.xlsx", "w") as buffer: ... with pd.ExcelWriter(buffer) as writer: ... df.to_excel(writer) # doctest: +SKIP
You can specify additional arguments to the underlying engine:
>>> with pd.ExcelWriter( ... "path_to_file.xlsx", ... engine="xlsxwriter", ... engine_kwargs={"options": {"nan_inf_to_errors": True}}, ... ) as writer: ... df.to_excel(writer) # doctest: +SKIP
In append mode, ``engine_kwargs`` are passed through to openpyxl's ``load_workbook``:
>>> with pd.ExcelWriter( ... "path_to_file.xlsx", ... engine="openpyxl", ... mode="a", ... engine_kwargs={"keep_vba": True}, ... ) as writer: ... df.to_excel(writer, sheet_name="Sheet2") # doctest: +SKIP """
# Defining an ExcelWriter implementation (see abstract methods for more...)
# - Mandatory # - ``write_cells(self, cells, sheet_name=None, startrow=0, startcol=0)`` # --> called to write additional DataFrames to disk # - ``_supported_extensions`` (tuple of supported extensions), used to # check that engine supports the given extension. # - ``_engine`` - string that gives the engine name. Necessary to # instantiate class directly and bypass ``ExcelWriterMeta`` engine # lookup. # - ``save(self)`` --> called to save file to disk # - Mostly mandatory (i.e. should at least exist) # - book, cur_sheet, path
# - Optional: # - ``__init__(self, path, engine=None, **kwargs)`` --> always called # with path as first argument.
# You also need to register the class with ``register_writer()``. # Technically, ExcelWriter implementations don't need to subclass # ExcelWriter.
_engine: str _supported_extensions: tuple[str, ...]
def __new__( cls, path: FilePath | WriteExcelBuffer | ExcelWriter, engine: str | None = None, date_format: str | None = None, datetime_format: str | None = None, mode: str = "w", storage_options: StorageOptions | None = None, if_sheet_exists: ExcelWriterIfSheetExists | None = None, engine_kwargs: dict | None = None, ) -> Self: # only switch class if generic(ExcelWriter) if cls is ExcelWriter: if engine is None or (isinstance(engine, str) and engine == "auto"): if isinstance(path, str): ext = os.path.splitext(path)[-1][1:] else: ext = "xlsx"
try: engine = config.get_option(f"io.excel.{ext}.writer") if engine == "auto": engine = get_default_engine(ext, mode="writer") except KeyError as err: raise ValueError(f"No engine for filetype: '{ext}'") from err
# for mypy assert engine is not None # error: Incompatible types in assignment (expression has type # "type[ExcelWriter[Any]]", variable has type "type[Self]") cls = get_writer(engine) # type: ignore[assignment]
return object.__new__(cls)
@property def supported_extensions(self) -> tuple[str, ...]: """Extensions that writer engine supports.""" return self._supported_extensions
@property def engine(self) -> str: """Name of engine.""" return self._engine
@property def sheets(self) -> dict[str, Any]: """Mapping of sheet names to sheet objects.""" raise NotImplementedError
@property def book(self) -> _WorkbookT: """ Book instance. Class type will depend on the engine used.
This attribute can be used to access engine-specific features. """ raise NotImplementedError
def _write_cells( self, cells, sheet_name: str | None = None, startrow: int = 0, startcol: int = 0, freeze_panes: tuple[int, int] | None = None, autofilter_range: str | None = None, ) -> None: """ Write given formatted cells into Excel an excel sheet
Parameters ---------- cells : generator cell of formatted data to save to Excel sheet sheet_name : str, default None Name of Excel sheet, if None, then use self.cur_sheet startrow : upper left cell row to dump data frame startcol : upper left cell column to dump data frame freeze_panes: int tuple of length 2 contains the bottom-most row and right-most column to freeze autofilter_range: str, default None column ranges to add automatic filters to, for example "A1:D5" """ raise NotImplementedError
def _save(self) -> None: """ Save workbook to disk. """ raise NotImplementedError
def __init__( self, path: FilePath | WriteExcelBuffer | ExcelWriter, engine: str | None = None, date_format: str | None = None, datetime_format: str | None = None, mode: str = "w", storage_options: StorageOptions | None = None, if_sheet_exists: ExcelWriterIfSheetExists | None = None, engine_kwargs: dict[str, Any] | None = None, ) -> None: # validate that this engine can handle the extension if isinstance(path, str): ext = os.path.splitext(path)[-1] self.check_extension(ext)
# use mode to open the file if "b" not in mode: mode += "b" # use "a" for the user to append data to excel but internally use "r+" to let # the excel backend first read the existing file and then write any data to it mode = mode.replace("a", "r+")
if if_sheet_exists not in (None, "error", "new", "replace", "overlay"): raise ValueError( f"'{if_sheet_exists}' is not valid for if_sheet_exists. " "Valid options are 'error', 'new', 'replace' and 'overlay'." ) if if_sheet_exists and "r+" not in mode: raise ValueError("if_sheet_exists is only valid in append mode (mode='a')") if if_sheet_exists is None: if_sheet_exists = "error" self._if_sheet_exists = if_sheet_exists
# cast ExcelWriter to avoid adding 'if self._handles is not None' self._handles = IOHandles( cast(IO[bytes], path), compression={"compression": None} ) if not isinstance(path, ExcelWriter): self._handles = get_handle( path, mode, storage_options=storage_options, is_text=False ) self._cur_sheet = None
if date_format is None: self._date_format = "YYYY-MM-DD" else: self._date_format = date_format if datetime_format is None: self._datetime_format = "YYYY-MM-DD HH:MM:SS" else: self._datetime_format = datetime_format
self._mode = mode
@property def date_format(self) -> str: """ Format string for dates written into Excel files (e.g. 'YYYY-MM-DD'). """ return self._date_format
@property def datetime_format(self) -> str: """ Format string for dates written into Excel files (e.g. 'YYYY-MM-DD'). """ return self._datetime_format
@property def if_sheet_exists(self) -> str: """ How to behave when writing to a sheet that already exists in append mode. """ return self._if_sheet_exists
def __fspath__(self) -> str: return getattr(self._handles.handle, "name", "")
def _get_sheet_name(self, sheet_name: str | None) -> str: if sheet_name is None: sheet_name = self._cur_sheet if sheet_name is None: # pragma: no cover raise ValueError("Must pass explicit sheet_name or set _cur_sheet property") return sheet_name
def _value_with_fmt( self, val ) -> tuple[ int | float | bool | str | datetime.datetime | datetime.date, str | None ]: """ Convert numpy types to Python types for the Excel writers.
Parameters ---------- val : object Value to be written into cells
Returns ------- Tuple with the first element being the converted value and the second being an optional format """ fmt = None
if is_integer(val): val = int(val) elif is_float(val): val = float(val) elif is_bool(val): val = bool(val) elif is_decimal(val): val = Decimal(val) elif isinstance(val, datetime.datetime): fmt = self._datetime_format elif isinstance(val, datetime.date): fmt = self._date_format elif isinstance(val, datetime.timedelta): val = val.total_seconds() / 86400 fmt = "0" else: val = str(val) # GH#56954 # Excel's limitation on cell contents is 32767 characters # xref https://support.microsoft.com/en-au/office/excel-specifications-and-limits-1672b34d-7043-467e-8e27-269d656771c3 if len(val) > 32767: warnings.warn( f"Cell contents too long ({len(val)}), " "truncated to 32767 characters", UserWarning, stacklevel=find_stack_level(), ) return val, fmt
@classmethod def check_extension(cls, ext: str) -> Literal[True]: """ checks that path's extension against the Writer's supported extensions. If it isn't supported, raises UnsupportedFiletypeError. """ if ext.startswith("."): ext = ext[1:] if not any(ext in extension for extension in cls._supported_extensions): raise ValueError(f"Invalid extension for engine '{cls.engine}': '{ext}'") return True
# Allow use as a contextmanager def __enter__(self) -> Self: return self
def __exit__( self, exc_type: type[BaseException] | None, exc_value: BaseException | None, traceback: TracebackType | None, ) -> None: self.close()
def close(self) -> None: """synonym for save, to make it more file-like""" self._save() self._handles.close()
XLS_SIGNATURES = ( b"\x09\x00\x04\x00\x07\x00\x10\x00", # BIFF2 b"\x09\x02\x06\x00\x00\x00\x10\x00", # BIFF3 b"\x09\x04\x06\x00\x00\x00\x10\x00", # BIFF4 b"\xd0\xcf\x11\xe0\xa1\xb1\x1a\xe1", # Compound File Binary)ZIP_SIGNATURE = b"PK\x03\x04"PEEK_SIZE = max(map(len, (*XLS_SIGNATURES, ZIP_SIGNATURE)))
def inspect_excel_format( content_or_path: FilePath | ReadBuffer[bytes], storage_options: StorageOptions | None = None,) -> str | None: """ Inspect the path or content of an excel file and get its format.
Adopted from xlrd: https://github.com/python-excel/xlrd.
Parameters ---------- content_or_path : str or file-like object Path to file or content of file to inspect. May be a URL. storage_options : dict, optional 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.request.Request`` as header options. For other URLs (e.g. starting with "s3://", and "gcs://") the key-value pairs are forwarded to ``fsspec.open``. Please see ``fsspec`` and ``urllib`` for more details, and for more examples on storage options refer `here <https://pandas.pydata.org/docs/user_guide/io.html? highlight=storage_options#reading-writing-remote-files>`_.
Returns ------- str or None Format of file if it can be determined.
Raises ------ ValueError If resulting stream is empty. BadZipFile If resulting stream does not have an XLS signature and is not a valid zipfile. """ with get_handle( content_or_path, "rb", storage_options=storage_options, is_text=False ) as handle: stream = handle.handle stream.seek(0) buf = stream.read(PEEK_SIZE) if buf is None: raise ValueError("stream is empty") assert isinstance(buf, bytes) peek = buf stream.seek(0)
if any(peek.startswith(sig) for sig in XLS_SIGNATURES): return "xls" elif not peek.startswith(ZIP_SIGNATURE): return None
with zipfile.ZipFile(stream) as zf: # Workaround for some third party files that use forward slashes and # lower case names. component_names = { name.replace("\\", "/").lower() for name in zf.namelist() }
if "xl/workbook.xml" in component_names: return "xlsx" if "xl/workbook.bin" in component_names: return "xlsb" if "content.xml" in component_names: return "ods" return "zip"
@set_module("pandas")class ExcelFile: """ Class for parsing tabular Excel sheets into DataFrame objects.
See read_excel for more documentation.
Parameters ---------- path_or_buffer : str, bytes, pathlib.Path, A file-like object, xlrd workbook or openpyxl workbook. If a string or path object, expected to be a path to a .xls, .xlsx, .xlsb, .xlsm, .odf, .ods, or .odt file. engine : str, default None If io is not a buffer or path, this must be set to identify io. Supported engines: ``xlrd``, ``openpyxl``, ``odf``, ``pyxlsb``, ``calamine`` Engine compatibility :
- ``xlrd`` supports old-style Excel files (.xls). - ``openpyxl`` supports newer Excel file formats. - ``odf`` supports OpenDocument file formats (.odf, .ods, .odt). - ``pyxlsb`` supports Binary Excel files. - ``calamine`` supports Excel (.xls, .xlsx, .xlsm, .xlsb) and OpenDocument (.ods) file formats.
The engine `xlrd <https://xlrd.readthedocs.io/en/latest/>`_ now only supports old-style ``.xls`` files. When ``engine=None``, the following logic will be used to determine the engine:
- If ``path_or_buffer`` is an OpenDocument format (.odf, .ods, .odt), then `odf <https://pypi.org/project/odfpy/>`_ will be used. - Otherwise if ``path_or_buffer`` is an xls format, ``xlrd`` will be used. - Otherwise if ``path_or_buffer`` is in xlsb format, `pyxlsb <https://pypi.org/project/pyxlsb/>`_ will be used. - Otherwise if `openpyxl <https://pypi.org/project/openpyxl/>`_ is installed, then ``openpyxl`` will be used. - Otherwise if ``xlrd >= 2.0`` is installed, a ``ValueError`` will be raised.
.. warning::
Please do not report issues when using ``xlrd`` to read ``.xlsx`` files. This is not supported, switch to using ``openpyxl`` instead. storage_options : dict, optional 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.request.Request`` as header options. For other URLs (e.g. starting with "s3://", and "gcs://") the key-value pairs are forwarded to ``fsspec.open``. Please see ``fsspec`` and ``urllib`` for more details, and for more examples on storage options refer `here <https://pandas.pydata.org/docs/user_guide/io.html? highlight=storage_options#reading-writing-remote-files>`_. engine_kwargs : dict, optional Arbitrary keyword arguments passed to excel engine.
See Also -------- DataFrame.to_excel : Write DataFrame to an Excel file. DataFrame.to_csv : Write DataFrame to a comma-separated values (csv) file. read_csv : Read a comma-separated values (csv) file into DataFrame. read_fwf : Read a table of fixed-width formatted lines into DataFrame.
Examples -------- >>> file = pd.ExcelFile("myfile.xlsx") # doctest: +SKIP >>> with pd.ExcelFile("myfile.xls") as xls: # doctest: +SKIP ... df1 = pd.read_excel(xls, "Sheet1") # doctest: +SKIP """
from pandas.io.excel._calamine import CalamineReader from pandas.io.excel._odfreader import ODFReader from pandas.io.excel._openpyxl import OpenpyxlReader from pandas.io.excel._pyxlsb import PyxlsbReader from pandas.io.excel._xlrd import XlrdReader
_engines: Mapping[str, Any] = { "xlrd": XlrdReader, "openpyxl": OpenpyxlReader, "odf": ODFReader, "pyxlsb": PyxlsbReader, "calamine": CalamineReader, }
def __init__( self, path_or_buffer, engine: str | None = None, storage_options: StorageOptions | None = None, engine_kwargs: dict | None = None, ) -> None: if engine_kwargs is None: engine_kwargs = {}
if engine is not None and engine not in self._engines: raise ValueError(f"Unknown engine: {engine}")
# Always a string self._io = stringify_path(path_or_buffer)
if engine is None: # Only determine ext if it is needed ext: str | None = None
if not isinstance( path_or_buffer, (str, os.PathLike, ExcelFile) ) and not is_file_like(path_or_buffer): # GH#56692 - avoid importing xlrd if possible if import_optional_dependency("xlrd", errors="ignore") is None: xlrd_version = None else: import xlrd
xlrd_version = Version(get_version(xlrd))
if xlrd_version is not None and isinstance(path_or_buffer, xlrd.Book): ext = "xls"
if ext is None: ext = inspect_excel_format( content_or_path=path_or_buffer, storage_options=storage_options ) if ext is None: raise ValueError( "Excel file format cannot be determined, you must specify " "an engine manually." )
engine = config.get_option(f"io.excel.{ext}.reader") if engine == "auto": engine = get_default_engine(ext, mode="reader")
assert engine is not None self.engine = engine self.storage_options = storage_options
self._reader = self._engines[engine]( self._io, storage_options=storage_options, engine_kwargs=engine_kwargs, )
def __fspath__(self): return self._io
def parse( self, sheet_name: str | int | list[int] | list[str] | None = 0, header: int | Sequence[int] | None = 0, names: SequenceNotStr[Hashable] | range | None = None, index_col: int | Sequence[int] | None = None, usecols=None, converters=None, true_values: Iterable[Hashable] | None = None, false_values: Iterable[Hashable] | None = None, skiprows: Sequence[int] | int | Callable[[int], object] | None = None, nrows: int | None = None, na_values=None, parse_dates: list | dict | bool = False, date_format: str | dict[Hashable, str] | None = None, thousands: str | None = None, comment: str | None = None, skipfooter: int = 0, dtype_backend: DtypeBackend | lib.NoDefault = lib.no_default, **kwds, ) -> DataFrame | dict[str, DataFrame] | dict[int, DataFrame]: """ Parse specified sheet(s) into a DataFrame.
Equivalent to read_excel(ExcelFile, ...) See the read_excel docstring for more info on accepted parameters.
Parameters ---------- sheet_name : str, int, list, or None, default 0 Strings are used for sheet names. Integers are used in zero-indexed sheet positions (chart sheets do not count as a sheet position). Lists of strings/integers are used to request multiple sheets. When ``None``, will return a dictionary containing DataFrames for each sheet. header : int, list of int, default 0 Row (0-indexed) to use for the column labels of the parsed DataFrame. If a list of integers is passed those row positions will be combined into a ``MultiIndex``. Use None if there is no header. names : array-like, default None List of column names to use. If file contains no header row, then you should explicitly pass header=None. index_col : int, str, list of int, default None Column (0-indexed) to use as the row labels of the DataFrame. Pass None if there is no such column. If a list is passed, those columns will be combined into a ``MultiIndex``. If a subset of data is selected with ``usecols``, index_col is based on the subset.
Missing values will be forward filled to allow roundtripping with ``to_excel`` for ``merged_cells=True``. To avoid forward filling the missing values use ``set_index`` after reading the data instead of ``index_col``. usecols : str, list-like, or callable, default None * If None, then parse all columns. * If str, then indicates comma separated list of Excel column letters and column ranges (e.g. "A:E" or "A,C,E:F"). Ranges are inclusive of both sides. * If list of int, then indicates list of column numbers to be parsed (0-indexed). * If list of string, then indicates list of column names to be parsed. * If callable, then evaluate each column name against it and parse the column if the callable returns ``True``.
Returns a subset of the columns according to behavior above. converters : dict, default None Dict of functions for converting values in certain columns. Keys can either be integers or column labels, values are functions that take one input argument, the Excel cell content, and return the transformed content. true_values : list, default None Values to consider as True. false_values : list, default None Values to consider as False. skiprows : list-like, int, or callable, optional Line numbers to skip (0-indexed) or number of lines to skip (int) at the start of the file. If callable, the callable function will be evaluated against the row indices, returning True if the row should be skipped and False otherwise. An example of a valid callable argument would be ``lambda x: x in [0, 2]``. nrows : int, default None Number of rows to parse. na_values : scalar, str, list-like, or dict, default None Additional strings to recognize as NA/NaN. If dict passed, specific per-column NA values. parse_dates : bool, list-like, or dict, default False The behavior is as follows:
* ``bool``. If True -> try parsing the index. * ``list`` of int or names. e.g. If [1, 2, 3] -> try parsing columns 1, 2, 3 each as a separate date column. * ``list`` of lists. e.g. If [[1, 3]] -> combine columns 1 and 3 and parse as a single date column. * ``dict``, e.g. {'foo' : [1, 3]} -> parse columns 1, 3 as date and call result 'foo'
If a column or index contains an unparsable date, the entire column or index will be returned unaltered as an object data type. If you don`t want to parse some cells as date just change their type in Excel to "Text".For non-standard datetime parsing, use ``pd.to_datetime`` after ``pd.read_excel``.
Note: A fast-path exists for iso8601-formatted dates. date_format : str or dict of column -> format, default ``None`` If used in conjunction with ``parse_dates``, will parse dates according to this format. For anything more complex, please read in as ``object`` and then apply :func:`to_datetime` as-needed. thousands : str, default None Thousands separator for parsing string columns to numeric. Note that this parameter is only necessary for columns stored as TEXT in Excel, any numeric columns will automatically be parsed, regardless of display format. comment : str, default None Comments out remainder of line. Pass a character or characters to this argument to indicate comments in the input file. Any data between the comment string and the end of the current line is ignored. skipfooter : int, default 0 Rows at the end to skip (0-indexed). dtype_backend : {'numpy_nullable', 'pyarrow'} Back-end data type applied to the resultant :class:`DataFrame` (still experimental). If not specified, the default behavior is to not use nullable data types. If specified, the behavior is as follows:
* ``"numpy_nullable"``: returns nullable-dtype-backed :class:`DataFrame` * ``"pyarrow"``: returns pyarrow-backed nullable :class:`ArrowDtype` :class:`DataFrame`
.. versionadded:: 2.0 **kwds : dict, optional Arbitrary keyword arguments passed to excel engine.
Returns ------- DataFrame or dict of DataFrames DataFrame from the passed in Excel file.
See Also -------- read_excel : Read an Excel sheet values (xlsx) file into DataFrame. read_csv : Read a comma-separated values (csv) file into DataFrame. read_fwf : Read a table of fixed-width formatted lines into DataFrame.
Examples -------- >>> df = pd.DataFrame([[1, 2, 3], [4, 5, 6]], columns=["A", "B", "C"]) >>> df.to_excel("myfile.xlsx") # doctest: +SKIP >>> file = pd.ExcelFile("myfile.xlsx") # doctest: +SKIP >>> file.parse() # doctest: +SKIP """ return self._reader.parse( sheet_name=sheet_name, header=header, names=names, index_col=index_col, usecols=usecols, converters=converters, true_values=true_values, false_values=false_values, skiprows=skiprows, nrows=nrows, na_values=na_values, parse_dates=parse_dates, date_format=date_format, thousands=thousands, comment=comment, skipfooter=skipfooter, dtype_backend=dtype_backend, **kwds, )
@property def book(self): """ Gets the Excel workbook.
Workbook is the top-level container for all document information.
Returns ------- Excel Workbook The workbook object of the type defined by the engine being used.
See Also -------- read_excel : Read an Excel file into a pandas DataFrame.
Examples -------- >>> file = pd.ExcelFile("myfile.xlsx") # doctest: +SKIP >>> file.book # doctest: +SKIP <openpyxl.workbook.workbook.Workbook object at 0x11eb5ad70> >>> file.book.path # doctest: +SKIP '/xl/workbook.xml' >>> file.book.active # doctest: +SKIP <openpyxl.worksheet._read_only.ReadOnlyWorksheet object at 0x11eb5b370> >>> file.book.sheetnames # doctest: +SKIP ['Sheet1', 'Sheet2'] """ return self._reader.book
@property def sheet_names(self): """ Names of the sheets in the document.
This is particularly useful for loading a specific sheet into a DataFrame when you do not know the sheet names beforehand.
Returns ------- list of str List of sheet names in the document.
See Also -------- ExcelFile.parse : Parse a sheet into a DataFrame. read_excel : Read an Excel file into a pandas DataFrame. If you know the sheet names, it may be easier to specify them directly to read_excel.
Examples -------- >>> file = pd.ExcelFile("myfile.xlsx") # doctest: +SKIP >>> file.sheet_names # doctest: +SKIP ["Sheet1", "Sheet2"] """ return self._reader.sheet_names
def close(self) -> None: """close io if necessary""" self._reader.close()
def __enter__(self) -> Self: return self
def __exit__( self, exc_type: type[BaseException] | None, exc_value: BaseException | None, traceback: TracebackType | None, ) -> None: self.close()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129from __future__ import annotations
from datetime import ( date, datetime, time, timedelta,)from typing import ( TYPE_CHECKING, Any, TypeAlias,)
from pandas.compat._optional import import_optional_dependency
from pandas.io.excel._base import BaseExcelReader
if TYPE_CHECKING: from python_calamine import ( CalamineSheet, CalamineWorkbook, )
from pandas._typing import ( FilePath, NaTType, ReadBuffer, Scalar, StorageOptions, )
_CellValue: TypeAlias = int | float | str | bool | time | date | datetime | timedelta
class CalamineReader(BaseExcelReader["CalamineWorkbook"]): def __init__( self, filepath_or_buffer: FilePath | ReadBuffer[bytes], storage_options: StorageOptions | None = None, engine_kwargs: dict | None = None, ) -> None: """ Reader using calamine engine (xlsx/xls/xlsb/ods).
Parameters ---------- filepath_or_buffer : str, path to be parsed or an open readable stream. storage_options : dict, optional 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.request.Request`` as header options. For other URLs (e.g. starting with "s3://", and "gcs://") the key-value pairs are forwarded to ``fsspec.open``. Please see ``fsspec`` and ``urllib`` for more details, and for more examples on storage options refer `here <https://pandas.pydata.org/docs/user_guide/io.html? highlight=storage_options#reading-writing-remote-files>`_. engine_kwargs : dict, optional Arbitrary keyword arguments passed to excel engine. """ import_optional_dependency("python_calamine") super().__init__( filepath_or_buffer, storage_options=storage_options, engine_kwargs=engine_kwargs, )
@property def _workbook_class(self) -> type[CalamineWorkbook]: from python_calamine import CalamineWorkbook
return CalamineWorkbook
def load_workbook( self, filepath_or_buffer: FilePath | ReadBuffer[bytes], engine_kwargs: Any ) -> CalamineWorkbook: from python_calamine import load_workbook
return load_workbook( filepath_or_buffer, **engine_kwargs, )
@property def sheet_names(self) -> list[str]: from python_calamine import SheetTypeEnum
return [ sheet.name for sheet in self.book.sheets_metadata if sheet.typ == SheetTypeEnum.WorkSheet ]
def get_sheet_by_name(self, name: str) -> CalamineSheet: self.raise_if_bad_sheet_by_name(name) return self.book.get_sheet_by_name(name)
def get_sheet_by_index(self, index: int) -> CalamineSheet: self.raise_if_bad_sheet_by_index(index) return self.book.get_sheet_by_index(index)
def get_sheet_data( self, sheet: CalamineSheet, file_rows_needed: int | None = None ) -> list[list[Scalar | NaTType | time]]: def _convert_cell(value: _CellValue) -> Scalar | NaTType | time: if isinstance(value, float): val = int(value) if val == value: return val else: return value elif isinstance(value, (datetime, timedelta)): # Return as-is to match openpyxl behavior (GH#59186) return value elif isinstance(value, date): # Convert date to datetime to match openpyxl behavior (GH#59186) return datetime(value.year, value.month, value.day) elif isinstance(value, time): return value
return value
rows: list[list[_CellValue]] = sheet.to_python( skip_empty_area=False, nrows=file_rows_needed ) data = [[_convert_cell(cell) for cell in row] for row in rows]
return data123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249from __future__ import annotations
from typing import ( TYPE_CHECKING, cast,)
import numpy as np
from pandas._typing import ( FilePath, ReadBuffer, Scalar, StorageOptions,)from pandas.compat._optional import import_optional_dependencyfrom pandas.util._decorators import doc
import pandas as pdfrom pandas.core.shared_docs import _shared_docs
from pandas.io.excel._base import BaseExcelReader
if TYPE_CHECKING: from odf.opendocument import OpenDocument
from pandas._libs.tslibs.nattype import NaTType
@doc(storage_options=_shared_docs["storage_options"])class ODFReader(BaseExcelReader["OpenDocument"]): def __init__( self, filepath_or_buffer: FilePath | ReadBuffer[bytes], storage_options: StorageOptions | None = None, engine_kwargs: dict | None = None, ) -> None: """ Read tables out of OpenDocument formatted files.
Parameters ---------- filepath_or_buffer : str, path to be parsed or an open readable stream. {storage_options} engine_kwargs : dict, optional Arbitrary keyword arguments passed to excel engine. """ import_optional_dependency("odf") super().__init__( filepath_or_buffer, storage_options=storage_options, engine_kwargs=engine_kwargs, )
@property def _workbook_class(self) -> type[OpenDocument]: from odf.opendocument import OpenDocument
return OpenDocument
def load_workbook( self, filepath_or_buffer: FilePath | ReadBuffer[bytes], engine_kwargs ) -> OpenDocument: from odf.opendocument import load
return load(filepath_or_buffer, **engine_kwargs)
@property def empty_value(self) -> str: """Property for compat with other readers.""" return ""
@property def sheet_names(self) -> list[str]: """Return a list of sheet names present in the document""" from odf.table import Table
tables = self.book.getElementsByType(Table) return [t.getAttribute("name") for t in tables]
def get_sheet_by_index(self, index: int): from odf.table import Table
self.raise_if_bad_sheet_by_index(index) tables = self.book.getElementsByType(Table) return tables[index]
def get_sheet_by_name(self, name: str): from odf.table import Table
self.raise_if_bad_sheet_by_name(name) tables = self.book.getElementsByType(Table)
for table in tables: if table.getAttribute("name") == name: return table
self.close() raise ValueError(f"sheet {name} not found")
def get_sheet_data( self, sheet, file_rows_needed: int | None = None ) -> list[list[Scalar | NaTType]]: """ Parse an ODF Table into a list of lists """ from odf.table import ( CoveredTableCell, TableCell, TableRow, )
covered_cell_name = CoveredTableCell().qname table_cell_name = TableCell().qname cell_names = {covered_cell_name, table_cell_name}
sheet_rows = sheet.getElementsByType(TableRow) empty_rows = 0 max_row_len = 0
table: list[list[Scalar | NaTType]] = []
for sheet_row in sheet_rows: empty_cells = 0 table_row: list[Scalar | NaTType] = []
for sheet_cell in sheet_row.childNodes: if hasattr(sheet_cell, "qname") and sheet_cell.qname in cell_names: if sheet_cell.qname == table_cell_name: value = self._get_cell_value(sheet_cell) else: value = self.empty_value
column_repeat = self._get_column_repeat(sheet_cell)
# Queue up empty values, writing only if content succeeds them if value == self.empty_value: empty_cells += column_repeat else: table_row.extend([self.empty_value] * empty_cells) empty_cells = 0 table_row.extend([value] * column_repeat)
if max_row_len < len(table_row): max_row_len = len(table_row)
row_repeat = self._get_row_repeat(sheet_row) if len(table_row) == 0: empty_rows += row_repeat else: # add blank rows to our table table.extend([[self.empty_value]] * empty_rows) empty_rows = 0 table.extend(table_row for _ in range(row_repeat)) if file_rows_needed is not None and len(table) >= file_rows_needed: break
# Make our table square for row in table: if len(row) < max_row_len: row.extend([self.empty_value] * (max_row_len - len(row)))
return table
def _get_row_repeat(self, row) -> int: """ Return number of times this row was repeated Repeating an empty row appeared to be a common way of representing sparse rows in the table. """ from odf.namespaces import TABLENS
return int(row.attributes.get((TABLENS, "number-rows-repeated"), 1))
def _get_column_repeat(self, cell) -> int: from odf.namespaces import TABLENS
return int(cell.attributes.get((TABLENS, "number-columns-repeated"), 1))
def _get_cell_value(self, cell) -> Scalar | NaTType: from odf.namespaces import OFFICENS
if str(cell) == "#N/A": return np.nan
cell_type = cell.attributes.get((OFFICENS, "value-type")) if cell_type == "boolean": if str(cell) == "TRUE": return True return False if cell_type is None: return self.empty_value elif cell_type == "float": # GH5394 cell_value = float(cell.attributes.get((OFFICENS, "value"))) val = int(cell_value) if val == cell_value: return val return cell_value elif cell_type == "percentage": cell_value = cell.attributes.get((OFFICENS, "value")) return float(cell_value) elif cell_type == "string": return self._get_cell_string_value(cell) elif cell_type == "currency": cell_value = cell.attributes.get((OFFICENS, "value")) return float(cell_value) elif cell_type == "date": cell_value = cell.attributes.get((OFFICENS, "date-value")) return pd.Timestamp(cell_value) elif cell_type == "time": stamp = pd.Timestamp(str(cell)) # cast needed here because Scalar doesn't include datetime.time return cast(Scalar, stamp.time()) else: self.close() raise ValueError(f"Unrecognized type {cell_type}")
def _get_cell_string_value(self, cell) -> str: """ Find and decode OpenDocument text:s tags that represent a run length encoded sequence of space characters. """ from odf.element import Element from odf.namespaces import TEXTNS from odf.office import Annotation from odf.text import S
office_annotation = Annotation().qname text_s = S().qname
value = []
for fragment in cell.childNodes: if isinstance(fragment, Element): if fragment.qname == text_s: spaces = int(fragment.attributes.get((TEXTNS, "c"), 1)) value.append(" " * spaces) elif fragment.qname == office_annotation: continue else: # recursive impl needed in case of nested fragments # with multiple spaces # https://github.com/pandas-dev/pandas/pull/36175#discussion_r484639704 value.append(self._get_cell_string_value(fragment)) else: value.append(str(fragment).strip("\n")) return "".join(value)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362from __future__ import annotations
from collections import defaultdictimport datetimeimport jsonfrom typing import ( TYPE_CHECKING, Any, DefaultDict, cast, overload,)
from pandas.io.excel._base import ExcelWriterfrom pandas.io.excel._util import ( combine_kwargs, validate_freeze_panes,)
if TYPE_CHECKING: from odf.opendocument import OpenDocumentSpreadsheet
from pandas._typing import ( ExcelWriterIfSheetExists, FilePath, StorageOptions, WriteExcelBuffer, )
from pandas.io.formats.excel import ExcelCell
class ODSWriter(ExcelWriter): _engine = "odf" _supported_extensions = (".ods",)
def __init__( # pyright: ignore[reportInconsistentConstructor] self, path: FilePath | WriteExcelBuffer | ExcelWriter, engine: str | None = None, date_format: str | None = None, datetime_format: str | None = None, mode: str = "w", storage_options: StorageOptions | None = None, if_sheet_exists: ExcelWriterIfSheetExists | None = None, engine_kwargs: dict[str, Any] | None = None, **kwargs: Any, ) -> None: from odf.opendocument import OpenDocumentSpreadsheet
if mode == "a": raise ValueError("Append mode is not supported with odf!")
engine_kwargs = combine_kwargs(engine_kwargs, kwargs) self._book = OpenDocumentSpreadsheet(**engine_kwargs)
super().__init__( path, mode=mode, storage_options=storage_options, if_sheet_exists=if_sheet_exists, engine_kwargs=engine_kwargs, )
self._style_dict: dict[str, str] = {}
@property def book(self) -> OpenDocumentSpreadsheet: """ Book instance of class odf.opendocument.OpenDocumentSpreadsheet.
This attribute can be used to access engine-specific features. """ return self._book
@property def sheets(self) -> dict[str, Any]: """Mapping of sheet names to sheet objects.""" from odf.table import Table
result = { sheet.getAttribute("name"): sheet for sheet in self.book.getElementsByType(Table) } return result
def _save(self) -> None: """ Save workbook to disk. """ for sheet in self.sheets.values(): self.book.spreadsheet.addElement(sheet) self.book.save(self._handles.handle)
def _write_cells( self, cells: list[ExcelCell], sheet_name: str | None = None, startrow: int = 0, startcol: int = 0, freeze_panes: tuple[int, int] | None = None, autofilter_range: str | None = None, ) -> None: """ Write the frame cells using odf """
if autofilter_range: raise ValueError("Autofilter is not supported with odf!")
from odf.table import ( Table, TableCell, TableRow, ) from odf.text import P
sheet_name = self._get_sheet_name(sheet_name) assert sheet_name is not None
if sheet_name in self.sheets: wks = self.sheets[sheet_name] else: wks = Table(name=sheet_name) self.book.spreadsheet.addElement(wks)
if validate_freeze_panes(freeze_panes): freeze_panes = cast(tuple[int, int], freeze_panes) self._create_freeze_panes(sheet_name, freeze_panes)
for _ in range(startrow): wks.addElement(TableRow())
rows: DefaultDict = defaultdict(TableRow) col_count: DefaultDict = defaultdict(int)
for cell in sorted(cells, key=lambda cell: (cell.row, cell.col)): # only add empty cells if the row is still empty if not col_count[cell.row]: for _ in range(startcol): rows[cell.row].addElement(TableCell())
# fill with empty cells if needed for _ in range(cell.col - col_count[cell.row]): rows[cell.row].addElement(TableCell()) col_count[cell.row] += 1
pvalue, tc = self._make_table_cell(cell) rows[cell.row].addElement(tc) col_count[cell.row] += 1 p = P(text=pvalue) tc.addElement(p)
# add all rows to the sheet if len(rows) > 0: for row_nr in range(max(rows.keys()) + 1): wks.addElement(rows[row_nr])
def _make_table_cell_attributes(self, cell: ExcelCell) -> dict[str, int | str]: """Convert cell attributes to OpenDocument attributes
Parameters ---------- cell : ExcelCell Spreadsheet cell data
Returns ------- attributes : Dict[str, Union[int, str]] Dictionary with attributes and attribute values """ attributes: dict[str, int | str] = {} style_name = self._process_style(cell.style) if style_name is not None: attributes["stylename"] = style_name if cell.mergestart is not None and cell.mergeend is not None: attributes["numberrowsspanned"] = max(1, cell.mergestart) attributes["numbercolumnsspanned"] = cell.mergeend return attributes
def _make_table_cell(self, cell: ExcelCell) -> tuple[object, Any]: """Convert cell data to an OpenDocument spreadsheet cell
Parameters ---------- cell : ExcelCell Spreadsheet cell data
Returns ------- pvalue, cell : Tuple[str, TableCell] Display value, Cell value """ from odf.table import TableCell
attributes = self._make_table_cell_attributes(cell) val, fmt = self._value_with_fmt(cell.val) pvalue = value = val if isinstance(val, bool): value = str(val).lower() pvalue = str(val).upper() return ( pvalue, TableCell( valuetype="boolean", booleanvalue=value, attributes=attributes, ), ) elif isinstance(val, datetime.datetime): # Fast formatting value = val.isoformat() # Slow but locale-dependent pvalue = val.strftime("%c") return ( pvalue, TableCell(valuetype="date", datevalue=value, attributes=attributes), ) elif isinstance(val, datetime.date): # Fast formatting value = f"{val.year}-{val.month:02d}-{val.day:02d}" # Slow but locale-dependent pvalue = val.strftime("%x") return ( pvalue, TableCell(valuetype="date", datevalue=value, attributes=attributes), ) elif isinstance(val, str): return ( pvalue, TableCell( valuetype="string", stringvalue=value, attributes=attributes, ), ) else: return ( pvalue, TableCell( valuetype="float", value=value, attributes=attributes, ), )
@overload def _process_style(self, style: dict[str, Any]) -> str: ...
@overload def _process_style(self, style: None) -> None: ...
def _process_style(self, style: dict[str, Any] | None) -> str | None: """Convert a style dictionary to an OpenDocument style sheet
Parameters ---------- style : Dict Style dictionary
Returns ------- style_key : str Unique style key for later reference in sheet """ from odf.style import ( ParagraphProperties, Style, TableCellProperties, TextProperties, )
if style is None: return None style_key = json.dumps(style) if style_key in self._style_dict: return self._style_dict[style_key] name = f"pd{len(self._style_dict) + 1}" self._style_dict[style_key] = name odf_style = Style(name=name, family="table-cell") if "font" in style: font = style["font"] if font.get("bold", False): odf_style.addElement(TextProperties(fontweight="bold")) if "borders" in style: borders = style["borders"] for side, thickness in borders.items(): thickness_translation = {"thin": "0.75pt solid #000000"} odf_style.addElement( TableCellProperties( attributes={f"border{side}": thickness_translation[thickness]} ) ) if "alignment" in style: alignment = style["alignment"] horizontal = alignment.get("horizontal") if horizontal: odf_style.addElement(ParagraphProperties(textalign=horizontal)) vertical = alignment.get("vertical") if vertical: odf_style.addElement(TableCellProperties(verticalalign=vertical)) self.book.styles.addElement(odf_style) return name
def _create_freeze_panes( self, sheet_name: str, freeze_panes: tuple[int, int] ) -> None: """ Create freeze panes in the sheet.
Parameters ---------- sheet_name : str Name of the spreadsheet freeze_panes : tuple of (int, int) Freeze pane location x and y """ from odf.config import ( ConfigItem, ConfigItemMapEntry, ConfigItemMapIndexed, ConfigItemMapNamed, ConfigItemSet, )
config_item_set = ConfigItemSet(name="ooo:view-settings") self.book.settings.addElement(config_item_set)
config_item_map_indexed = ConfigItemMapIndexed(name="Views") config_item_set.addElement(config_item_map_indexed)
config_item_map_entry = ConfigItemMapEntry() config_item_map_indexed.addElement(config_item_map_entry)
config_item_map_named = ConfigItemMapNamed(name="Tables") config_item_map_entry.addElement(config_item_map_named)
config_item_map_entry = ConfigItemMapEntry(name=sheet_name) config_item_map_named.addElement(config_item_map_entry)
config_item_map_entry.addElement( ConfigItem(name="HorizontalSplitMode", type="short", text="2") ) config_item_map_entry.addElement( ConfigItem(name="VerticalSplitMode", type="short", text="2") ) config_item_map_entry.addElement( ConfigItem( name="HorizontalSplitPosition", type="int", text=str(freeze_panes[0]) ) ) config_item_map_entry.addElement( ConfigItem( name="VerticalSplitPosition", type="int", text=str(freeze_panes[1]) ) ) config_item_map_entry.addElement( ConfigItem(name="PositionRight", type="int", text=str(freeze_panes[0])) ) config_item_map_entry.addElement( ConfigItem(name="PositionBottom", type="int", text=str(freeze_panes[1])) )123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646from __future__ import annotations
import mmapfrom typing import ( TYPE_CHECKING, Any, cast,)
import numpy as np
from pandas.compat._optional import import_optional_dependencyfrom pandas.util._decorators import doc
from pandas.core.shared_docs import _shared_docs
from pandas.io.excel._base import ( BaseExcelReader, ExcelWriter,)from pandas.io.excel._util import ( combine_kwargs, validate_freeze_panes,)
if TYPE_CHECKING: from openpyxl import Workbook from openpyxl.descriptors.serialisable import Serialisable from openpyxl.styles import Fill
from pandas._typing import ( ExcelWriterIfSheetExists, FilePath, ReadBuffer, Scalar, StorageOptions, WriteExcelBuffer, )
class OpenpyxlWriter(ExcelWriter): _engine = "openpyxl" _supported_extensions = (".xlsx", ".xlsm")
def __init__( # pyright: ignore[reportInconsistentConstructor] self, path: FilePath | WriteExcelBuffer | ExcelWriter, engine: str | None = None, date_format: str | None = None, datetime_format: str | None = None, mode: str = "w", storage_options: StorageOptions | None = None, if_sheet_exists: ExcelWriterIfSheetExists | None = None, engine_kwargs: dict[str, Any] | None = None, **kwargs, ) -> None: # Use the openpyxl module as the Excel writer. from openpyxl.workbook import Workbook
engine_kwargs = combine_kwargs(engine_kwargs, kwargs)
super().__init__( path, mode=mode, storage_options=storage_options, if_sheet_exists=if_sheet_exists, engine_kwargs=engine_kwargs, )
# ExcelWriter replaced "a" by "r+" to allow us to first read the excel file from # the file and later write to it if "r+" in self._mode: # Load from existing workbook from openpyxl import load_workbook
try: self._book = load_workbook(self._handles.handle, **engine_kwargs) except TypeError: self._handles.handle.close() raise self._handles.handle.seek(0) else: # Create workbook object with default optimized_write=True. try: self._book = Workbook(**engine_kwargs) except TypeError: self._handles.handle.close() raise
if self.book.worksheets: self.book.remove(self.book.worksheets[0])
@property def book(self) -> Workbook: """ Book instance of class openpyxl.workbook.Workbook.
This attribute can be used to access engine-specific features. """ return self._book
@property def sheets(self) -> dict[str, Any]: """Mapping of sheet names to sheet objects.""" result = {name: self.book[name] for name in self.book.sheetnames} return result
def _save(self) -> None: """ Save workbook to disk. """ self.book.save(self._handles.handle) if "r+" in self._mode and not isinstance(self._handles.handle, mmap.mmap): # truncate file to the written content self._handles.handle.truncate()
@classmethod def _convert_to_style_kwargs( cls, style_dict: dict[str, Serialisable] ) -> dict[str, Serialisable]: """ Convert a style_dict to a set of kwargs suitable for initializing or updating-on-copy an openpyxl v2 style object.
Parameters ---------- style_dict : dict A dict with zero or more of the following keys (or their synonyms). 'font' 'fill' 'border' ('borders') 'alignment' 'number_format' 'protection'
Returns ------- style_kwargs : dict A dict with the same, normalized keys as ``style_dict`` but each value has been replaced with a native openpyxl style object of the appropriate class. """ _style_key_map = {"borders": "border"}
style_kwargs: dict[str, Serialisable] = {} for k, v in style_dict.items(): k = _style_key_map.get(k, k) _conv_to_x = getattr(cls, f"_convert_to_{k}", lambda x: None) new_v = _conv_to_x(v) if new_v: style_kwargs[k] = new_v
return style_kwargs
@classmethod def _convert_to_color(cls, color_spec): """ Convert ``color_spec`` to an openpyxl v2 Color object.
Parameters ---------- color_spec : str, dict A 32-bit ARGB hex string, or a dict with zero or more of the following keys. 'rgb' 'indexed' 'auto' 'theme' 'tint' 'index' 'type'
Returns ------- color : openpyxl.styles.Color """ from openpyxl.styles import Color
if isinstance(color_spec, str): return Color(color_spec) else: return Color(**color_spec)
@classmethod def _convert_to_font(cls, font_dict): """ Convert ``font_dict`` to an openpyxl v2 Font object.
Parameters ---------- font_dict : dict A dict with zero or more of the following keys (or their synonyms). 'name' 'size' ('sz') 'bold' ('b') 'italic' ('i') 'underline' ('u') 'strikethrough' ('strike') 'color' 'vertAlign' ('vertalign') 'charset' 'scheme' 'family' 'outline' 'shadow' 'condense'
Returns ------- font : openpyxl.styles.Font """ from openpyxl.styles import Font
_font_key_map = { "sz": "size", "b": "bold", "i": "italic", "u": "underline", "strike": "strikethrough", "vertalign": "vertAlign", }
font_kwargs = {} for k, v in font_dict.items(): k = _font_key_map.get(k, k) if k == "color": v = cls._convert_to_color(v) font_kwargs[k] = v
return Font(**font_kwargs)
@classmethod def _convert_to_stop(cls, stop_seq): """ Convert ``stop_seq`` to a list of openpyxl v2 Color objects, suitable for initializing the ``GradientFill`` ``stop`` parameter.
Parameters ---------- stop_seq : iterable An iterable that yields objects suitable for consumption by ``_convert_to_color``.
Returns ------- stop : list of openpyxl.styles.Color """ return map(cls._convert_to_color, stop_seq)
@classmethod def _convert_to_fill(cls, fill_dict: dict[str, Any]) -> Fill: """ Convert ``fill_dict`` to an openpyxl v2 Fill object.
Parameters ---------- fill_dict : dict A dict with one or more of the following keys (or their synonyms), 'fill_type' ('patternType', 'patterntype') 'start_color' ('fgColor', 'fgcolor') 'end_color' ('bgColor', 'bgcolor') or one or more of the following keys (or their synonyms). 'type' ('fill_type') 'degree' 'left' 'right' 'top' 'bottom' 'stop'
Returns ------- fill : openpyxl.styles.Fill """ from openpyxl.styles import ( GradientFill, PatternFill, )
_pattern_fill_key_map = { "patternType": "fill_type", "patterntype": "fill_type", "fgColor": "start_color", "fgcolor": "start_color", "bgColor": "end_color", "bgcolor": "end_color", }
_gradient_fill_key_map = {"fill_type": "type"}
pfill_kwargs = {} gfill_kwargs = {} for k, v in fill_dict.items(): pk = _pattern_fill_key_map.get(k) gk = _gradient_fill_key_map.get(k) if pk in ["start_color", "end_color"]: v = cls._convert_to_color(v) if gk == "stop": v = cls._convert_to_stop(v) if pk: pfill_kwargs[pk] = v elif gk: gfill_kwargs[gk] = v else: pfill_kwargs[k] = v gfill_kwargs[k] = v
try: return PatternFill(**pfill_kwargs) except TypeError: return GradientFill(**gfill_kwargs)
@classmethod def _convert_to_side(cls, side_spec): """ Convert ``side_spec`` to an openpyxl v2 Side object.
Parameters ---------- side_spec : str, dict A string specifying the border style, or a dict with zero or more of the following keys (or their synonyms). 'style' ('border_style') 'color'
Returns ------- side : openpyxl.styles.Side """ from openpyxl.styles import Side
_side_key_map = {"border_style": "style"}
if isinstance(side_spec, str): return Side(style=side_spec)
side_kwargs = {} for k, v in side_spec.items(): k = _side_key_map.get(k, k) if k == "color": v = cls._convert_to_color(v) side_kwargs[k] = v
return Side(**side_kwargs)
@classmethod def _convert_to_border(cls, border_dict): """ Convert ``border_dict`` to an openpyxl v2 Border object.
Parameters ---------- border_dict : dict A dict with zero or more of the following keys (or their synonyms). 'left' 'right' 'top' 'bottom' 'diagonal' 'diagonal_direction' 'vertical' 'horizontal' 'diagonalUp' ('diagonalup') 'diagonalDown' ('diagonaldown') 'outline'
Returns ------- border : openpyxl.styles.Border """ from openpyxl.styles import Border
_border_key_map = {"diagonalup": "diagonalUp", "diagonaldown": "diagonalDown"}
border_kwargs = {} for k, v in border_dict.items(): k = _border_key_map.get(k, k) if k == "color": v = cls._convert_to_color(v) if k in ["left", "right", "top", "bottom", "diagonal"]: v = cls._convert_to_side(v) border_kwargs[k] = v
return Border(**border_kwargs)
@classmethod def _convert_to_alignment(cls, alignment_dict): """ Convert ``alignment_dict`` to an openpyxl v2 Alignment object.
Parameters ---------- alignment_dict : dict A dict with zero or more of the following keys (or their synonyms). 'horizontal' 'vertical' 'text_rotation' 'wrap_text' 'shrink_to_fit' 'indent' Returns ------- alignment : openpyxl.styles.Alignment """ from openpyxl.styles import Alignment
return Alignment(**alignment_dict)
@classmethod def _convert_to_number_format(cls, number_format_dict): """ Convert ``number_format_dict`` to an openpyxl v2.1.0 number format initializer.
Parameters ---------- number_format_dict : dict A dict with zero or more of the following keys. 'format_code' : str
Returns ------- number_format : str """ return number_format_dict["format_code"]
@classmethod def _convert_to_protection(cls, protection_dict): """ Convert ``protection_dict`` to an openpyxl v2 Protection object.
Parameters ---------- protection_dict : dict A dict with zero or more of the following keys. 'locked' 'hidden'
Returns ------- """ from openpyxl.styles import Protection
return Protection(**protection_dict)
def _write_cells( self, cells, sheet_name: str | None = None, startrow: int = 0, startcol: int = 0, freeze_panes: tuple[int, int] | None = None, autofilter_range: str | None = None, ) -> None: # Write the frame cells using openpyxl. sheet_name = self._get_sheet_name(sheet_name)
_style_cache: dict[str, dict[str, Serialisable]] = {}
if sheet_name in self.sheets and self._if_sheet_exists != "new": if "r+" in self._mode: if self._if_sheet_exists == "replace": old_wks = self.sheets[sheet_name] target_index = self.book.index(old_wks) del self.book[sheet_name] wks = self.book.create_sheet(sheet_name, target_index) elif self._if_sheet_exists == "error": raise ValueError( f"Sheet '{sheet_name}' already exists and " f"if_sheet_exists is set to 'error'." ) elif self._if_sheet_exists == "overlay": wks = self.sheets[sheet_name] else: raise ValueError( f"'{self._if_sheet_exists}' is not valid for if_sheet_exists. " "Valid options are 'error', 'new', 'replace' and 'overlay'." ) else: wks = self.sheets[sheet_name] else: wks = self.book.create_sheet() wks.title = sheet_name
if validate_freeze_panes(freeze_panes): freeze_panes = cast(tuple[int, int], freeze_panes) wks.freeze_panes = wks.cell( row=freeze_panes[0] + 1, column=freeze_panes[1] + 1 )
for cell in cells: xcell = wks.cell( row=startrow + cell.row + 1, column=startcol + cell.col + 1 ) xcell.value, fmt = self._value_with_fmt(cell.val) if fmt: xcell.number_format = fmt
style_kwargs: dict[str, Serialisable] | None = {} if cell.style: key = str(cell.style) style_kwargs = _style_cache.get(key) if style_kwargs is None: style_kwargs = self._convert_to_style_kwargs(cell.style) _style_cache[key] = style_kwargs
if style_kwargs: for k, v in style_kwargs.items(): setattr(xcell, k, v)
if cell.mergestart is not None and cell.mergeend is not None: wks.merge_cells( start_row=startrow + cell.row + 1, start_column=startcol + cell.col + 1, end_column=startcol + cell.mergeend + 1, end_row=startrow + cell.mergestart + 1, )
# When cells are merged only the top-left cell is preserved # The behaviour of the other cells in a merged range is # undefined if style_kwargs: first_row = startrow + cell.row + 1 last_row = startrow + cell.mergestart + 1 first_col = startcol + cell.col + 1 last_col = startcol + cell.mergeend + 1
for row in range(first_row, last_row + 1): for col in range(first_col, last_col + 1): if row == first_row and col == first_col: # Ignore first cell. It is already handled. continue xcell = wks.cell(column=col, row=row) for k, v in style_kwargs.items(): setattr(xcell, k, v)
if autofilter_range: wks.auto_filter.ref = autofilter_range
class OpenpyxlReader(BaseExcelReader["Workbook"]): @doc(storage_options=_shared_docs["storage_options"]) def __init__( self, filepath_or_buffer: FilePath | ReadBuffer[bytes], storage_options: StorageOptions | None = None, engine_kwargs: dict | None = None, ) -> None: """ Reader using openpyxl engine.
Parameters ---------- filepath_or_buffer : str, path object or Workbook Object to be parsed. {storage_options} engine_kwargs : dict, optional Arbitrary keyword arguments passed to excel engine. """ import_optional_dependency("openpyxl") super().__init__( filepath_or_buffer, storage_options=storage_options, engine_kwargs=engine_kwargs, )
@property def _workbook_class(self) -> type[Workbook]: from openpyxl import Workbook
return Workbook
def load_workbook( self, filepath_or_buffer: FilePath | ReadBuffer[bytes], engine_kwargs ) -> Workbook: from openpyxl import load_workbook
default_kwargs = {"read_only": True, "data_only": True, "keep_links": False}
return load_workbook( filepath_or_buffer, **(default_kwargs | engine_kwargs), )
@property def sheet_names(self) -> list[str]: return [sheet.title for sheet in self.book.worksheets]
def get_sheet_by_name(self, name: str): self.raise_if_bad_sheet_by_name(name) return self.book[name]
def get_sheet_by_index(self, index: int): self.raise_if_bad_sheet_by_index(index) return self.book.worksheets[index]
def _convert_cell(self, cell) -> Scalar: from openpyxl.cell.cell import ( TYPE_ERROR, TYPE_NUMERIC, )
if cell.value is None: return "" # compat with xlrd elif cell.data_type == TYPE_ERROR: return np.nan elif cell.data_type == TYPE_NUMERIC: val = int(cell.value) if val == cell.value: return val return float(cell.value)
return cell.value
def get_sheet_data( self, sheet, file_rows_needed: int | None = None ) -> list[list[Scalar]]: if self.book.read_only: sheet.reset_dimensions()
data: list[list[Scalar]] = [] last_row_with_data = -1 for row_number, row in enumerate(sheet.rows): converted_row = [self._convert_cell(cell) for cell in row] while converted_row and converted_row[-1] == "": # trim trailing empty elements converted_row.pop() if converted_row: last_row_with_data = row_number data.append(converted_row) if file_rows_needed is not None and len(data) >= file_rows_needed: break
# Trim trailing empty rows data = data[: last_row_with_data + 1]
if len(data) > 0: # extend rows to max width max_width = max(len(data_row) for data_row in data) if min(len(data_row) for data_row in data) < max_width: empty_cell: list[Scalar] = [""] data = [ data_row + (max_width - len(data_row)) * empty_cell for data_row in data ]
return data123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131# pyright: reportMissingImports=falsefrom __future__ import annotations
from typing import TYPE_CHECKING
from pandas.compat._optional import import_optional_dependency
from pandas.io.excel._base import BaseExcelReader
if TYPE_CHECKING: from pyxlsb import Workbook
from pandas._typing import ( FilePath, ReadBuffer, Scalar, StorageOptions, )
class PyxlsbReader(BaseExcelReader["Workbook"]): def __init__( self, filepath_or_buffer: FilePath | ReadBuffer[bytes], storage_options: StorageOptions | None = None, engine_kwargs: dict | None = None, ) -> None: """ Reader using pyxlsb engine.
Parameters ---------- filepath_or_buffer : str, path object, or Workbook Object to be parsed. storage_options : dict, optional 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.request.Request`` as header options. For other URLs (e.g. starting with "s3://", and "gcs://") the key-value pairs are forwarded to ``fsspec.open``. Please see ``fsspec`` and ``urllib`` for more details, and for more examples on storage options refer `here <https://pandas.pydata.org/docs/user_guide/io.html? highlight=storage_options#reading-writing-remote-files>`_. engine_kwargs : dict, optional Arbitrary keyword arguments passed to excel engine. """ import_optional_dependency("pyxlsb") # This will call load_workbook on the filepath or buffer # And set the result to the book-attribute super().__init__( filepath_or_buffer, storage_options=storage_options, engine_kwargs=engine_kwargs, )
@property def _workbook_class(self) -> type[Workbook]: from pyxlsb import Workbook
return Workbook
def load_workbook( self, filepath_or_buffer: FilePath | ReadBuffer[bytes], engine_kwargs ) -> Workbook: from pyxlsb import open_workbook
# TODO: hack in buffer capability # This might need some modifications to the Pyxlsb library # Actual work for opening it is in xlsbpackage.py, line 20-ish
return open_workbook(filepath_or_buffer, **engine_kwargs)
@property def sheet_names(self) -> list[str]: return self.book.sheets
def get_sheet_by_name(self, name: str): self.raise_if_bad_sheet_by_name(name) return self.book.get_sheet(name)
def get_sheet_by_index(self, index: int): self.raise_if_bad_sheet_by_index(index) # pyxlsb sheets are indexed from 1 onwards # There's a fix for this in the source, but the pypi package doesn't have it return self.book.get_sheet(index + 1)
def _convert_cell(self, cell) -> Scalar: # TODO: there is no way to distinguish between floats and datetimes in pyxlsb # This means that there is no way to read datetime types from an xlsb file yet if cell.v is None: return "" # Prevents non-named columns from not showing up as Unnamed: i if isinstance(cell.v, float): val = int(cell.v) if val == cell.v: return val else: return float(cell.v)
return cell.v
def get_sheet_data( self, sheet, file_rows_needed: int | None = None, ) -> list[list[Scalar]]: data: list[list[Scalar]] = [] previous_row_number = -1 # When sparse=True the rows can have different lengths and empty rows are # not returned. The cells are namedtuples of row, col, value (r, c, v). for row in sheet.rows(sparse=True): row_number = row[0].r converted_row = [self._convert_cell(cell) for cell in row] while converted_row and converted_row[-1] == "": # trim trailing empty elements converted_row.pop() if converted_row: data.extend([[]] * (row_number - previous_row_number - 1)) data.append(converted_row) previous_row_number = row_number if file_rows_needed is not None and len(data) >= file_rows_needed: break if data: # extend rows to max_width max_width = max(len(data_row) for data_row in data) if min(len(data_row) for data_row in data) < max_width: empty_cell: list[Scalar] = [""] data = [ data_row + (max_width - len(data_row)) * empty_cell for data_row in data ] return data123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328from __future__ import annotations
from collections.abc import ( Callable, Hashable, Iterable, MutableMapping, Sequence,)from typing import ( TYPE_CHECKING, Any, Literal, TypeVar, overload,)
from pandas.compat._optional import import_optional_dependency
from pandas.core.dtypes.common import ( is_integer, is_list_like,)
if TYPE_CHECKING: from pandas.io.excel._base import ExcelWriter
ExcelWriter_t = type[ExcelWriter] usecols_func = TypeVar("usecols_func", bound=Callable[[Hashable], object])
_writers: MutableMapping[str, ExcelWriter_t] = {}
def register_writer(klass: ExcelWriter_t) -> None: """ Add engine to the excel writer registry.io.excel.
You must use this method to integrate with ``to_excel``.
Parameters ---------- klass : ExcelWriter """ if not callable(klass): raise ValueError("Can only register callables as engines") engine_name = klass._engine _writers[engine_name] = klass
def get_default_engine(ext: str, mode: Literal["reader", "writer"] = "reader") -> str: """ Return the default reader/writer for the given extension.
Parameters ---------- ext : str The excel file extension for which to get the default engine. mode : str {'reader', 'writer'} Whether to get the default engine for reading or writing. Either 'reader' or 'writer'
Returns ------- str The default engine for the extension. """ _default_readers = { "xlsx": "openpyxl", "xlsm": "openpyxl", "xlsb": "pyxlsb", "xls": "xlrd", "ods": "odf", } _default_writers = { "xlsx": "openpyxl", "xlsm": "openpyxl", "xlsb": "pyxlsb", "ods": "odf", } assert mode in ["reader", "writer"] if mode == "writer": # Prefer xlsxwriter over openpyxl if installed xlsxwriter = import_optional_dependency("xlsxwriter", errors="warn") if xlsxwriter: _default_writers["xlsx"] = "xlsxwriter" return _default_writers[ext] else: return _default_readers[ext]
def get_writer(engine_name: str) -> ExcelWriter_t: try: return _writers[engine_name] except KeyError as err: raise ValueError(f"No Excel writer '{engine_name}'") from err
def _excel2num(x: str) -> int: """ Convert Excel column name like 'AB' to 0-based column index.
Parameters ---------- x : str The Excel column name to convert to a 0-based column index.
Returns ------- num : int The column index corresponding to the name.
Raises ------ ValueError Part of the Excel column name was invalid. """ index = 0
for c in x.upper().strip(): cp = ord(c)
if cp < ord("A") or cp > ord("Z"): raise ValueError(f"Invalid column name: {x}")
index = index * 26 + cp - ord("A") + 1
return index - 1
def _range2cols(areas: str) -> list[int]: """ Convert comma separated list of column names and ranges to indices.
Parameters ---------- areas : str A string containing a sequence of column ranges (or areas).
Returns ------- cols : list A list of 0-based column indices.
Examples -------- >>> _range2cols("A:E") [0, 1, 2, 3, 4] >>> _range2cols("A,C,Z:AB") [0, 2, 25, 26, 27] """ cols: list[int] = []
for rng in areas.split(","): if ":" in rng: rngs = rng.split(":") cols.extend(range(_excel2num(rngs[0]), _excel2num(rngs[1]) + 1)) else: cols.append(_excel2num(rng))
return cols
@overloaddef maybe_convert_usecols(usecols: str | list[int]) -> list[int]: ...
@overloaddef maybe_convert_usecols(usecols: list[str]) -> list[str]: ...
@overloaddef maybe_convert_usecols(usecols: usecols_func) -> usecols_func: ...
@overloaddef maybe_convert_usecols(usecols: None) -> None: ...
def maybe_convert_usecols( usecols: str | list[int] | list[str] | usecols_func | None,) -> None | list[int] | list[str] | usecols_func: """ Convert `usecols` into a compatible format for parsing in `parsers.py`.
Parameters ---------- usecols : object The use-columns object to potentially convert.
Returns ------- converted : object The compatible format of `usecols`. """ if usecols is None: return usecols
if is_integer(usecols): raise ValueError( "Passing an integer for `usecols` is no longer supported. " "Please pass in a list of int from 0 to `usecols` inclusive instead." )
if isinstance(usecols, str): return _range2cols(usecols)
return usecols
@overloaddef validate_freeze_panes(freeze_panes: tuple[int, int]) -> Literal[True]: ...
@overloaddef validate_freeze_panes(freeze_panes: None) -> Literal[False]: ...
def validate_freeze_panes(freeze_panes: tuple[int, int] | None) -> bool: if freeze_panes is not None: if len(freeze_panes) == 2 and all( isinstance(item, int) for item in freeze_panes ): return True
raise ValueError( "freeze_panes must be of form (row, column) " "where row and column are integers" )
# freeze_panes wasn't specified, return False so it won't be applied # to output sheet return False
def fill_mi_header( row: list[Hashable], control_row: list[bool]) -> tuple[list[Hashable], list[bool]]: """ Forward fill blank entries in row but only inside the same parent index.
Used for creating headers in Multiindex.
Parameters ---------- row : list List of items in a single row. control_row : list of bool Helps to determine if particular column is in same parent index as the previous value. Used to stop propagation of empty cells between different indexes.
Returns ------- Returns changed row and control_row """ last = row[0] for i in range(1, len(row)): if not control_row[i]: last = row[i]
if row[i] == "" or row[i] is None: row[i] = last else: control_row[i] = False last = row[i]
return row, control_row
def pop_header_name( row: list[Hashable], index_col: int | Sequence[int]) -> tuple[Hashable | None, list[Hashable]]: """ Pop the header name for MultiIndex parsing.
Parameters ---------- row : list The data row to parse for the header name. index_col : int, list The index columns for our data. Assumed to be non-null.
Returns ------- header_name : str The extracted header name. trimmed_row : list The original data row with the header name removed. """ # Pop out header name and fill w/blank. if is_list_like(index_col): assert isinstance(index_col, Iterable) i = max(index_col) else: assert not isinstance(index_col, Iterable) i = index_col
header_name = row[i] header_name = None if header_name == "" else header_name
return header_name, [*row[:i], "", *row[i + 1 :]]
def combine_kwargs(engine_kwargs: dict[str, Any] | None, kwargs: dict) -> dict: """ Used to combine two sources of kwargs for the backend engine.
Use of kwargs is deprecated, this function is solely for use in 1.3 and should be removed in 1.4/2.0. Also _base.ExcelWriter.__new__ ensures either engine_kwargs or kwargs must be None or empty respectively.
Parameters ---------- engine_kwargs: dict kwargs to be passed through to the engine. kwargs: dict kwargs to be psased through to the engine (deprecated)
Returns ------- engine_kwargs combined with kwargs """ if engine_kwargs is None: result = {} else: result = engine_kwargs.copy() result.update(kwargs) return result123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147from __future__ import annotations
from datetime import timeimport mathfrom typing import TYPE_CHECKING
import numpy as np
from pandas.compat._optional import import_optional_dependency
from pandas.io.excel._base import BaseExcelReader
if TYPE_CHECKING: from xlrd import Book
from pandas._typing import ( Scalar, StorageOptions, )
class XlrdReader(BaseExcelReader["Book"]): def __init__( self, filepath_or_buffer, storage_options: StorageOptions | None = None, engine_kwargs: dict | None = None, ) -> None: """ Reader using xlrd engine.
Parameters ---------- filepath_or_buffer : str, path object or Workbook Object to be parsed. storage_options : dict, optional 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.request.Request`` as header options. For other URLs (e.g. starting with "s3://", and "gcs://") the key-value pairs are forwarded to ``fsspec.open``. Please see ``fsspec`` and ``urllib`` for more details, and for more examples on storage options refer `here <https://pandas.pydata.org/ pandas-docs/stable/user_guide/io.html? highlight=storage_options#reading-writing-remote-files>`__. engine_kwargs : dict, optional Arbitrary keyword arguments passed to excel engine. """ err_msg = "Install xlrd >= 2.0.1 for xls Excel support" import_optional_dependency("xlrd", extra=err_msg) super().__init__( filepath_or_buffer, storage_options=storage_options, engine_kwargs=engine_kwargs, )
@property def _workbook_class(self) -> type[Book]: from xlrd import Book
return Book
def load_workbook(self, filepath_or_buffer, engine_kwargs) -> Book: from xlrd import open_workbook
if hasattr(filepath_or_buffer, "read"): data = filepath_or_buffer.read() return open_workbook(file_contents=data, **engine_kwargs) else: return open_workbook(filepath_or_buffer, **engine_kwargs)
@property def sheet_names(self): return self.book.sheet_names()
def get_sheet_by_name(self, name): self.raise_if_bad_sheet_by_name(name) return self.book.sheet_by_name(name)
def get_sheet_by_index(self, index): self.raise_if_bad_sheet_by_index(index) return self.book.sheet_by_index(index)
def get_sheet_data( self, sheet, file_rows_needed: int | None = None ) -> list[list[Scalar]]: from xlrd import ( XL_CELL_BOOLEAN, XL_CELL_DATE, XL_CELL_ERROR, XL_CELL_NUMBER, xldate, )
epoch1904 = self.book.datemode
def _parse_cell(cell_contents, cell_typ): """ converts the contents of the cell into a pandas appropriate object """ if cell_typ == XL_CELL_DATE: # Use the newer xlrd datetime handling. try: cell_contents = xldate.xldate_as_datetime(cell_contents, epoch1904) except OverflowError: return cell_contents
# Excel doesn't distinguish between dates and time, # so we treat dates on the epoch as times only. # Also, Excel supports 1900 and 1904 epochs. year = (cell_contents.timetuple())[0:3] if (not epoch1904 and year == (1899, 12, 31)) or ( epoch1904 and year == (1904, 1, 1) ): cell_contents = time( cell_contents.hour, cell_contents.minute, cell_contents.second, cell_contents.microsecond, )
elif cell_typ == XL_CELL_ERROR: cell_contents = np.nan elif cell_typ == XL_CELL_BOOLEAN: cell_contents = bool(cell_contents) elif cell_typ == XL_CELL_NUMBER: # GH5394 - Excel 'numbers' are always floats # it's a minimal perf hit and less surprising if math.isfinite(cell_contents): # GH54564 - don't attempt to convert NaN/Inf val = int(cell_contents) if val == cell_contents: cell_contents = val return cell_contents
nrows = sheet.nrows if file_rows_needed is not None: nrows = min(nrows, file_rows_needed) return [ [ _parse_cell(value, typ) for value, typ in zip( sheet.row_values(i), sheet.row_types(i), strict=True ) ] for i in range(nrows) ]123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288from __future__ import annotations
import jsonfrom typing import ( TYPE_CHECKING, Any,)
from pandas.io.excel._base import ExcelWriterfrom pandas.io.excel._util import ( combine_kwargs, validate_freeze_panes,)
if TYPE_CHECKING: from pandas._typing import ( ExcelWriterIfSheetExists, FilePath, StorageOptions, WriteExcelBuffer, )
class _XlsxStyler: # Map from openpyxl-oriented styles to flatter xlsxwriter representation # Ordering necessary for both determinism and because some are keyed by # prefixes of others. STYLE_MAPPING: dict[str, list[tuple[tuple[str, ...], str]]] = { "font": [ (("name",), "font_name"), (("sz",), "font_size"), (("size",), "font_size"), (("color", "rgb"), "font_color"), (("color",), "font_color"), (("b",), "bold"), (("bold",), "bold"), (("i",), "italic"), (("italic",), "italic"), (("u",), "underline"), (("underline",), "underline"), (("strike",), "font_strikeout"), (("vertAlign",), "font_script"), (("vertalign",), "font_script"), ], "number_format": [(("format_code",), "num_format"), ((), "num_format")], "protection": [(("locked",), "locked"), (("hidden",), "hidden")], "alignment": [ (("horizontal",), "align"), (("vertical",), "valign"), (("text_rotation",), "rotation"), (("wrap_text",), "text_wrap"), (("indent",), "indent"), (("shrink_to_fit",), "shrink"), ], "fill": [ (("patternType",), "pattern"), (("patterntype",), "pattern"), (("fill_type",), "pattern"), (("start_color", "rgb"), "fg_color"), (("fgColor", "rgb"), "fg_color"), (("fgcolor", "rgb"), "fg_color"), (("start_color",), "fg_color"), (("fgColor",), "fg_color"), (("fgcolor",), "fg_color"), (("end_color", "rgb"), "bg_color"), (("bgColor", "rgb"), "bg_color"), (("bgcolor", "rgb"), "bg_color"), (("end_color",), "bg_color"), (("bgColor",), "bg_color"), (("bgcolor",), "bg_color"), ], "border": [ (("color", "rgb"), "border_color"), (("color",), "border_color"), (("style",), "border"), (("top", "color", "rgb"), "top_color"), (("top", "color"), "top_color"), (("top", "style"), "top"), (("top",), "top"), (("right", "color", "rgb"), "right_color"), (("right", "color"), "right_color"), (("right", "style"), "right"), (("right",), "right"), (("bottom", "color", "rgb"), "bottom_color"), (("bottom", "color"), "bottom_color"), (("bottom", "style"), "bottom"), (("bottom",), "bottom"), (("left", "color", "rgb"), "left_color"), (("left", "color"), "left_color"), (("left", "style"), "left"), (("left",), "left"), ], }
@classmethod def convert(cls, style_dict, num_format_str=None) -> dict[str, Any]: """ converts a style_dict to an xlsxwriter format dict
Parameters ---------- style_dict : style dictionary to convert num_format_str : optional number format string """ # Create an XlsxWriter format object. props = {}
if num_format_str is not None: props["num_format"] = num_format_str
if style_dict is None: return props
if "borders" in style_dict: style_dict = style_dict.copy() style_dict["border"] = style_dict.pop("borders")
for style_group_key, style_group in style_dict.items(): for src, dst in cls.STYLE_MAPPING.get(style_group_key, []): # src is a sequence of keys into a nested dict # dst is a flat key if dst in props: continue v = style_group for k in src: try: v = v[k] except (KeyError, TypeError): break else: props[dst] = v
if isinstance(props.get("pattern"), str): # TODO: support other fill patterns props["pattern"] = 0 if props["pattern"] == "none" else 1
for k in ["border", "top", "right", "bottom", "left"]: if isinstance(props.get(k), str): try: props[k] = [ "none", "thin", "medium", "dashed", "dotted", "thick", "double", "hair", "mediumDashed", "dashDot", "mediumDashDot", "dashDotDot", "mediumDashDotDot", "slantDashDot", ].index(props[k]) except ValueError: props[k] = 2
if isinstance(props.get("font_script"), str): props["font_script"] = ["baseline", "superscript", "subscript"].index( props["font_script"] )
if isinstance(props.get("underline"), str): props["underline"] = { "none": 0, "single": 1, "double": 2, "singleAccounting": 33, "doubleAccounting": 34, }[props["underline"]]
# GH 30107 - xlsxwriter uses different name if props.get("valign") == "center": props["valign"] = "vcenter"
return props
class XlsxWriter(ExcelWriter): _engine = "xlsxwriter" _supported_extensions = (".xlsx",)
def __init__( # pyright: ignore[reportInconsistentConstructor] self, path: FilePath | WriteExcelBuffer | ExcelWriter, engine: str | None = None, date_format: str | None = None, datetime_format: str | None = None, mode: str = "w", storage_options: StorageOptions | None = None, if_sheet_exists: ExcelWriterIfSheetExists | None = None, engine_kwargs: dict[str, Any] | None = None, **kwargs, ) -> None: # Use the xlsxwriter module as the Excel writer. from xlsxwriter import Workbook
engine_kwargs = combine_kwargs(engine_kwargs, kwargs)
if mode == "a": raise ValueError("Append mode is not supported with xlsxwriter!")
super().__init__( path, engine=engine, date_format=date_format, datetime_format=datetime_format, mode=mode, storage_options=storage_options, if_sheet_exists=if_sheet_exists, engine_kwargs=engine_kwargs, )
try: self._book = Workbook(self._handles.handle, **engine_kwargs) except TypeError: self._handles.handle.close() raise
@property def book(self): """ Book instance of class xlsxwriter.Workbook.
This attribute can be used to access engine-specific features. """ return self._book
@property def sheets(self) -> dict[str, Any]: result = self.book.sheetnames return result
def _save(self) -> None: """ Save workbook to disk. """ self.book.close()
def _write_cells( self, cells, sheet_name: str | None = None, startrow: int = 0, startcol: int = 0, freeze_panes: tuple[int, int] | None = None, autofilter_range: str | None = None, ) -> None: # Write the frame cells using xlsxwriter. sheet_name = self._get_sheet_name(sheet_name)
wks = self.book.get_worksheet_by_name(sheet_name) if wks is None: wks = self.book.add_worksheet(sheet_name)
style_dict = {"null": None}
if validate_freeze_panes(freeze_panes): wks.freeze_panes(*(freeze_panes))
for cell in cells: val, fmt = self._value_with_fmt(cell.val)
stylekey = json.dumps(cell.style) if fmt: stylekey += fmt
if stylekey in style_dict: style = style_dict[stylekey] else: style = self.book.add_format(_XlsxStyler.convert(cell.style, fmt)) style_dict[stylekey] = style
if cell.mergestart is not None and cell.mergeend is not None: wks.merge_range( startrow + cell.row, startcol + cell.col, startrow + cell.mergestart, startcol + cell.mergeend, val, style, ) else: wks.write(startrow + cell.row, startcol + cell.col, val, style)
if autofilter_range: wks.autofilter(autofilter_range)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205"""feather-format compat"""
from __future__ import annotations
from typing import ( TYPE_CHECKING, Any,)import warnings
import numpy as np
from pandas._config import using_string_dtype
from pandas._libs import libfrom pandas.compat._optional import import_optional_dependencyfrom pandas.errors import Pandas4Warningfrom pandas.util._decorators import set_modulefrom pandas.util._validators import check_dtype_backend
from pandas.core.api import DataFramefrom pandas.core.arrays.string_ import StringDtype
from pandas.io._util import arrow_table_to_pandasfrom pandas.io.common import get_handle
if TYPE_CHECKING: from collections.abc import ( Hashable, Sequence, )
from pandas._typing import ( DtypeBackend, FilePath, ReadBuffer, StorageOptions, WriteBuffer, )
def to_feather( df: DataFrame, path: FilePath | WriteBuffer[bytes], storage_options: StorageOptions | None = None, **kwargs: Any,) -> None: """ Write a DataFrame to the binary Feather format.
Parameters ---------- df : DataFrame path : str, path object, or file-like object storage_options : dict, optional 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.request.Request`` as header options. For other URLs (e.g. starting with "s3://", and "gcs://") the key-value pairs are forwarded to ``fsspec.open``. Please see ``fsspec`` and ``urllib`` for more details, and for more examples on storage options refer `here <https://pandas.pydata.org/docs/user_guide/io.html? highlight=storage_options#reading-writing-remote-files>`_. **kwargs : Additional keywords passed to `pyarrow.feather.write_feather`.
""" import_optional_dependency("pyarrow") from pyarrow import feather
if not isinstance(df, DataFrame): raise ValueError("feather only support IO with DataFrames")
with get_handle( path, "wb", storage_options=storage_options, is_text=False ) as handles: # pyarrow>=24 deprecates feather.write_feather in favor of pyarrow.ipc; # suppress until we migrate the implementation (GH#66169) with warnings.catch_warnings(): warnings.filterwarnings( "ignore", "pyarrow.feather.write_feather is deprecated", FutureWarning, ) feather.write_feather(df, handles.handle, **kwargs)
@set_module("pandas")def read_feather( path: FilePath | ReadBuffer[bytes], columns: Sequence[Hashable] | None = None, use_threads: bool = True, storage_options: StorageOptions | None = None, dtype_backend: DtypeBackend | lib.NoDefault = lib.no_default,) -> DataFrame: """ Load a feather-format object from the file path.
Feather is particularly useful for scenarios that require efficient serialization and deserialization of tabular data. It supports schema preservation, making it a reliable choice for use cases such as sharing data between Python and R, or persisting intermediate results during data processing pipelines. This method provides additional flexibility with options for selective column reading, thread parallelism, and choosing the backend for data types.
Parameters ---------- path : str, path object, or file-like object String, path object (implementing ``os.PathLike[str]``), or file-like object implementing a binary ``read()`` function. The string could be a URL. Valid URL schemes include http, ftp, s3, gs and file. For file URLs, a host is expected. A local file could be: ``file://localhost/path/to/table.feather``. columns : sequence, default None If not provided, all columns are read. use_threads : bool, default True Whether to parallelize reading using multiple threads. storage_options : dict, optional 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.request.Request`` as header options. For other URLs (e.g. starting with "s3://", and "gcs://") the key-value pairs are forwarded to ``fsspec.open``. Please see ``fsspec`` and ``urllib`` for more details, and for more examples on storage options refer `here <https://pandas.pydata.org/docs/user_guide/io.html? highlight=storage_options#reading-writing-remote-files>`_.
dtype_backend : {'numpy_nullable', 'pyarrow'} Back-end data type applied to the resultant :class:`DataFrame` (still experimental). If not specified, the default behavior is to not use nullable data types. If specified, the behavior is as follows:
* ``"numpy_nullable"``: returns nullable-dtype-backed :class:`DataFrame`. * ``"pyarrow"``: returns pyarrow-backed nullable :class:`ArrowDtype` :class:`DataFrame`
.. versionadded:: 2.0
Returns ------- type of object stored in file DataFrame object stored in the file.
See Also -------- read_csv : Read a comma-separated values (csv) file into a pandas DataFrame. read_excel : Read an Excel file into a pandas DataFrame. read_spss : Read an SPSS file into a pandas DataFrame. read_orc : Load an ORC object into a pandas DataFrame. read_sas : Read SAS file into a pandas DataFrame.
Examples -------- >>> df = pd.read_feather("path/to/file.feather") # doctest: +SKIP """ import_optional_dependency("pyarrow") from pyarrow import feather
# import utils to register the pyarrow extension types import pandas.core.arrays.arrow.extension_types # pyright: ignore[reportUnusedImport] # noqa: F401
check_dtype_backend(dtype_backend)
with get_handle( path, "rb", storage_options=storage_options, is_text=False ) as handles: if dtype_backend is lib.no_default and not using_string_dtype(): with warnings.catch_warnings(): warnings.filterwarnings( "ignore", "make_block is deprecated", Pandas4Warning, ) # pyarrow>=24 deprecates feather.read_feather in favor of # pyarrow.ipc; suppress until we migrate the implementation # (GH#66169) warnings.filterwarnings( "ignore", "pyarrow.feather.read_feather is deprecated", FutureWarning, )
df = feather.read_feather( handles.handle, columns=columns, use_threads=bool(use_threads) ) # Convert any StringDtype columns to object dtype (pyarrow always # uses string dtype even when the infer_string option is False) for col, dtype in zip(df.columns, df.dtypes, strict=True): if isinstance(dtype, StringDtype) and dtype.na_value is np.nan: df[col] = df[col].astype("object") return df
# pyarrow>=24 deprecates feather.read_table in favor of pyarrow.ipc; # suppress until we migrate the implementation (GH#66169) with warnings.catch_warnings(): warnings.filterwarnings( "ignore", "pyarrow.feather.read_table is deprecated", FutureWarning, ) pa_table = feather.read_table( handles.handle, columns=columns, use_threads=bool(use_threads) ) return arrow_table_to_pandas(pa_table, dtype_backend=dtype_backend)123456789# ruff: noqa: TC004from typing import TYPE_CHECKING
if TYPE_CHECKING: # import modules that have public classes/functions from pandas.io.formats import style
# and mark only those modules as public __all__ = ["style"]123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157# GH37967: Enable the use of CSS named colors, as defined in# matplotlib.colors.CSS4_COLORS, when exporting to Excel.# This data has been copied here, instead of being imported from matplotlib,# not to have ``to_excel`` methods require matplotlib.# source: matplotlib._color_data (3.3.3)from __future__ import annotations
CSS4_COLORS = { "aliceblue": "F0F8FF", "antiquewhite": "FAEBD7", "aqua": "00FFFF", "aquamarine": "7FFFD4", "azure": "F0FFFF", "beige": "F5F5DC", "bisque": "FFE4C4", "black": "000000", "blanchedalmond": "FFEBCD", "blue": "0000FF", "blueviolet": "8A2BE2", "brown": "A52A2A", "burlywood": "DEB887", "cadetblue": "5F9EA0", "chartreuse": "7FFF00", "chocolate": "D2691E", "coral": "FF7F50", "cornflowerblue": "6495ED", "cornsilk": "FFF8DC", "crimson": "DC143C", "cyan": "00FFFF", "darkblue": "00008B", "darkcyan": "008B8B", "darkgoldenrod": "B8860B", "darkgray": "A9A9A9", "darkgreen": "006400", "darkgrey": "A9A9A9", "darkkhaki": "BDB76B", "darkmagenta": "8B008B", "darkolivegreen": "556B2F", "darkorange": "FF8C00", "darkorchid": "9932CC", "darkred": "8B0000", "darksalmon": "E9967A", "darkseagreen": "8FBC8F", "darkslateblue": "483D8B", "darkslategray": "2F4F4F", "darkslategrey": "2F4F4F", "darkturquoise": "00CED1", "darkviolet": "9400D3", "deeppink": "FF1493", "deepskyblue": "00BFFF", "dimgray": "696969", "dimgrey": "696969", "dodgerblue": "1E90FF", "firebrick": "B22222", "floralwhite": "FFFAF0", "forestgreen": "228B22", "fuchsia": "FF00FF", "gainsboro": "DCDCDC", "ghostwhite": "F8F8FF", "gold": "FFD700", "goldenrod": "DAA520", "gray": "808080", "green": "008000", "greenyellow": "ADFF2F", "grey": "808080", "honeydew": "F0FFF0", "hotpink": "FF69B4", "indianred": "CD5C5C", "indigo": "4B0082", "ivory": "FFFFF0", "khaki": "F0E68C", "lavender": "E6E6FA", "lavenderblush": "FFF0F5", "lawngreen": "7CFC00", "lemonchiffon": "FFFACD", "lightblue": "ADD8E6", "lightcoral": "F08080", "lightcyan": "E0FFFF", "lightgoldenrodyellow": "FAFAD2", "lightgray": "D3D3D3", "lightgreen": "90EE90", "lightgrey": "D3D3D3", "lightpink": "FFB6C1", "lightsalmon": "FFA07A", "lightseagreen": "20B2AA", "lightskyblue": "87CEFA", "lightslategray": "778899", "lightslategrey": "778899", "lightsteelblue": "B0C4DE", "lightyellow": "FFFFE0", "lime": "00FF00", "limegreen": "32CD32", "linen": "FAF0E6", "magenta": "FF00FF", "maroon": "800000", "mediumaquamarine": "66CDAA", "mediumblue": "0000CD", "mediumorchid": "BA55D3", "mediumpurple": "9370DB", "mediumseagreen": "3CB371", "mediumslateblue": "7B68EE", "mediumspringgreen": "00FA9A", "mediumturquoise": "48D1CC", "mediumvioletred": "C71585", "midnightblue": "191970", "mintcream": "F5FFFA", "mistyrose": "FFE4E1", "moccasin": "FFE4B5", "navajowhite": "FFDEAD", "navy": "000080", "oldlace": "FDF5E6", "olive": "808000", "olivedrab": "6B8E23", "orange": "FFA500", "orangered": "FF4500", "orchid": "DA70D6", "palegoldenrod": "EEE8AA", "palegreen": "98FB98", "paleturquoise": "AFEEEE", "palevioletred": "DB7093", "papayawhip": "FFEFD5", "peachpuff": "FFDAB9", "peru": "CD853F", "pink": "FFC0CB", "plum": "DDA0DD", "powderblue": "B0E0E6", "purple": "800080", "rebeccapurple": "663399", "red": "FF0000", "rosybrown": "BC8F8F", "royalblue": "4169E1", "saddlebrown": "8B4513", "salmon": "FA8072", "sandybrown": "F4A460", "seagreen": "2E8B57", "seashell": "FFF5EE", "sienna": "A0522D", "silver": "C0C0C0", "skyblue": "87CEEB", "slateblue": "6A5ACD", "slategray": "708090", "slategrey": "708090", "snow": "FFFAFA", "springgreen": "00FF7F", "steelblue": "4682B4", "tan": "D2B48C", "teal": "008080", "thistle": "D8BFD8", "tomato": "FF6347", "turquoise": "40E0D0", "violet": "EE82EE", "wheat": "F5DEB3", "white": "FFFFFF", "whitesmoke": "F5F5F5", "yellow": "FFFF00", "yellowgreen": "9ACD32",}1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495"""Internal module for console introspection"""
from __future__ import annotations
from shutil import get_terminal_size
def get_console_size() -> tuple[int | None, int | None]: """ Return console size as tuple = (width, height).
Returns (None,None) in non-interactive session. """ from pandas import get_option
display_width = get_option("display.width") display_height = get_option("display.max_rows")
# Consider # interactive shell terminal, can detect term size # interactive non-shell terminal (ipnb/ipqtconsole), cannot detect term # size non-interactive script, should disregard term size
# in addition # width,height have default values, but setting to 'None' signals # should use Auto-Detection, But only in interactive shell-terminal. # Simple. yeah.
if in_interactive_session(): if in_ipython_frontend(): # sane defaults for interactive non-shell terminal # match default for width,height in config_init from pandas._config.config import get_default_val
terminal_width = get_default_val("display.width") terminal_height = get_default_val("display.max_rows") else: # pure terminal terminal_width, terminal_height = get_terminal_size() else: terminal_width, terminal_height = None, None
# Note if the User sets width/Height to None (auto-detection) # and we're in a script (non-inter), this will return (None,None) # caller needs to deal. return display_width or terminal_width, display_height or terminal_height
# ----------------------------------------------------------------------# Detect our environment
def in_interactive_session() -> bool: """ Check if we're running in an interactive shell.
Returns ------- bool True if running under python/ipython interactive shell. """ from pandas import get_option
def check_main() -> bool: try: import __main__ as main except ModuleNotFoundError: return get_option("mode.sim_interactive") return not hasattr(main, "__file__") or get_option("mode.sim_interactive")
try: # error: Name '__IPYTHON__' is not defined return __IPYTHON__ or check_main() # type: ignore[name-defined] except NameError: return check_main()
def in_ipython_frontend() -> bool: """ Check if we're inside an IPython zmq frontend.
Returns ------- bool """ try: # error: Name 'get_ipython' is not defined ip = get_ipython() # type: ignore[name-defined] return "zmq" in str(type(ip)).lower() except NameError: pass
return False123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425"""Utilities for interpreting CSS from Stylers for formatting non-HTML outputs."""
from __future__ import annotations
import refrom typing import TYPE_CHECKINGimport warnings
from pandas.errors import CSSWarningfrom pandas.util._exceptions import find_stack_level
if TYPE_CHECKING: from collections.abc import ( Callable, Generator, Iterable, Iterator, )
def _side_expander(prop_fmt: str) -> Callable: """ Wrapper to expand shorthand property into top, right, bottom, left properties
Parameters ---------- side : str The border side to expand into properties
Returns ------- function: Return to call when a 'border(-{side}): {value}' string is encountered """
def expand(self: CSSResolver, prop: str, value: str) -> Generator[tuple[str, str]]: """ Expand shorthand property into side-specific property (top, right, bottom, left)
Parameters ---------- prop (str): CSS property name value (str): String token for property
Yields ------ Tuple (str, str): Expanded property, value """ tokens = value.split() try: mapping = self.SIDE_SHORTHANDS[len(tokens)] except KeyError: warnings.warn( f'Could not expand "{prop}: {value}"', CSSWarning, stacklevel=find_stack_level(), ) return for key, idx in zip(self.SIDES, mapping, strict=True): yield prop_fmt.format(key), tokens[idx]
return expand
def _border_expander(side: str = "") -> Callable: """ Wrapper to expand 'border' property into border color, style, and width properties
Parameters ---------- side : str The border side to expand into properties
Returns ------- function: Return to call when a 'border(-{side}): {value}' string is encountered """ if side != "": side = f"-{side}"
def expand(self: CSSResolver, prop: str, value: str) -> Generator[tuple[str, str]]: """ Expand border into color, style, and width tuples
Parameters ---------- prop : str CSS property name passed to styler value : str Value passed to styler for property
Yields ------ Tuple (str, str): Expanded property, value """ tokens = value.split() if len(tokens) == 0 or len(tokens) > 3: warnings.warn( f'Too many tokens provided to "{prop}" (expected 1-3)', CSSWarning, stacklevel=find_stack_level(), )
# TODO: Can we use current color as initial value to comply with CSS standards? border_declarations = { f"border{side}-color": "black", f"border{side}-style": "none", f"border{side}-width": "medium", } for token in tokens: if token.lower() in self.BORDER_STYLES: border_declarations[f"border{side}-style"] = token elif any(ratio in token.lower() for ratio in self.BORDER_WIDTH_RATIOS): border_declarations[f"border{side}-width"] = token else: border_declarations[f"border{side}-color"] = token # TODO: Warn user if item entered more than once (e.g. "border: red green")
# Per CSS, "border" will reset previous "border-*" definitions yield from self.atomize(border_declarations.items())
return expand
class CSSResolver: """ A callable for parsing and resolving CSS to atomic properties. """
UNIT_RATIOS = { "pt": ("pt", 1), "em": ("em", 1), "rem": ("pt", 12), "ex": ("em", 0.5), # 'ch': "px": ("pt", 0.75), "pc": ("pt", 12), "in": ("pt", 72), "cm": ("in", 1 / 2.54), "mm": ("in", 1 / 25.4), "q": ("mm", 0.25), "!!default": ("em", 0), }
FONT_SIZE_RATIOS = UNIT_RATIOS.copy() FONT_SIZE_RATIOS.update( { "%": ("em", 0.01), "xx-small": ("rem", 0.5), "x-small": ("rem", 0.625), "small": ("rem", 0.8), "medium": ("rem", 1), "large": ("rem", 1.125), "x-large": ("rem", 1.5), "xx-large": ("rem", 2), "smaller": ("em", 1 / 1.2), "larger": ("em", 1.2), "!!default": ("em", 1), } )
MARGIN_RATIOS = UNIT_RATIOS.copy() MARGIN_RATIOS.update({"none": ("pt", 0)})
BORDER_WIDTH_RATIOS = UNIT_RATIOS.copy() BORDER_WIDTH_RATIOS.update( { "none": ("pt", 0), "thick": ("px", 4), "medium": ("px", 2), "thin": ("px", 1), # Default: medium only if solid } )
BORDER_STYLES = [ "none", "hidden", "dotted", "dashed", "solid", "double", "groove", "ridge", "inset", "outset", "mediumdashdot", "dashdotdot", "hair", "mediumdashdotdot", "dashdot", "slantdashdot", "mediumdashed", ]
SIDE_SHORTHANDS = { 1: [0, 0, 0, 0], 2: [0, 1, 0, 1], 3: [0, 1, 2, 1], 4: [0, 1, 2, 3], }
SIDES = ("top", "right", "bottom", "left")
CSS_EXPANSIONS = { **{ (f"border-{prop}" if prop else "border"): _border_expander(prop) for prop in ["", "top", "right", "bottom", "left"] }, **{ f"border-{prop}": _side_expander(f"border-{{:s}}-{prop}") for prop in ["color", "style", "width"] }, "margin": _side_expander("margin-{:s}"), "padding": _side_expander("padding-{:s}"), }
def __call__( self, declarations: str | Iterable[tuple[str, str]], inherited: dict[str, str] | None = None, ) -> dict[str, str]: """ The given declarations to atomic properties.
Parameters ---------- declarations_str : str | Iterable[tuple[str, str]] A CSS string or set of CSS declaration tuples e.g. "font-weight: bold; background: blue" or {("font-weight", "bold"), ("background", "blue")} inherited : dict, optional Atomic properties indicating the inherited style context in which declarations_str is to be resolved. ``inherited`` should already be resolved, i.e. valid output of this method.
Returns ------- dict Atomic CSS 2.2 properties.
Examples -------- >>> resolve = CSSResolver() >>> inherited = {"font-family": "serif", "font-weight": "bold"} >>> out = resolve( ... ''' ... border-color: BLUE RED; ... font-size: 1em; ... font-size: 2em; ... font-weight: normal; ... font-weight: inherit; ... ''', ... inherited, ... ) >>> sorted(out.items()) # doctest: +NORMALIZE_WHITESPACE [('border-bottom-color', 'blue'), ('border-left-color', 'red'), ('border-right-color', 'red'), ('border-top-color', 'blue'), ('font-family', 'serif'), ('font-size', '24pt'), ('font-weight', 'bold')] """ if isinstance(declarations, str): declarations = self.parse(declarations) props = dict(self.atomize(declarations)) if inherited is None: inherited = {}
props = self._update_initial(props, inherited) props = self._update_font_size(props, inherited) return self._update_other_units(props)
def _update_initial( self, props: dict[str, str], inherited: dict[str, str], ) -> dict[str, str]: # 1. resolve inherited, initial for prop, val in inherited.items(): if prop not in props: props[prop] = val
new_props = props.copy() for prop, val in props.items(): if val == "inherit": val = inherited.get(prop, "initial")
if val in ("initial", None): # we do not define a complete initial stylesheet del new_props[prop] else: new_props[prop] = val return new_props
def _update_font_size( self, props: dict[str, str], inherited: dict[str, str], ) -> dict[str, str]: # 2. resolve relative font size if props.get("font-size"): props["font-size"] = self.size_to_pt( props["font-size"], self._get_font_size(inherited), conversions=self.FONT_SIZE_RATIOS, ) return props
def _get_font_size(self, props: dict[str, str]) -> float | None: if props.get("font-size"): font_size_string = props["font-size"] return self._get_float_font_size_from_pt(font_size_string) return None
def _get_float_font_size_from_pt(self, font_size_string: str) -> float: assert font_size_string.endswith("pt") return float(font_size_string.rstrip("pt"))
def _update_other_units(self, props: dict[str, str]) -> dict[str, str]: font_size = self._get_font_size(props) # 3. TODO: resolve other font-relative units for side in self.SIDES: prop = f"border-{side}-width" if prop in props: props[prop] = self.size_to_pt( props[prop], em_pt=font_size, conversions=self.BORDER_WIDTH_RATIOS, )
for prop in [f"margin-{side}", f"padding-{side}"]: if prop in props: # TODO: support % props[prop] = self.size_to_pt( props[prop], em_pt=font_size, conversions=self.MARGIN_RATIOS, ) return props
def size_to_pt( self, in_val: str, em_pt: float | None = None, conversions: dict = UNIT_RATIOS ) -> str: def _error() -> str: warnings.warn( f"Unhandled size: {in_val!r}", CSSWarning, stacklevel=find_stack_level(), ) return self.size_to_pt("1!!default", conversions=conversions)
match = re.match(r"^(\S*?)([a-zA-Z%!].*)", in_val) if match is None: return _error()
val, unit = match.groups() if val == "": # hack for 'large' etc. val = 1 else: try: val = float(val) except ValueError: return _error()
while unit != "pt": if unit == "em": if em_pt is None: unit = "rem" else: val *= em_pt unit = "pt" continue
try: unit, mul = conversions[unit] except KeyError: return _error() val *= mul
val = round(val, 5) if int(val) == val: size_fmt = f"{int(val):d}pt" else: size_fmt = f"{val:f}pt" return size_fmt
def atomize(self, declarations: Iterable) -> Generator[tuple[str, str]]: for prop, value in declarations: prop = prop.lower() value = value.lower() if prop in self.CSS_EXPANSIONS: expand = self.CSS_EXPANSIONS[prop] yield from expand(self, prop, value) else: yield prop, value
def parse(self, declarations_str: str) -> Iterator[tuple[str, str]]: """ Generates (prop, value) pairs from declarations.
In a future version may generate parsed tokens from tinycss/tinycss2
Parameters ---------- declarations_str : str """ for decl in declarations_str.split(";"): if not decl.strip(): continue prop, sep, val = decl.partition(":") prop = prop.strip().lower() # TODO: don't lowercase case sensitive parts of values (strings) val = val.strip().lower() if sep: yield prop, val else: warnings.warn( f"Ill-formatted attribute: expected a colon in {decl!r}", CSSWarning, stacklevel=find_stack_level(), )123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336"""Module for formatting output data into CSV files."""
from __future__ import annotations
from collections.abc import ( Hashable, Iterable, Iterator, Sequence,)import csv as csvlibimport osfrom typing import ( TYPE_CHECKING, Any, cast,)
import numpy as np
from pandas._libs import writers as libwritersfrom pandas._typing import SequenceNotStrfrom pandas.util._decorators import cache_readonly
from pandas.core.dtypes.generic import ( ABCDatetimeIndex, ABCIndex, ABCMultiIndex, ABCPeriodIndex,)from pandas.core.dtypes.missing import notna
from pandas.core.indexes.api import Index
from pandas.io.common import get_handle
if TYPE_CHECKING: from pandas._typing import ( CompressionOptions, FilePath, FloatFormatType, IndexLabel, StorageOptions, WriteBuffer, npt, )
from pandas.io.formats.format import DataFrameFormatter
_DEFAULT_CHUNKSIZE_CELLS = 100_000
class CSVFormatter: cols: npt.NDArray[np.object_]
def __init__( self, formatter: DataFrameFormatter, path_or_buf: FilePath | WriteBuffer[str] | WriteBuffer[bytes] = "", sep: str = ",", cols: Sequence[Hashable] | None = None, index_label: IndexLabel | None = None, mode: str = "w", encoding: str | None = None, errors: str = "strict", compression: CompressionOptions = "infer", quoting: int | None = None, lineterminator: str | None = "\n", chunksize: int | None = None, quotechar: str | None = '"', date_format: str | None = None, doublequote: bool = True, escapechar: str | None = None, storage_options: StorageOptions | None = None, ) -> None: self.fmt = formatter
self.obj = self.fmt.frame
self.filepath_or_buffer = path_or_buf self.encoding = encoding self.compression: CompressionOptions = compression self.mode = mode self.storage_options = storage_options
self.sep = sep self.index_label = self._initialize_index_label(index_label) self.errors = errors self.quoting = quoting or csvlib.QUOTE_MINIMAL self.doublequote = doublequote self.escapechar = escapechar self.quotechar = self._initialize_quotechar(quotechar) self.lineterminator = lineterminator or os.linesep self.date_format = date_format self.cols = self._initialize_columns(cols) self.chunksize = self._initialize_chunksize(chunksize)
@property def na_rep(self) -> str: return self.fmt.na_rep
@property def float_format(self) -> FloatFormatType | None: return self.fmt.float_format
@property def decimal(self) -> str: return self.fmt.decimal
@property def header(self) -> bool | SequenceNotStr[str]: return self.fmt.header
@property def index(self) -> bool: return self.fmt.index
def _initialize_index_label(self, index_label: IndexLabel | None) -> IndexLabel: if index_label is not False: if index_label is None: return self._get_index_label_from_obj() elif not isinstance(index_label, (list, tuple, np.ndarray, ABCIndex)): # given a string for a DF with Index return [index_label] return index_label
def _get_index_label_from_obj(self) -> Sequence[Hashable]: if isinstance(self.obj.index, ABCMultiIndex): return self._get_index_label_multiindex() else: return self._get_index_label_flat()
def _get_index_label_multiindex(self) -> Sequence[Hashable]: return [name or "" for name in self.obj.index.names]
def _get_index_label_flat(self) -> Sequence[Hashable]: index_label = self.obj.index.name return [""] if index_label is None else [index_label]
def _initialize_quotechar(self, quotechar: str | None) -> str | None: if self.quoting != csvlib.QUOTE_NONE or self.escapechar is not None: # prevents crash in _csv return quotechar return None
@property def has_mi_columns(self) -> bool: return bool(isinstance(self.obj.columns, ABCMultiIndex))
def _initialize_columns( self, cols: Iterable[Hashable] | None ) -> npt.NDArray[np.object_]: # validate mi options if self.has_mi_columns: if cols is not None: msg = "cannot specify cols with a MultiIndex on the columns" raise TypeError(msg)
if cols is not None: if isinstance(cols, ABCIndex): cols = cols._get_values_for_csv(**self._number_format) else: cols = list(cols) self.obj = self.obj.loc[:, cols]
# update columns to include possible multiplicity of dupes # and make sure cols is just a list of labels new_cols = self.obj.columns return new_cols._get_values_for_csv(**self._number_format)
def _initialize_chunksize(self, chunksize: int | None) -> int: if chunksize is None: return (_DEFAULT_CHUNKSIZE_CELLS // (len(self.cols) or 1)) or 1 return int(chunksize)
@property def _number_format(self) -> dict[str, Any]: """Dictionary used for storing number formatting settings.""" return { "na_rep": self.na_rep, "float_format": self.float_format, "date_format": self.date_format, "quoting": self.quoting, "decimal": self.decimal, }
@cache_readonly def data_index(self) -> Index: data_index = self.obj.index if ( isinstance(data_index, (ABCDatetimeIndex, ABCPeriodIndex)) and self.date_format is not None ): data_index = Index( [x.strftime(self.date_format) if notna(x) else "" for x in data_index] ) elif isinstance(data_index, ABCMultiIndex): data_index = data_index.remove_unused_levels() return data_index
@property def nlevels(self) -> int: if self.index: return getattr(self.data_index, "nlevels", 1) else: return 0
@property def _has_aliases(self) -> bool: return isinstance(self.header, (tuple, list, np.ndarray, ABCIndex))
@property def _need_to_save_header(self) -> bool: return bool(self._has_aliases or self.header)
@property def write_cols(self) -> SequenceNotStr[Hashable]: if self._has_aliases: assert not isinstance(self.header, bool) if len(self.header) != len(self.cols): raise ValueError( f"Writing {len(self.cols)} cols but got {len(self.header)} aliases" ) return self.header else: # self.cols is an ndarray derived from Index._get_values_for_csv, # so its entries are strings, i.e. hashable return cast(SequenceNotStr[Hashable], self.cols)
@property def encoded_labels(self) -> list[Hashable]: encoded_labels: list[Hashable] = []
if self.index and self.index_label: assert isinstance(self.index_label, Sequence) encoded_labels = list(self.index_label)
if not self.has_mi_columns or self._has_aliases: encoded_labels += list(self.write_cols)
return encoded_labels
def save(self) -> None: """ Create the writer & save. """ # apply compression and byte/text conversion with get_handle( self.filepath_or_buffer, self.mode, encoding=self.encoding, errors=self.errors, compression=self.compression, storage_options=self.storage_options, ) as handles: # Note: self.encoding is irrelevant here # error: Argument "quoting" to "writer" has incompatible type "int"; # expected "Literal[0, 1, 2, 3]" self.writer = csvlib.writer( handles.handle, lineterminator=self.lineterminator, delimiter=self.sep, quoting=self.quoting, # type: ignore[arg-type] doublequote=self.doublequote, escapechar=self.escapechar, quotechar=self.quotechar, )
self._save()
def _save(self) -> None: if self._need_to_save_header: self._save_header() self._save_body()
def _save_header(self) -> None: if not self.has_mi_columns or self._has_aliases: self.writer.writerow(self.encoded_labels) else: for row in self._generate_multiindex_header_rows(): self.writer.writerow(row)
def _generate_multiindex_header_rows(self) -> Iterator[list[Hashable]]: columns = self.obj.columns for i in range(columns.nlevels): # we need at least 1 index column to write our col names col_line = [] if self.index: # name is the first column col_line.append(columns.names[i])
if isinstance(self.index_label, list) and len(self.index_label) > 1: col_line.extend([""] * (len(self.index_label) - 1))
col_line.extend(columns._get_level_values(i)) yield col_line
# Write out the index line if it's not empty. # Otherwise, we will print out an extraneous # blank line between the mi and the data rows. if self.encoded_labels and set(self.encoded_labels) != {""}: yield self.encoded_labels + [""] * len(columns)
def _save_body(self) -> None: nrows = len(self.data_index) chunks = (nrows // self.chunksize) + 1 for i in range(chunks): start_i = i * self.chunksize end_i = min(start_i + self.chunksize, nrows) if start_i >= end_i: break self._save_chunk(start_i, end_i)
def _save_chunk(self, start_i: int, end_i: int) -> None: # create the data for a chunk slicer = slice(start_i, end_i) df = self.obj.iloc[slicer]
res = df._get_values_for_csv(**self._number_format) data = list(res._iter_column_arrays())
ix = ( self.data_index[slicer]._get_values_for_csv(**self._number_format) if self.nlevels != 0 else np.empty(end_i - start_i) ) libwriters.write_csv_rows( data, ix, self.nlevels, self.cols, self.writer, )123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023"""Utilities for conversion to writer-agnostic Excel representation."""
from __future__ import annotations
from collections.abc import ( Callable, Hashable, Iterable, Mapping, Sequence,)import functoolsimport itertoolsimport refrom typing import ( TYPE_CHECKING, Any, cast,)import warnings
import numpy as np
from pandas._libs.lib import is_list_likefrom pandas.util._exceptions import find_stack_level
from pandas.core.dtypes import missingfrom pandas.core.dtypes.common import ( is_float, is_scalar,)
from pandas import ( DataFrame, Index, MultiIndex, Period, PeriodIndex,)import pandas.core.common as com
from pandas.io.formats._color_data import CSS4_COLORSfrom pandas.io.formats.css import ( CSSResolver, CSSWarning,)from pandas.io.formats.format import get_level_lengths
if TYPE_CHECKING: from pandas._typing import ( ExcelWriterMergeCells, FilePath, IndexLabel, StorageOptions, WriteExcelBuffer, )
from pandas import ExcelWriter
class ExcelCell: __fields__ = ("row", "col", "val", "style", "mergestart", "mergeend") __slots__ = __fields__
def __init__( self, row: int, col: int, val, style=None, mergestart: int | None = None, mergeend: int | None = None, ) -> None: self.row = row self.col = col self.val = val self.style = style self.mergestart = mergestart self.mergeend = mergeend
class CssExcelCell(ExcelCell): def __init__( self, row: int, col: int, val, style: dict | None, css_styles: dict[tuple[int, int], list[tuple[str, Any]]] | None, css_row: int, css_col: int, css_converter: Callable | None, **kwargs, ) -> None: if css_styles and css_converter: # Use dict to get only one (case-insensitive) declaration per property declaration_dict = { prop.lower(): val for prop, val in css_styles[css_row, css_col] } # Convert to frozenset for order-invariant caching unique_declarations = frozenset(declaration_dict.items()) style = css_converter(unique_declarations)
super().__init__(row=row, col=col, val=val, style=style, **kwargs)
class CSSToExcelConverter: """ A callable for converting CSS declarations to ExcelWriter styles
Supports parts of CSS 2.2, with minimal CSS 3.0 support (e.g. text-shadow), focusing on font styling, backgrounds, borders and alignment.
Operates by first computing CSS styles in a fairly generic way (see :meth:`compute_css`) then determining Excel style properties from CSS properties (see :meth:`build_xlstyle`).
Parameters ---------- inherited : str, optional CSS declarations understood to be the containing scope for the CSS processed by :meth:`__call__`. """
NAMED_COLORS = CSS4_COLORS
VERTICAL_MAP = { "top": "top", "text-top": "top", "middle": "center", "baseline": "bottom", "bottom": "bottom", "text-bottom": "bottom", # OpenXML also has 'justify', 'distributed' }
BOLD_MAP = { "bold": True, "bolder": True, "600": True, "700": True, "800": True, "900": True, "normal": False, "lighter": False, "100": False, "200": False, "300": False, "400": False, "500": False, }
ITALIC_MAP = { "normal": False, "italic": True, "oblique": True, }
FAMILY_MAP = { "serif": 1, # roman "sans-serif": 2, # swiss "cursive": 4, # script "fantasy": 5, # decorative }
BORDER_STYLE_MAP = { style.lower(): style for style in [ "dashed", "mediumDashDot", "dashDotDot", "hair", "dotted", "mediumDashDotDot", "double", "dashDot", "slantDashDot", "mediumDashed", ] }
# NB: Most of the methods here could be classmethods, as only __init__ # and __call__ make use of instance attributes. We leave them as # instancemethods so that users can easily experiment with extensions # without monkey-patching. inherited: dict[str, str] | None
def __init__(self, inherited: str | None = None) -> None: if inherited is not None: self.inherited = self.compute_css(inherited) else: self.inherited = None # We should avoid cache on the __call__ method. # Otherwise once the method __call__ has been called # garbage collection no longer deletes the instance. self._call_cached = functools.cache(self._call_uncached)
compute_css = CSSResolver()
def __call__( self, declarations: str | frozenset[tuple[str, str]] ) -> dict[str, dict[str, str]]: """ Convert CSS declarations to ExcelWriter style.
Parameters ---------- declarations : str | frozenset[tuple[str, str]] CSS string or set of CSS declaration tuples. e.g. "font-weight: bold; background: blue" or {("font-weight", "bold"), ("background", "blue")}
Returns ------- xlstyle : dict A style as interpreted by ExcelWriter when found in ExcelCell.style. """ return self._call_cached(declarations)
def _call_uncached( self, declarations: str | frozenset[tuple[str, str]] ) -> dict[str, dict[str, str]]: properties = self.compute_css(declarations, self.inherited) return self.build_xlstyle(properties)
def build_xlstyle(self, props: Mapping[str, str]) -> dict[str, dict[str, str]]: out = { "alignment": self.build_alignment(props), "border": self.build_border(props), "fill": self.build_fill(props), "font": self.build_font(props), "number_format": self.build_number_format(props), }
# TODO: handle cell width and height: needs support in pandas.io.excel
def remove_none(d: dict[str, str | None]) -> None: """Remove key where value is None, through nested dicts""" for k, v in list(d.items()): if v is None: del d[k] elif isinstance(v, dict): remove_none(v) if not v: del d[k]
remove_none(out) return out
def build_alignment(self, props: Mapping[str, str]) -> dict[str, bool | str | None]: # TODO: text-indent, padding-left -> alignment.indent return { "horizontal": props.get("text-align"), "vertical": self._get_vertical_alignment(props), "wrap_text": self._get_is_wrap_text(props), }
def _get_vertical_alignment(self, props: Mapping[str, str]) -> str | None: vertical_align = props.get("vertical-align") if vertical_align: return self.VERTICAL_MAP.get(vertical_align) return None
def _get_is_wrap_text(self, props: Mapping[str, str]) -> bool | None: if props.get("white-space") is None: return None return bool(props["white-space"] not in ("nowrap", "pre", "pre-line"))
def build_border( self, props: Mapping[str, str] ) -> dict[str, dict[str, str | None]]: return { side: { "style": self._border_style( props.get(f"border-{side}-style"), props.get(f"border-{side}-width"), self.color_to_excel(props.get(f"border-{side}-color")), ), "color": self.color_to_excel(props.get(f"border-{side}-color")), } for side in ["top", "right", "bottom", "left"] }
def _border_style( self, style: str | None, width: str | None, color: str | None ) -> str | None: # convert styles and widths to openxml, one of: # 'dashDot' # 'dashDotDot' # 'dashed' # 'dotted' # 'double' # 'hair' # 'medium' # 'mediumDashDot' # 'mediumDashDotDot' # 'mediumDashed' # 'slantDashDot' # 'thick' # 'thin' if width is None and style is None: if color is None: # Return None will remove "border" from style dictionary return None else: # Return "none" will keep "border" in style dictionary return "none"
if style in ("none", "hidden"): return "none"
width_name = self._get_width_name(width) if width_name is None: return "none"
if style in (None, "groove", "ridge", "inset", "outset", "solid"): # not handled return width_name
if style == "double": return "double" if style == "dotted": if width_name in ("hair", "thin"): return "dotted" return "mediumDashDotDot" if style == "dashed": if width_name in ("hair", "thin"): return "dashed" return "mediumDashed" elif style in self.BORDER_STYLE_MAP: # Excel-specific styles return self.BORDER_STYLE_MAP[style] else: warnings.warn( f"Unhandled border style format: {style!r}", CSSWarning, stacklevel=find_stack_level(), ) return "none"
def _get_width_name(self, width_input: str | None) -> str | None: width = self._width_to_float(width_input) if width < 1e-5: return None elif width < 1.3: return "thin" elif width < 2.8: return "medium" return "thick"
def _width_to_float(self, width: str | None) -> float: if width is None: width = "2pt" return self._pt_to_float(width)
def _pt_to_float(self, pt_string: str) -> float: assert pt_string.endswith("pt") return float(pt_string.rstrip("pt"))
def build_fill(self, props: Mapping[str, str]): # TODO: perhaps allow for special properties # -excel-pattern-bgcolor and -excel-pattern-type fill_color = props.get("background-color") if fill_color not in (None, "transparent", "none"): return {"fgColor": self.color_to_excel(fill_color), "patternType": "solid"}
def build_number_format(self, props: Mapping[str, str]) -> dict[str, str | None]: fc = props.get("number-format") fc = fc.replace("§", ";") if isinstance(fc, str) else fc return {"format_code": fc}
def build_font( self, props: Mapping[str, str] ) -> dict[str, bool | float | str | None]: font_names = self._get_font_names(props) decoration = self._get_decoration(props) return { "name": font_names[0] if font_names else None, "family": self._select_font_family(font_names), "size": self._get_font_size(props), "bold": self._get_is_bold(props), "italic": self._get_is_italic(props), "underline": ("single" if "underline" in decoration else None), "strike": ("line-through" in decoration) or None, "color": self.color_to_excel(props.get("color")), # shadow if nonzero digit before shadow color "shadow": self._get_shadow(props), }
def _get_is_bold(self, props: Mapping[str, str]) -> bool | None: weight = props.get("font-weight") if weight: return self.BOLD_MAP.get(weight) return None
def _get_is_italic(self, props: Mapping[str, str]) -> bool | None: font_style = props.get("font-style") if font_style: return self.ITALIC_MAP.get(font_style) return None
def _get_decoration(self, props: Mapping[str, str]) -> Sequence[str]: decoration = props.get("text-decoration") if decoration is not None: return decoration.split() else: return ()
def _get_shadow(self, props: Mapping[str, str]) -> bool | None: if "text-shadow" in props: return bool(re.search("^[^#(]*[1-9]", props["text-shadow"])) return None
def _get_font_names(self, props: Mapping[str, str]) -> Sequence[str]: font_names_tmp = re.findall( r"""(?x) ( "(?:[^"]|\\")+" | '(?:[^']|\\')+' | [^'",]+ )(?=,|\s*$) """, props.get("font-family", ""), )
font_names = [] for name in font_names_tmp: if name[:1] == '"': name = name[1:-1].replace('\\"', '"') elif name[:1] == "'": name = name[1:-1].replace("\\'", "'") else: name = name.strip() if name: font_names.append(name) return font_names
def _get_font_size(self, props: Mapping[str, str]) -> float | None: size = props.get("font-size") if size is None: return size return self._pt_to_float(size)
def _select_font_family(self, font_names: Sequence[str]) -> int | None: family = None for name in font_names: family = self.FAMILY_MAP.get(name) if family: break
return family
def color_to_excel(self, val: str | None) -> str | None: if val is None: return None
if self._is_hex_color(val): return self._convert_hex_to_excel(val)
try: return self.NAMED_COLORS[val] except KeyError: warnings.warn( f"Unhandled color format: {val!r}", CSSWarning, stacklevel=find_stack_level(), ) return None
def _is_hex_color(self, color_string: str) -> bool: return bool(color_string.startswith("#"))
def _convert_hex_to_excel(self, color_string: str) -> str: code = color_string.lstrip("#") if self._is_shorthand_color(color_string): return (code[0] * 2 + code[1] * 2 + code[2] * 2).upper() else: return code.upper()
def _is_shorthand_color(self, color_string: str) -> bool: """Check if color code is shorthand.
#FFF is a shorthand as opposed to full #FFFFFF. """ code = color_string.lstrip("#") if len(code) == 3: return True elif len(code) == 6: return False else: raise ValueError(f"Unexpected color {color_string}")
class ExcelFormatter: """ Class for formatting a DataFrame to a list of ExcelCells,
Parameters ---------- df : DataFrame or Styler na_rep: na representation float_format : str, default None Format string for floating point numbers cols : sequence, optional Columns to write header : bool or sequence of str, default True Write out column names. If a list of string is given it is assumed to be aliases for the column names index : bool, default True output row names (index) index_label : str or sequence, default None Column label for index column(s) if desired. If None is given, and `header` and `index` are True, then the index names are used. A sequence should be given if the DataFrame uses MultiIndex. merge_cells : bool or 'columns', default False Format MultiIndex column headers and Hierarchical Rows as merged cells if True. Merge MultiIndex column headers only if 'columns'. .. versionchanged:: 3.0.0 Added the 'columns' option. inf_rep : str, default `'inf'` representation for np.inf values (which aren't representable in Excel) A `'-'` sign will be added in front of -inf. style_converter : callable, optional This translates Styler styles (CSS) into ExcelWriter styles. Defaults to ``CSSToExcelConverter()``. It should have signature css_declarations string -> excel style. This is only called for body cells. autofilter : bool, default False If True, add automatic filters to all columns. """
max_rows = 2**20 max_cols = 2**14
def __init__( self, df, na_rep: str = "", float_format: str | None = None, cols: Sequence[Hashable] | None = None, header: Sequence[Hashable] | bool = True, index: bool = True, index_label: IndexLabel | None = None, merge_cells: ExcelWriterMergeCells = False, inf_rep: str = "inf", style_converter: Callable | None = None, autofilter: bool = False, ) -> None: self.rowcounter = 0 self.na_rep = na_rep if not isinstance(df, DataFrame): self.styler = df self.styler._compute() # calculate applied styles df = df.data if style_converter is None: style_converter = CSSToExcelConverter() self.style_converter: Callable | None = style_converter else: self.styler = None self.style_converter = None self.df = df if cols is not None: # all missing, raise if not len(Index(cols).intersection(df.columns)): raise KeyError("passes columns are not ALL present dataframe")
if len(Index(cols).intersection(df.columns)) != len(set(cols)): # Deprecated in GH#17295, enforced in 1.0.0 raise KeyError("Not all names specified in 'columns' are found")
self.df = df.reindex(columns=cols)
self.columns = self.df.columns self.float_format = float_format self.index = index self.index_label = index_label self.header = header
if not isinstance(merge_cells, bool) and merge_cells != "columns": raise ValueError(f"Unexpected value for {merge_cells=}.") self.merge_cells = merge_cells self.inf_rep = inf_rep self.autofilter = autofilter
def _format_value(self, val): if is_scalar(val) and missing.isna(val): val = self.na_rep elif is_float(val): if missing.isposinf_scalar(val): val = self.inf_rep elif missing.isneginf_scalar(val): val = f"-{self.inf_rep}" elif self.float_format is not None: val = float(self.float_format % val) if getattr(val, "tzinfo", None) is not None: raise ValueError( "Excel does not support datetimes with " "timezones. Please ensure that datetimes " "are timezone unaware before writing to Excel." ) return val
def _format_header_mi(self) -> Iterable[ExcelCell]: if self.columns.nlevels > 1: if not self.index: raise NotImplementedError( "Writing to Excel with MultiIndex columns and no " "index ('index'=False) is not yet implemented." )
if not (self._has_aliases or self.header): return
columns = self.columns merge_columns = self.merge_cells in {True, "columns"} level_strs = columns._format_multi(sparsify=merge_columns, include_names=False) level_lengths = get_level_lengths(level_strs) coloffset = 0 lnum = 0
if self.index and isinstance(self.df.index, MultiIndex): coloffset = self.df.index.nlevels - 1
for lnum, name in enumerate(columns.names): yield ExcelCell( row=lnum, col=coloffset, val=name, style=None, )
for lnum, (spans, levels, level_codes) in enumerate( zip(level_lengths, columns.levels, columns.codes, strict=True) ): values = levels.take(level_codes) for i, span_val in spans.items(): mergestart, mergeend = None, None if merge_columns and span_val > 1: mergestart, mergeend = lnum, coloffset + i + span_val yield CssExcelCell( row=lnum, col=coloffset + i + 1, val=values[i], style=None, css_styles=getattr(self.styler, "ctx_columns", None), css_row=lnum, css_col=i, css_converter=self.style_converter, mergestart=mergestart, mergeend=mergeend, ) self.rowcounter = lnum
def _format_header_regular(self) -> Iterable[ExcelCell]: if self._has_aliases or self.header: coloffset = 0
if self.index: coloffset = 1 if isinstance(self.df.index, MultiIndex): coloffset = len(self.df.index.names)
colnames = self.columns if self._has_aliases: self.header = cast(Sequence, self.header) if len(self.header) != len(self.columns): raise ValueError( f"Writing {len(self.columns)} cols " f"but got {len(self.header)} aliases" ) colnames = self.header
for colindex, colname in enumerate(colnames): yield CssExcelCell( row=self.rowcounter, col=colindex + coloffset, val=colname, style=None, css_styles=getattr(self.styler, "ctx_columns", None), css_row=0, css_col=colindex, css_converter=self.style_converter, )
def _format_header(self) -> Iterable[ExcelCell]: gen: Iterable[ExcelCell]
if isinstance(self.columns, MultiIndex): gen = self._format_header_mi() else: gen = self._format_header_regular()
gen2: Iterable[ExcelCell] = ()
if self.df.index.names: row = [x if x is not None else "" for x in self.df.index.names] + [ "" ] * len(self.columns) if functools.reduce(lambda x, y: x and y, (x != "" for x in row)): gen2 = ( ExcelCell(self.rowcounter, colindex, val, None) for colindex, val in enumerate(row) ) self.rowcounter += 1 return itertools.chain(gen, gen2)
def _format_body(self) -> Iterable[ExcelCell]: if isinstance(self.df.index, MultiIndex): return self._format_hierarchical_rows() else: return self._format_regular_rows()
def _format_regular_rows(self) -> Iterable[ExcelCell]: if self._has_aliases or self.header: self.rowcounter += 1
# output index and index_label? if self.index: # check aliases # if list only take first as this is not a MultiIndex if self.index_label and isinstance( self.index_label, (list, tuple, np.ndarray, Index) ): index_label = self.index_label[0] # if string good to go elif self.index_label and isinstance(self.index_label, str): index_label = self.index_label else: index_label = self.df.index.names[0]
if isinstance(self.columns, MultiIndex): self.rowcounter += 1
if index_label and self.header is not False: yield ExcelCell(self.rowcounter - 1, 0, index_label, None)
# write index_values index_values = self.df.index if isinstance(self.df.index, PeriodIndex): index_values = self.df.index.to_timestamp()
for idx, idxval in enumerate(index_values): yield CssExcelCell( row=self.rowcounter + idx, col=0, val=idxval, style=None, css_styles=getattr(self.styler, "ctx_index", None), css_row=idx, css_col=0, css_converter=self.style_converter, ) coloffset = 1 else: coloffset = 0
yield from self._generate_body(coloffset)
def _format_hierarchical_rows(self) -> Iterable[ExcelCell]: if self._has_aliases or self.header: self.rowcounter += 1
gcolidx = 0
if self.index: index_labels = self.df.index.names # check for aliases if self.index_label and isinstance( self.index_label, (list, tuple, np.ndarray, Index) ): index_labels = self.index_label
# MultiIndex columns require an extra row # with index names (blank if None) for # unambiguous round-trip, Issue #11328 if isinstance(self.columns, MultiIndex): self.rowcounter += 1
# if index labels are not empty go ahead and dump if com.any_not_none(*index_labels) and self.header is not False: for cidx, name in enumerate(index_labels): yield ExcelCell(self.rowcounter - 1, cidx, name, None)
if self.merge_cells and self.merge_cells != "columns": # Format hierarchical rows as merged cells. level_strs = self.df.index._format_multi( sparsify=True, include_names=False ) level_lengths = get_level_lengths(level_strs)
for spans, levels, level_codes in zip( level_lengths, self.df.index.levels, self.df.index.codes, strict=False, ): values = levels.take( level_codes, allow_fill=levels._can_hold_na, fill_value=levels._na_value, ) # GH#60099 if isinstance(values[0], Period): values = values.to_timestamp()
for i, span_val in spans.items(): mergestart, mergeend = None, None if span_val > 1: mergestart = self.rowcounter + i + span_val - 1 mergeend = gcolidx yield CssExcelCell( row=self.rowcounter + i, col=gcolidx, val=values[i], style=None, css_styles=getattr(self.styler, "ctx_index", None), css_row=i, css_col=gcolidx, css_converter=self.style_converter, mergestart=mergestart, mergeend=mergeend, ) gcolidx += 1
else: # Format hierarchical rows with non-merged values. for indexcolvals in zip(*self.df.index, strict=True): for idx, indexcolval in enumerate(indexcolvals): # GH#60099 if isinstance(indexcolval, Period): indexcolval = indexcolval.to_timestamp()
yield CssExcelCell( row=self.rowcounter + idx, col=gcolidx, val=indexcolval, style=None, css_styles=getattr(self.styler, "ctx_index", None), css_row=idx, css_col=gcolidx, css_converter=self.style_converter, ) gcolidx += 1
yield from self._generate_body(gcolidx)
@property def _has_aliases(self) -> bool: """Whether the aliases for column names are present.""" return is_list_like(self.header)
def _generate_body(self, coloffset: int) -> Iterable[ExcelCell]: # Write the body of the frame data series by series. for colidx in range(len(self.columns)): series = self.df.iloc[:, colidx] for i, val in enumerate(series): yield CssExcelCell( row=self.rowcounter + i, col=colidx + coloffset, val=val, style=None, css_styles=getattr(self.styler, "ctx", None), css_row=i, css_col=colidx, css_converter=self.style_converter, )
def get_formatted_cells(self) -> Iterable[ExcelCell]: for cell in itertools.chain(self._format_header(), self._format_body()): cell.val = self._format_value(cell.val) yield cell
def _num2excel(self, index: int) -> str: """ Convert 0-based column index to Excel column name.
Parameters ---------- index : int The numeric column index to convert to an Excel column name.
Returns ------- column_name : str The column name corresponding to the index.
Raises ------ ValueError Index is negative """ if index < 0: raise ValueError(f"Index cannot be negative: {index}") column_name = "" # while loop in case column name needs to be longer than 1 character while index > 0 or not column_name: index, remainder = divmod(index, 26) column_name = chr(65 + remainder) + column_name return column_name
def write( self, writer: FilePath | WriteExcelBuffer | ExcelWriter, sheet_name: str = "Sheet1", startrow: int = 0, startcol: int = 0, freeze_panes: tuple[int, int] | None = None, engine: str | None = None, storage_options: StorageOptions | None = None, engine_kwargs: dict | None = None, ) -> None: """ writer : path-like, file-like, or ExcelWriter object File path or existing ExcelWriter sheet_name : str, default 'Sheet1' Name of sheet which will contain DataFrame startrow : upper left cell row to dump data frame startcol : upper left cell column to dump data frame freeze_panes : tuple of integer (length 2), default None Specifies the one-based bottommost row and rightmost column that is to be frozen engine : string, default None write engine to use if writer is a path - you can also set this via the options ``io.excel.xlsx.writer``, or ``io.excel.xlsm.writer``.
storage_options : dict, optional 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.request.Request`` as header options. For other URLs (e.g. starting with "s3://", and "gcs://") the key-value pairs are forwarded to ``fsspec.open``. Please see ``fsspec`` and ``urllib`` for more details, and for more examples on storage options refer `here <https://pandas.pydata.org/docs/user_guide/io.html? highlight=storage_options#reading-writing-remote-files>`_.
engine_kwargs: dict, optional Arbitrary keyword arguments passed to excel engine. """ from pandas.io.excel import ExcelWriter
num_rows, num_cols = self.df.shape if num_rows > self.max_rows or num_cols > self.max_cols: raise ValueError( f"This sheet is too large! Your sheet size is: {num_rows}, {num_cols} " f"Max sheet size is: {self.max_rows}, {self.max_cols}" )
if self.autofilter: # default offset for header row startrowsoffset = 1 endrowsoffset = 1
if num_cols == 0: indexoffset = 0 elif self.index: indexoffset = 0 if isinstance(self.df.index, MultiIndex): if self.merge_cells: raise ValueError( "Excel filters merged cells by showing only the first row. " "'autofilter' and 'merge_cells' cannot " "be used simultaneously." ) else: indexoffset = self.df.index.nlevels - 1
if isinstance(self.columns, MultiIndex): if self.merge_cells: raise ValueError( "Excel filters merged cells by showing only the first row. " "'autofilter' and 'merge_cells' cannot " "be used simultaneously." ) else: startrowsoffset = self.columns.nlevels # multindex columns add a blank row between header and data endrowsoffset = self.columns.nlevels + 1 else: # no index column indexoffset = -1 start = f"{self._num2excel(startcol)}{startrow + startrowsoffset}" autofilter_end_column = self._num2excel(startcol + num_cols + indexoffset) end = f"{autofilter_end_column}{startrow + num_rows + endrowsoffset}" autofilter_range = f"{start}:{end}" else: autofilter_range = None
if engine_kwargs is None: engine_kwargs = {}
formatted_cells = self.get_formatted_cells() if isinstance(writer, ExcelWriter): need_save = False else: writer = ExcelWriter( writer, engine=engine, storage_options=storage_options, engine_kwargs=engine_kwargs, ) need_save = True
try: writer._write_cells( formatted_cells, sheet_name, startrow=startrow, startcol=startcol, freeze_panes=freeze_panes, autofilter_range=autofilter_range, ) finally: # make sure to close opened file handles if need_save: writer.close()1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080"""Internal module for formatting output data in csv, html, xml,and latex files. This module also applies to display formatting."""
from __future__ import annotations
from collections.abc import ( Callable, Generator, Hashable, Mapping, Sequence,)from contextlib import contextmanagerfrom csv import QUOTE_NONEfrom decimal import Decimalfrom functools import partialfrom io import StringIOimport mathimport refrom shutil import get_terminal_sizefrom typing import ( TYPE_CHECKING, Any, Final, cast,)
import numpy as np
from pandas._config.config import ( get_option, set_option,)
from pandas._libs import libfrom pandas._libs.missing import NAfrom pandas._libs.tslibs import ( NaT, Timedelta, Timestamp,)from pandas._libs.tslibs.nattype import NaTTypefrom pandas.util._decorators import set_module
from pandas.core.dtypes.common import ( is_complex_dtype, is_float, is_integer, is_list_like, is_numeric_dtype, is_scalar,)from pandas.core.dtypes.dtypes import ( CategoricalDtype, DatetimeTZDtype, ExtensionDtype,)from pandas.core.dtypes.missing import ( isna, notna,)
from pandas.core.arrays import ( Categorical, DatetimeArray, ExtensionArray, TimedeltaArray,)from pandas.core.base import PandasObjectimport pandas.core.common as comfrom pandas.core.indexes.api import ( Index, MultiIndex, PeriodIndex, ensure_index,)from pandas.core.indexes.datetimes import DatetimeIndexfrom pandas.core.indexes.timedeltas import TimedeltaIndex
from pandas.io.common import ( check_parent_directory, stringify_path,)from pandas.io.formats import printing
if TYPE_CHECKING: from pandas._typing import ( ArrayLike, Axes, ColspaceArgType, ColspaceType, CompressionOptions, FilePath, FloatFormatType, FormattersType, IndexLabel, SequenceNotStr, StorageOptions, WriteBuffer, )
from pandas import ( DataFrame, Series, )
common_docstring: Final = """ Parameters ---------- buf : str, Path or StringIO-like, optional, default None Buffer to write to. If None, the output is returned as a string. columns : array-like, optional, default None The subset of columns to write. Writes all columns by default. col_space : %(col_space_type)s, optional %(col_space)s header : %(header_type)s, optional %(header)s. index : bool, optional, default True Whether to print index (row) labels. na_rep : str, optional, default 'NaN' String representation of ``NaN`` to use. formatters : list, tuple or dict of one-param. functions, optional Formatter functions to apply to columns' elements by position or name. The result of each function must be a unicode string. List/tuple must be of length equal to the number of columns. float_format : one-parameter function, optional, default None Formatter function to apply to columns' elements if they are floats. This function must return a unicode string and will be applied only to the non-``NaN`` elements, with ``NaN`` being handled by ``na_rep``. sparsify : bool, optional, default True Set to False for a DataFrame with a hierarchical index to print every multiindex key at each row. index_names : bool, optional, default True Prints the names of the indexes. justify : str, default None How to justify the column labels. If None uses the option from the print configuration (controlled by set_option), 'right' out of the box. Valid values are
* left * right * center * justify * justify-all * start * end * inherit * match-parent * initial * unset. max_rows : int, optional Maximum number of rows to display in the console. max_cols : int, optional Maximum number of columns to display in the console. show_dimensions : bool, default False Display DataFrame dimensions (number of rows by number of columns). decimal : str, default '.' Character recognized as decimal separator, e.g. ',' in Europe. """
VALID_JUSTIFY_PARAMETERS = ( "left", "right", "center", "justify", "justify-all", "start", "end", "inherit", "match-parent", "initial", "unset",)
return_docstring: Final = """ Returns ------- str or None If buf is None, returns the result as a string. Otherwise returns None. """
class SeriesFormatter: """ Implement the main logic of Series.to_string, which underlies Series.__repr__. """
def __init__( self, series: Series, *, length: bool | str = True, header: bool = True, index: bool = True, na_rep: str = "NaN", name: bool = False, float_format: str | None = None, dtype: bool = True, max_rows: int | None = None, min_rows: int | None = None, ) -> None: self.series = series self.buf = StringIO() self.name = name self.na_rep = na_rep self.header = header self.length = length self.index = index self.max_rows = max_rows self.min_rows = min_rows
if float_format is None: float_format = get_option("display.float_format") self.float_format = float_format self.dtype = dtype self.adj = printing.get_adjustment()
self._chk_truncate()
def _chk_truncate(self) -> None: self.tr_row_num: int | None
min_rows = self.min_rows max_rows = self.max_rows # truncation determined by max_rows, actual truncated number of rows # used below by min_rows is_truncated_vertically = max_rows and (len(self.series) > max_rows) series = self.series if is_truncated_vertically: max_rows = cast(int, max_rows) if min_rows: # if min_rows is set (not None or 0), set max_rows to minimum # of both max_rows = min(min_rows, max_rows) if max_rows == 1: row_num = max_rows series = series.iloc[:max_rows] else: row_num = max_rows // 2 _len = len(series) _slice = np.hstack( [np.arange(row_num), np.arange(_len - row_num, _len)] ) series = series.iloc[_slice] self.tr_row_num = row_num else: self.tr_row_num = None self.tr_series = series self.is_truncated_vertically = is_truncated_vertically
def _get_footer(self) -> str: name = self.series.name footer = ""
index = self.series.index if ( isinstance(index, (DatetimeIndex, PeriodIndex, TimedeltaIndex)) and index.freq is not None ): footer += f"Freq: {index.freqstr}"
if self.name is not False and name is not None: if footer: footer += ", "
series_name = printing.pprint_thing(name, escape_chars=("\t", "\r", "\n")) footer += f"Name: {series_name}"
if self.length is True or ( self.length == "truncate" and self.is_truncated_vertically ): if footer: footer += ", " footer += f"Length: {len(self.series)}"
if self.dtype is not False and self.dtype is not None: dtype_name = getattr(self.tr_series.dtype, "name", None) if dtype_name: if footer: footer += ", " footer += f"dtype: {printing.pprint_thing(dtype_name)}"
# level infos are added to the end and in a new line, like it is done # for Categoricals if isinstance(self.tr_series.dtype, CategoricalDtype): level_info = self.tr_series._values._get_repr_footer() if footer: footer += "\n" footer += level_info
return str(footer)
def _get_formatted_values(self) -> list[str]: return format_array( self.tr_series._values, None, float_format=self.float_format, na_rep=self.na_rep, leading_space=self.index, )
def to_string(self) -> str: series = self.tr_series footer = self._get_footer()
if len(series) == 0: return f"{type(self.series).__name__}([], {footer})"
index = series.index have_header = _has_names(index) if isinstance(index, MultiIndex): fmt_index = index._format_multi(include_names=True, sparsify=None) adj = printing.get_adjustment() fmt_index = adj.adjoin(2, *fmt_index).split("\n") else: fmt_index = index._format_flat(include_name=True) fmt_values = self._get_formatted_values()
if self.is_truncated_vertically: n_header_rows = 0 row_num = self.tr_row_num row_num = cast(int, row_num) width = self.adj.len(fmt_values[row_num - 1]) if width > 3: dot_str = "..." else: dot_str = ".." # Series uses mode=center because it has single value columns # DataFrame uses mode=left dot_str = self.adj.justify([dot_str], width, mode="center")[0] fmt_values.insert(row_num + n_header_rows, dot_str) fmt_index.insert(row_num + 1, "")
if self.index: result = self.adj.adjoin(3, *[fmt_index[1:], fmt_values]) else: result = self.adj.adjoin(3, fmt_values)
if self.header and have_header: result = fmt_index[0] + "\n" + result
if footer: result += "\n" + footer
return str("".join(result))
def get_dataframe_repr_params() -> dict[str, Any]: """Get the parameters used to repr(dataFrame) calls using DataFrame.to_string.
Supplying these parameters to DataFrame.to_string is equivalent to calling ``repr(DataFrame)``. This is useful if you want to adjust the repr output.
Example ------- >>> import pandas as pd >>> >>> df = pd.DataFrame([[1, 2], [3, 4]]) >>> repr_params = pd.io.formats.format.get_dataframe_repr_params() >>> repr(df) == df.to_string(**repr_params) True """ from pandas.io.formats import console
if get_option("display.expand_frame_repr"): line_width, _ = console.get_console_size() else: line_width = None return { "max_rows": get_option("display.max_rows"), "min_rows": get_option("display.min_rows"), "max_cols": get_option("display.max_columns"), "max_colwidth": get_option("display.max_colwidth"), "show_dimensions": get_option("display.show_dimensions"), "line_width": line_width, }
def get_series_repr_params() -> dict[str, Any]: """Get the parameters used to repr(Series) calls using Series.to_string.
Supplying these parameters to Series.to_string is equivalent to calling ``repr(series)``. This is useful if you want to adjust the series repr output.
Example ------- >>> import pandas as pd >>> >>> ser = pd.Series([1, 2, 3, 4]) >>> repr_params = pd.io.formats.format.get_series_repr_params() >>> repr(ser) == ser.to_string(**repr_params) True """ width, height = get_terminal_size() max_rows_opt = get_option("display.max_rows") max_rows = height if max_rows_opt == 0 else max_rows_opt min_rows = height if max_rows_opt == 0 else get_option("display.min_rows")
return { "name": True, "dtype": True, "min_rows": min_rows, "max_rows": max_rows, "length": get_option("display.show_dimensions"), }
class DataFrameFormatter: """ Class for processing dataframe formatting options and data.
Used by DataFrame.to_string, which backs DataFrame.__repr__. """
__doc__ = __doc__ if __doc__ else "" __doc__ += common_docstring + return_docstring
def __init__( self, frame: DataFrame, columns: Axes | None = None, col_space: ColspaceArgType | None = None, header: bool | SequenceNotStr[str] = True, index: bool = True, na_rep: str = "NaN", formatters: FormattersType | None = None, justify: str | None = None, float_format: FloatFormatType | None = None, sparsify: bool | None = None, index_names: bool = True, max_rows: int | None = None, min_rows: int | None = None, max_cols: int | None = None, show_dimensions: bool | str = False, decimal: str = ".", bold_rows: bool = False, escape: bool = True, ) -> None: self.frame = frame self.columns = self._initialize_columns(columns) self.col_space = self._initialize_colspace(col_space) self.header = header self.index = index self.na_rep = na_rep self.formatters = self._initialize_formatters(formatters) self.justify = self._initialize_justify(justify) self.float_format = self._validate_float_format(float_format) self.sparsify = self._initialize_sparsify(sparsify) self.show_index_names = index_names self.decimal = decimal self.bold_rows = bold_rows self.escape = escape self.max_rows = max_rows self.min_rows = min_rows self.max_cols = max_cols self.show_dimensions = show_dimensions
self.max_cols_fitted = self._calc_max_cols_fitted() self.max_rows_fitted = self._calc_max_rows_fitted()
self.tr_frame = self.frame self.truncate() self.adj = printing.get_adjustment()
def get_strcols(self) -> list[list[str]]: """ Render a DataFrame to a list of columns (as lists of strings). """ strcols = self._get_strcols_without_index()
if self.index: str_index = self._get_formatted_index(self.tr_frame) strcols.insert(0, str_index)
return strcols
@property def should_show_dimensions(self) -> bool: return self.show_dimensions is True or ( self.show_dimensions == "truncate" and self.is_truncated )
@property def is_truncated(self) -> bool: return bool(self.is_truncated_horizontally or self.is_truncated_vertically)
@property def is_truncated_horizontally(self) -> bool: return bool(self.max_cols_fitted and (len(self.columns) > self.max_cols_fitted))
@property def is_truncated_vertically(self) -> bool: return bool(self.max_rows_fitted and (len(self.frame) > self.max_rows_fitted))
@property def dimensions_info(self) -> str: return f"\n\n[{len(self.frame)} rows x {len(self.frame.columns)} columns]"
@property def has_index_names(self) -> bool: return _has_names(self.frame.index)
@property def has_column_names(self) -> bool: return _has_names(self.frame.columns)
@property def show_row_idx_names(self) -> bool: return all((self.has_index_names, self.index, self.show_index_names))
@property def show_col_idx_names(self) -> bool: return all((self.has_column_names, self.show_index_names, self.header))
@property def max_rows_displayed(self) -> int: return min(self.max_rows or len(self.frame), len(self.frame))
def _initialize_sparsify(self, sparsify: bool | None) -> bool: if sparsify is None: return get_option("display.multi_sparse") return sparsify
def _initialize_formatters( self, formatters: FormattersType | None ) -> FormattersType: if formatters is None: return {} elif len(self.frame.columns) == len(formatters) or isinstance(formatters, dict): return formatters else: raise ValueError( f"Formatters length({len(formatters)}) should match " f"DataFrame number of columns({len(self.frame.columns)})" )
def _initialize_justify(self, justify: str | None) -> str: if justify is None: return get_option("display.colheader_justify") else: return justify
def _initialize_columns(self, columns: Axes | None) -> Index: if columns is not None: cols = ensure_index(columns) self.frame = self.frame[cols] return cols else: return self.frame.columns
def _initialize_colspace(self, col_space: ColspaceArgType | None) -> ColspaceType: result: ColspaceType
if col_space is None: result = {} elif isinstance(col_space, (int, str)): result = {"": col_space} result.update(dict.fromkeys(self.frame.columns, col_space)) elif isinstance(col_space, Mapping): for column in col_space.keys(): if column not in self.frame.columns and column != "": raise ValueError( f"Col_space is defined for an unknown column: {column}" ) result = col_space else: if len(self.frame.columns) != len(col_space): raise ValueError( f"Col_space length({len(col_space)}) should match " f"DataFrame number of columns({len(self.frame.columns)})" ) result = dict(zip(self.frame.columns, col_space, strict=True)) return result
def _calc_max_cols_fitted(self) -> int | None: """Number of columns fitting the screen.""" if not self._is_in_terminal(): return self.max_cols
width, _ = get_terminal_size() if self._is_screen_narrow(width): return width else: return self.max_cols
def _calc_max_rows_fitted(self) -> int | None: """Number of rows with data fitting the screen.""" max_rows: int | None
if self._is_in_terminal(): _, height = get_terminal_size() if self.max_rows == 0: # rows available to fill with actual data return height - self._get_number_of_auxiliary_rows()
if self._is_screen_short(height): max_rows = height else: max_rows = self.max_rows else: max_rows = self.max_rows
return self._adjust_max_rows(max_rows)
def _adjust_max_rows(self, max_rows: int | None) -> int | None: """Adjust max_rows using display logic.
See description here: https://pandas.pydata.org/docs/dev/user_guide/options.html#frequently-used-options
GH #37359 """ if max_rows: if (len(self.frame) > max_rows) and self.min_rows: # if truncated, set max_rows showed to min_rows max_rows = min(self.min_rows, max_rows) return max_rows
def _is_in_terminal(self) -> bool: """Check if the output is to be shown in terminal.""" return bool(self.max_cols == 0 or self.max_rows == 0)
def _is_screen_narrow(self, max_width) -> bool: return bool(self.max_cols == 0 and len(self.frame.columns) > max_width)
def _is_screen_short(self, max_height) -> bool: return bool(self.max_rows == 0 and len(self.frame) > max_height)
def _get_number_of_auxiliary_rows(self) -> int: """Get number of rows occupied by prompt, dots and dimension info.""" dot_row = 1 prompt_row = 1 num_rows = dot_row + prompt_row
if self.show_dimensions: num_rows += len(self.dimensions_info.splitlines())
if self.header: num_rows += 1
return num_rows
def truncate(self) -> None: """ Check whether the frame should be truncated. If so, slice the frame up. """ if self.is_truncated_horizontally: self._truncate_horizontally()
if self.is_truncated_vertically: self._truncate_vertically()
def _truncate_horizontally(self) -> None: """Remove columns, which are not to be displayed and adjust formatters.
Attributes affected: - tr_frame - formatters - tr_col_num """ assert self.max_cols_fitted is not None col_num = self.max_cols_fitted // 2 if col_num >= 1: _len = len(self.tr_frame.columns) _slice = np.hstack([np.arange(col_num), np.arange(_len - col_num, _len)]) self.tr_frame = self.tr_frame.iloc[:, _slice]
# truncate formatter if isinstance(self.formatters, (list, tuple)): self.formatters = [ *self.formatters[:col_num], *self.formatters[-col_num:], ] else: col_num = cast(int, self.max_cols) self.tr_frame = self.tr_frame.iloc[:, :col_num] self.tr_col_num: int = col_num
def _truncate_vertically(self) -> None: """Remove rows, which are not to be displayed.
Attributes affected: - tr_frame - tr_row_num """ assert self.max_rows_fitted is not None row_num = self.max_rows_fitted // 2 if row_num >= 1: _len = len(self.tr_frame) _slice = np.hstack([np.arange(row_num), np.arange(_len - row_num, _len)]) self.tr_frame = self.tr_frame.iloc[_slice] else: row_num = cast(int, self.max_rows) self.tr_frame = self.tr_frame.iloc[:row_num, :] self.tr_row_num = row_num
def _get_strcols_without_index(self) -> list[list[str]]: strcols: list[list[str]] = []
if not is_list_like(self.header) and not self.header: for i, c in enumerate(self.tr_frame): fmt_values = self.format_col(i) fmt_values = _make_fixed_width( strings=fmt_values, justify=self.justify, minimum=int(self.col_space.get(c, 0)), adj=self.adj, ) strcols.append(fmt_values) return strcols
if is_list_like(self.header): # cast here since can't be bool if is_list_like self.header = cast(list[str], self.header) if len(self.header) != len(self.columns): raise ValueError( f"Writing {len(self.columns)} cols " f"but got {len(self.header)} aliases" ) str_columns = [[label] for label in self.header] else: str_columns = self._get_formatted_column_labels(self.tr_frame)
if self.show_row_idx_names: for x in str_columns: x.append("")
for i, c in enumerate(self.tr_frame): cheader = str_columns[i] header_colwidth = max( int(self.col_space.get(c, 0)), *(self.adj.len(x) for x in cheader) ) fmt_values = self.format_col(i) fmt_values = _make_fixed_width( fmt_values, self.justify, minimum=header_colwidth, adj=self.adj )
max_len = max(*(self.adj.len(x) for x in fmt_values), header_colwidth) cheader = self.adj.justify(cheader, max_len, mode=self.justify) strcols.append(cheader + fmt_values)
return strcols
def format_col(self, i: int) -> list[str]: frame = self.tr_frame formatter = self._get_formatter(i) return format_array( frame.iloc[:, i]._values, formatter, float_format=self.float_format, na_rep=self.na_rep, space=self.col_space.get(frame.columns[i]), decimal=self.decimal, leading_space=self.index, )
def _get_formatter(self, i: str | int) -> Callable | None: if isinstance(self.formatters, (list, tuple)): if is_integer(i): i = cast(int, i) return self.formatters[i] else: return None else: if is_integer(i) and i not in self.columns: i = self.columns[i] return self.formatters.get(i, None)
def _get_formatted_column_labels(self, frame: DataFrame) -> list[list[str]]: from pandas.core.indexes.multi import sparsify_labels
columns = frame.columns
if isinstance(columns, MultiIndex): fmt_columns = columns._format_multi(sparsify=False, include_names=False) if self.sparsify and len(fmt_columns): fmt_columns = sparsify_labels(fmt_columns)
str_columns = [list(x) for x in zip(*fmt_columns, strict=True)] else: fmt_columns = columns._format_flat(include_name=False) str_columns = [ [ " " + x if not self._get_formatter(i) and is_numeric_dtype(dtype) else x ] for i, (x, dtype) in enumerate( zip(fmt_columns, self.frame.dtypes, strict=False) ) ] return str_columns
def _get_formatted_index(self, frame: DataFrame) -> list[str]: # Note: this is only used by to_string() and to_latex(), not by # to_html(). so safe to cast col_space here. col_space = {k: cast(int, v) for k, v in self.col_space.items()} index = frame.index columns = frame.columns fmt = self._get_formatter("__index__")
if isinstance(index, MultiIndex): fmt_index = index._format_multi( sparsify=self.sparsify, include_names=self.show_row_idx_names, formatter=fmt, ) else: fmt_index = [ index._format_flat(include_name=self.show_row_idx_names, formatter=fmt) ]
fmt_index = [ tuple( _make_fixed_width( list(x), justify="left", minimum=col_space.get("", 0), adj=self.adj ) ) for x in fmt_index ]
adjoined = self.adj.adjoin(1, *fmt_index).split("\n")
# empty space for columns if self.show_col_idx_names: col_header = [str(x) for x in self._get_column_name_list()] else: col_header = [""] * columns.nlevels
if self.header: return col_header + adjoined else: return adjoined
def _get_column_name_list(self) -> list[Hashable]: names: list[Hashable] = [] columns = self.frame.columns if isinstance(columns, MultiIndex): names.extend("" if name is None else name for name in columns.names) else: names.append("" if columns.name is None else columns.name) return names
def _validate_float_format( self, fmt: FloatFormatType | None ) -> FloatFormatType | None: """ Validates and processes the float_format argument. Converts new-style format strings to callables. """ if fmt is None or callable(fmt): return fmt
if isinstance(fmt, str): if "%" in fmt: # Keeps old-style format strings as they are (C code handles them) return fmt else: try: _ = fmt.format(1.0) # Test with an arbitrary float return fmt.format except (ValueError, KeyError, IndexError) as e: raise ValueError(f"Invalid new-style format string {fmt!r}") from e
raise ValueError("float_format must be a string or callable")
class DataFrameRenderer: """Class for creating dataframe output in multiple formats.
Called in pandas.core.generic.NDFrame: - to_csv - to_latex
Called in pandas.DataFrame: - to_html - to_string
Parameters ---------- fmt : DataFrameFormatter Formatter with the formatting options. """
def __init__(self, fmt: DataFrameFormatter) -> None: self.fmt = fmt
def to_html( self, buf: FilePath | WriteBuffer[str] | None = None, encoding: str | None = None, classes: str | list | tuple | None = None, notebook: bool = False, border: int | bool | None = None, table_id: str | None = None, render_links: bool = False, ) -> str | None: """ Render a DataFrame to an html table.
Parameters ---------- buf : str, path object, file-like object, or None, default None String, path object (implementing ``os.PathLike[str]``), or file-like object implementing a string ``write()`` function. If None, the result is returned as a string. encoding : str, default “utf-8” Set character encoding. classes : str or list-like classes to include in the `class` attribute of the opening ``<table>`` tag, in addition to the default "dataframe". notebook : {True, False}, optional, default False Whether the generated HTML is for IPython Notebook. border : int or bool When an integer value is provided, it sets the border attribute in the opening tag, specifying the thickness of the border. If ``False`` or ``0`` is passed, the border attribute will not be present in the ``<table>`` tag. The default value for this parameter is governed by ``pd.options.display.html.border``. table_id : str, optional A css id is included in the opening `<table>` tag if specified. render_links : bool, default False Convert URLs to HTML links. """ from pandas.io.formats.html import ( HTMLFormatter, NotebookFormatter, )
Klass = NotebookFormatter if notebook else HTMLFormatter
html_formatter = Klass( self.fmt, classes=classes, border=border, table_id=table_id, render_links=render_links, ) string = html_formatter.to_string() return save_to_buffer(string, buf=buf, encoding=encoding)
def to_string( self, buf: FilePath | WriteBuffer[str] | None = None, encoding: str | None = None, line_width: int | None = None, ) -> str | None: """ Render a DataFrame to a console-friendly tabular output.
Parameters ---------- buf : str, path object, file-like object, or None, default None String, path object (implementing ``os.PathLike[str]``), or file-like object implementing a string ``write()`` function. If None, the result is returned as a string. encoding: str, default “utf-8” Set character encoding. line_width : int, optional Width to wrap a line in characters. """ from pandas.io.formats.string import StringFormatter
string_formatter = StringFormatter(self.fmt, line_width=line_width) string = string_formatter.to_string() return save_to_buffer(string, buf=buf, encoding=encoding)
def to_csv( self, path_or_buf: FilePath | WriteBuffer[bytes] | WriteBuffer[str] | None = None, encoding: str | None = None, sep: str = ",", columns: Sequence[Hashable] | None = None, index_label: IndexLabel | None = None, mode: str = "w", compression: CompressionOptions = "infer", quoting: int | None = None, quotechar: str = '"', lineterminator: str | None = None, chunksize: int | None = None, date_format: str | None = None, doublequote: bool = True, escapechar: str | None = None, errors: str = "strict", storage_options: StorageOptions | None = None, ) -> str | None: """ Render dataframe as comma-separated file. """ from pandas.io.formats.csvs import CSVFormatter
if path_or_buf is None: created_buffer = True path_or_buf = StringIO() else: created_buffer = False
csv_formatter = CSVFormatter( path_or_buf=path_or_buf, lineterminator=lineterminator, sep=sep, encoding=encoding, errors=errors, compression=compression, quoting=quoting, cols=columns, index_label=index_label, mode=mode, chunksize=chunksize, quotechar=quotechar, date_format=date_format, doublequote=doublequote, escapechar=escapechar, storage_options=storage_options, formatter=self.fmt, ) csv_formatter.save()
if created_buffer: assert isinstance(path_or_buf, StringIO) content = path_or_buf.getvalue() path_or_buf.close() return content
return None
def save_to_buffer( string: str, buf: FilePath | WriteBuffer[str] | None = None, encoding: str | None = None,) -> str | None: """ Perform serialization. Write to buf or return as string if buf is None. """ with _get_buffer(buf, encoding=encoding) as fd: fd.write(string) if buf is None: # error: "WriteBuffer[str]" has no attribute "getvalue" return fd.getvalue() # type: ignore[attr-defined] return None
@contextmanagerdef _get_buffer( buf: FilePath | WriteBuffer[str] | None, encoding: str | None = None) -> Generator[WriteBuffer[str]] | Generator[StringIO]: """ Context manager to open, yield and close buffer for filenames or Path-like objects, otherwise yield buf unchanged. """ if buf is not None: buf = stringify_path(buf) else: buf = StringIO()
if encoding is None: encoding = "utf-8" elif not isinstance(buf, str): raise ValueError("buf is not a file name and encoding is specified.")
if hasattr(buf, "write"): # Incompatible types in "yield" (actual type "Union[str, WriteBuffer[str], # StringIO]", expected type "Union[WriteBuffer[str], StringIO]") yield buf # type: ignore[misc] elif isinstance(buf, str): check_parent_directory(str(buf)) with open(buf, "w", encoding=encoding, newline="") as f: # GH#30034 open instead of codecs.open prevents a file leak # if we have an invalid encoding argument. # newline="" is needed to roundtrip correctly on # windows test_to_latex_filename yield f else: raise TypeError("buf is not a file name and it has no write method")
# ----------------------------------------------------------------------# Array formatters
def format_array( values: ArrayLike, formatter: Callable | None, float_format: FloatFormatType | None = None, na_rep: str = "NaN", digits: int | None = None, space: str | int | None = None, justify: str = "right", decimal: str = ".", leading_space: bool | None = True, quoting: int | None = None, fallback_formatter: Callable | None = None,) -> list[str]: """ Format an array for printing.
Parameters ---------- values : np.ndarray or ExtensionArray formatter float_format na_rep digits space justify decimal leading_space : bool, optional, default True Whether the array should be formatted with a leading space. When an array as a column of a Series or DataFrame, we do want the leading space to pad between columns.
When formatting an Index subclass (e.g. IntervalIndex._get_values_for_csv), we don't want the leading space since it should be left-aligned. fallback_formatter
Returns ------- List[str] """ fmt_klass: type[_GenericArrayFormatter] if lib.is_np_dtype(values.dtype, "M"): fmt_klass = _Datetime64Formatter values = cast(DatetimeArray, values) elif isinstance(values.dtype, DatetimeTZDtype): fmt_klass = _Datetime64TZFormatter values = cast(DatetimeArray, values) elif lib.is_np_dtype(values.dtype, "m"): fmt_klass = _Timedelta64Formatter values = cast(TimedeltaArray, values) elif isinstance(values.dtype, ExtensionDtype): fmt_klass = _ExtensionArrayFormatter elif lib.is_np_dtype(values.dtype, "fc"): fmt_klass = FloatArrayFormatter elif lib.is_np_dtype(values.dtype, "iu"): fmt_klass = _IntArrayFormatter else: fmt_klass = _GenericArrayFormatter
if space is None: space = 12
if float_format is None: float_format = get_option("display.float_format")
if digits is None: digits = get_option("display.precision")
fmt_obj = fmt_klass( values, digits=digits, na_rep=na_rep, float_format=float_format, formatter=formatter, space=space, justify=justify, decimal=decimal, leading_space=leading_space, quoting=quoting, fallback_formatter=fallback_formatter, )
return fmt_obj.get_result()
class _GenericArrayFormatter: def __init__( self, values: ArrayLike, digits: int = 7, formatter: Callable | None = None, na_rep: str = "NaN", space: str | int = 12, float_format: FloatFormatType | None = None, justify: str = "right", decimal: str = ".", quoting: int | None = None, fixed_width: bool = True, leading_space: bool | None = True, fallback_formatter: Callable | None = None, ) -> None: self.values = values self.digits = digits self.na_rep = na_rep self.space = space self.formatter = formatter self.float_format = float_format self.justify = justify self.decimal = decimal self.quoting = quoting self.fixed_width = fixed_width self.leading_space = leading_space self.fallback_formatter = fallback_formatter
def get_result(self) -> list[str]: fmt_values = self._format_strings() return _make_fixed_width(fmt_values, self.justify)
def _format_strings(self) -> list[str]: if self.float_format is None: float_format = get_option("display.float_format") if float_format is None: precision = get_option("display.precision") float_format = lambda x: _trim_zeros_single_float( f"{x: .{precision:d}f}" ) else: float_format = self.float_format
if self.formatter is not None: formatter = self.formatter elif self.fallback_formatter is not None: formatter = self.fallback_formatter else: quote_strings = self.quoting is not None and self.quoting != QUOTE_NONE formatter = partial( printing.pprint_thing, escape_chars=("\t", "\r", "\n"), quote_strings=quote_strings, )
def _format(x): if self.na_rep is not None and is_scalar(x) and isna(x): if x is None: return "None" elif x is NA: return str(NA) elif x is NaT or isinstance(x, (np.datetime64, np.timedelta64)): return "NaT" return self.na_rep elif isinstance(x, PandasObject): return str(x) else: # object dtype return str(formatter(x))
vals = self.values if not isinstance(vals, np.ndarray): raise TypeError( "ExtensionArray formatting should use _ExtensionArrayFormatter" ) inferred = lib.map_infer(vals, is_float) is_float_type = ( inferred # vals may have 2 or more dimensions & np.all(notna(vals), axis=tuple(range(1, len(vals.shape)))) ) leading_space = self.leading_space if leading_space is None: leading_space = is_float_type.any()
fmt_values = [] for i, v in enumerate(vals): if (not is_float_type[i] or self.formatter is not None) and leading_space: fmt_values.append(f" {_format(v)}") elif is_float_type[i]: fmt_values.append(float_format(v)) else: if leading_space is False: # False specifically, so that the default is # to include a space if we get here. tpl = "{v}" else: tpl = " {v}" fmt_values.append(tpl.format(v=_format(v)))
return fmt_values
class FloatArrayFormatter(_GenericArrayFormatter): def __init__(self, *args, **kwargs) -> None: super().__init__(*args, **kwargs)
# float_format is expected to be a string # formatter should be used to pass a function if self.float_format is not None and self.formatter is None: # GH21625, GH22270 self.fixed_width = False if callable(self.float_format): self.formatter = self.float_format self.float_format = None
def _value_formatter( self, float_format: FloatFormatType | None = None, threshold: float | None = None, ) -> Callable: """Returns a function to be applied on each value to format it""" # the float_format parameter supersedes self.float_format if float_format is None: float_format = self.float_format
# we are going to compose different functions, to first convert to # a string, then replace the decimal symbol, and finally chop according # to the threshold
# when there is no float_format, we use str instead of '%g' # because str(0.0) = '0.0' while '%g' % 0.0 = '0' if float_format:
def base_formatter(v): assert float_format is not None # for mypy # error: "str" not callable # error: Unexpected keyword argument "value" for "__call__" of # "EngFormatter" return ( float_format(value=v) # type: ignore[operator,call-arg] if notna(v) else self.na_rep )
else:
def base_formatter(v): return str(v) if notna(v) else self.na_rep
if self.decimal != ".":
def decimal_formatter(v): return base_formatter(v).replace(".", self.decimal, 1)
else: decimal_formatter = base_formatter
if threshold is None: return decimal_formatter
def formatter(value): if notna(value): if abs(value) > threshold: return decimal_formatter(value) else: return decimal_formatter(0.0) else: return self.na_rep
return formatter
def get_result_as_array(self) -> np.ndarray: """ Returns the float values converted into strings using the parameters given at initialisation, as a numpy array """
def format_with_na_rep( values: ArrayLike, formatter: Callable, na_rep: str ) -> np.ndarray: mask = isna(values) formatted = np.array( [ formatter(val) if not m else na_rep for val, m in zip(values.ravel(), mask.ravel(), strict=True) ] ).reshape(values.shape) return formatted
def format_complex_with_na_rep( values: ArrayLike, formatter: Callable, na_rep: str ) -> np.ndarray: real_values = np.real(values).ravel() # type: ignore[arg-type] imag_values = np.imag(values).ravel() # type: ignore[arg-type] real_mask, imag_mask = isna(real_values), isna(imag_values) formatted_lst = [] for val, real_val, imag_val, re_isna, im_isna in zip( values.ravel(), real_values, imag_values, real_mask, imag_mask, strict=True, ): if not re_isna and not im_isna: formatted_lst.append(formatter(val)) elif not re_isna: # xxx+nanj formatted_lst.append(f"{formatter(real_val)}+{na_rep}j") elif not im_isna: # nan[+/-]xxxj # The imaginary part may either start with a "-" or a space imag_formatted = formatter(imag_val).strip() if imag_formatted.startswith("-"): formatted_lst.append(f"{na_rep}{imag_formatted}j") else: formatted_lst.append(f"{na_rep}+{imag_formatted}j") else: # nan+nanj formatted_lst.append(f"{na_rep}+{na_rep}j") return np.array(formatted_lst).reshape(values.shape)
if self.formatter is not None: return format_with_na_rep(self.values, self.formatter, self.na_rep)
if self.fixed_width: threshold = get_option("display.chop_threshold") else: threshold = None
# if we have a fixed_width, we'll need to try different float_format def format_values_with(float_format): formatter = self._value_formatter(float_format, threshold)
# default formatter leaves a space to the left when formatting # floats, must be consistent for left-justifying NaNs (GH #25061) na_rep = " " + self.na_rep if self.justify == "left" else self.na_rep
# different formatting strategies for complex and non-complex data # need to distinguish complex and float NaNs (GH #53762) values = self.values is_complex = is_complex_dtype(values)
# separate the wheat from the chaff if is_complex: values = format_complex_with_na_rep(values, formatter, na_rep) else: values = format_with_na_rep(values, formatter, na_rep)
if self.fixed_width: if is_complex: result = _trim_zeros_complex(values, self.decimal) else: result = _trim_zeros_float(values, self.decimal) return np.asarray(result, dtype="object")
return values
# There is a special default string when we are fixed-width # The default is otherwise to use str instead of a formatting string float_format: FloatFormatType | None if self.float_format is None: if self.fixed_width: if self.leading_space is True: fmt_str = "{value: .{digits:d}f}" else: fmt_str = "{value:.{digits:d}f}" float_format = partial(fmt_str.format, digits=self.digits) else: float_format = self.float_format else: float_format = lambda value: self.float_format % value
formatted_values = format_values_with(float_format)
if not self.fixed_width: return formatted_values
# we need do convert to engineering format if some values are too small # and would appear as 0, or if some values are too big and take too # much space
if len(formatted_values) > 0: maxlen = max(len(x) for x in formatted_values) too_long = maxlen > self.digits + 6 else: too_long = False
abs_vals = np.abs(self.values) # this is pretty arbitrary for now # large values: more that 8 characters including decimal symbol # and first digit, hence > 1e6 has_large_values = (abs_vals > 1e6).any() has_small_values = ((abs_vals < 10 ** (-self.digits)) & (abs_vals > 0)).any()
if has_small_values or (too_long and has_large_values): if self.leading_space is True: fmt_str = "{value: .{digits:d}e}" else: fmt_str = "{value:.{digits:d}e}" float_format = partial(fmt_str.format, digits=self.digits) formatted_values = format_values_with(float_format)
return formatted_values
def _format_strings(self) -> list[str]: return list(self.get_result_as_array())
class _IntArrayFormatter(_GenericArrayFormatter): def _format_strings(self) -> list[str]: if self.leading_space is False: formatter_str = lambda x: f"{x:d}".format(x=x) else: formatter_str = lambda x: f"{x: d}".format(x=x) formatter = self.formatter or formatter_str fmt_values = [formatter(x) for x in self.values] return fmt_values
class _Datetime64Formatter(_GenericArrayFormatter): values: DatetimeArray
def __init__( self, values: DatetimeArray, nat_rep: str = "NaT", date_format: None = None, **kwargs, ) -> None: super().__init__(values, **kwargs) self.nat_rep = nat_rep self.date_format = date_format
def _format_strings(self) -> list[str]: """we by definition have DO NOT have a TZ""" values = self.values
if self.formatter is not None: return [self.formatter(x) for x in values]
fmt_values = values._format_native_types( na_rep=self.nat_rep, date_format=self.date_format ) return fmt_values.tolist()
class _ExtensionArrayFormatter(_GenericArrayFormatter): values: ExtensionArray
def _format_strings(self) -> list[str]: values = self.values
formatter = self.formatter fallback_formatter = None if formatter is None: fallback_formatter = values._formatter(boxed=True)
if isinstance(values, Categorical): # Categorical is special for now, so that we can preserve tzinfo array = values._internal_get_values() else: array = np.asarray(values, dtype=object)
fmt_values = format_array( array, formatter, float_format=self.float_format, na_rep=self.na_rep, digits=self.digits, space=self.space, justify=self.justify, decimal=self.decimal, leading_space=self.leading_space, quoting=self.quoting, fallback_formatter=fallback_formatter, ) return fmt_values
def format_percentiles( percentiles: np.ndarray | Sequence[float],) -> list[str]: """ Outputs rounded and formatted percentiles.
Parameters ---------- percentiles : list-like, containing floats from interval [0,1]
Returns ------- formatted : list of strings
Notes ----- Rounding precision is chosen so that: (1) if any two elements of ``percentiles`` differ, they remain different after rounding (2) no entry is *rounded* to 0% or 100%. Any non-integer is always rounded to at least 1 decimal place.
Examples -------- Keeps all entries different after rounding:
>>> format_percentiles([0.01999, 0.02001, 0.5, 0.666666, 0.9999]) ['1.999%', '2.001%', '50%', '66.667%', '99.99%']
No element is rounded to 0% or 100% (unless already equal to it). Duplicates are allowed:
>>> format_percentiles([0, 0.5, 0.02001, 0.5, 0.666666, 0.9999]) ['0%', '50%', '2.0%', '50%', '66.67%', '99.99%'] """ if len(percentiles) == 0: return []
percentiles = np.asarray(percentiles)
# It checks for np.nan as well if ( not is_numeric_dtype(percentiles) or not np.all(percentiles >= 0) or not np.all(percentiles <= 1) ): raise ValueError("percentiles should all be in the interval [0,1]")
percentiles = 100 * percentiles prec = get_precision(percentiles) percentiles_round_type = percentiles.round(prec).astype(int)
int_idx = np.isclose(percentiles_round_type, percentiles)
if np.all(int_idx): out = percentiles_round_type.astype(str) return [i + "%" for i in out]
unique_pcts = np.unique(percentiles) prec = get_precision(unique_pcts) out = np.empty_like(percentiles, dtype=object) out[int_idx] = percentiles[int_idx].round().astype(int).astype(str)
out[~int_idx] = percentiles[~int_idx].round(prec).astype(str) return [i + "%" for i in out]
def get_precision(array: np.ndarray | Sequence[float]) -> int: to_begin = array[0] if array[0] > 0 else None to_end = 100 - array[-1] if array[-1] < 100 else None diff = np.ediff1d(array, to_begin=to_begin, to_end=to_end) diff = abs(diff) prec = -np.floor(np.log10(np.min(diff))).astype(int) prec = max(1, prec) return prec
def _format_datetime64(x: NaTType | Timestamp, nat_rep: str = "NaT") -> str: if x is NaT: return nat_rep
# Timestamp.__str__ falls back to datetime.datetime.__str__ = isoformat(sep=' ') # so it already uses string formatting rather than strftime (faster). return str(x)
def _format_datetime64_dateonly( x: NaTType | Timestamp, nat_rep: str = "NaT", date_format: str | None = None,) -> str: if isinstance(x, NaTType): return nat_rep
if date_format: return x.strftime(date_format) else: # Timestamp._date_repr relies on string formatting (faster than strftime) return x._date_repr
def get_format_datetime64( is_dates_only: bool, nat_rep: str = "NaT", date_format: str | None = None) -> Callable: """Return a formatter callable taking a datetime64 as input and providing a string as output"""
if is_dates_only: return lambda x: _format_datetime64_dateonly( x, nat_rep=nat_rep, date_format=date_format ) else: return lambda x: _format_datetime64(x, nat_rep=nat_rep)
class _Datetime64TZFormatter(_Datetime64Formatter): values: DatetimeArray
def _format_strings(self) -> list[str]: """we by definition have a TZ""" ido = self.values._is_dates_only values = self.values.astype(object) formatter = self.formatter or get_format_datetime64( ido, date_format=self.date_format ) fmt_values = [formatter(x) for x in values]
return fmt_values
class _Timedelta64Formatter(_GenericArrayFormatter): values: TimedeltaArray
def __init__( self, values: TimedeltaArray, nat_rep: str = "NaT", **kwargs, ) -> None: # TODO: nat_rep is never passed, na_rep is. super().__init__(values, **kwargs) self.nat_rep = nat_rep
def _format_strings(self) -> list[str]: formatter = self.formatter or get_format_timedelta64( self.values, nat_rep=self.nat_rep, box=False ) return [formatter(x) for x in self.values]
def get_format_timedelta64( values: TimedeltaArray, nat_rep: str | float = "NaT", box: bool = False,) -> Callable: """ Return a formatter function for a range of timedeltas. These will all have the same format argument
If box, then show the return in quotes """ even_days = values._is_dates_only
if even_days: format = None else: format = "long"
def _formatter(x): if x is None or (is_scalar(x) and isna(x)): return nat_rep
if not isinstance(x, Timedelta): x = Timedelta(x)
# Timedelta._repr_base uses string formatting (faster than strftime) result = x._repr_base(format=format) if box: result = f"'{result}'" return result
return _formatter
def _make_fixed_width( strings: list[str], justify: str = "right", minimum: int | None = None, adj: printing._TextAdjustment | None = None,) -> list[str]: if len(strings) == 0 or justify == "all": return strings
if adj is None: adjustment = printing.get_adjustment() else: adjustment = adj
max_len = max(adjustment.len(x) for x in strings)
if minimum is not None: max_len = max(minimum, max_len)
conf_max = get_option("display.max_colwidth") if conf_max is not None and max_len > conf_max: max_len = conf_max
def just(x: str) -> str: if conf_max is not None: if (conf_max > 3) & (adjustment.len(x) > max_len): x = x[: max_len - 3] + "..." return x
strings = [just(x) for x in strings] result = adjustment.justify(strings, max_len, mode=justify) return result
def _trim_zeros_complex(str_complexes: ArrayLike, decimal: str = ".") -> list[str]: """ Separates the real and imaginary parts from the complex number, and executes the _trim_zeros_float method on each of those. """ real_part, imag_part = [], [] for x in str_complexes: # Complex numbers are represented as "(-)xxx(+/-)xxxj" # The split will give [{"", "-"}, "xxx", "+/-", "xxx", "j", ""] # Therefore, the imaginary part is the 4th and 3rd last elements, # and the real part is everything before the imaginary part trimmed = re.split(r"(?<!e)([j+-])", x) real_part.append("".join(trimmed[:-4])) imag_part.append("".join(trimmed[-4:-2]))
# We want to align the lengths of the real and imaginary parts of each complex # number, as well as the lengths the real (resp. complex) parts of all numbers # in the array n = len(str_complexes) padded_parts = _trim_zeros_float(real_part + imag_part, decimal) if len(padded_parts) == 0: return [] padded_length = max(len(part) for part in padded_parts) - 1 padded = [ real_pt # real part, possibly NaN + imag_pt[0] # +/- + f"{imag_pt[1:]:>{padded_length}}" # complex part (no sign), possibly nan + "j" for real_pt, imag_pt in zip(padded_parts[:n], padded_parts[n:], strict=True) ] return padded
def _trim_zeros_single_float(str_float: str) -> str: """ Trims trailing zeros after a decimal point, leaving just one if necessary. """ str_float = str_float.rstrip("0") if str_float.endswith("."): str_float += "0"
return str_float
def _trim_zeros_float( str_floats: ArrayLike | list[str], decimal: str = ".") -> list[str]: """ Trims the maximum number of trailing zeros equally from all numbers containing decimals, leaving just one if necessary. """ trimmed = str_floats number_regex = re.compile(rf"^\s*[\+-]?[0-9]+\{decimal}[0-9]*$")
def is_number_with_decimal(x) -> bool: return re.match(number_regex, x) is not None
def should_trim(values: ArrayLike | list[str]) -> bool: """ Determine if an array of strings should be trimmed.
Returns True if all numbers containing decimals (defined by the above regular expression) within the array end in a zero, otherwise returns False. """ numbers = [x for x in values if is_number_with_decimal(x)] return len(numbers) > 0 and all(x.endswith("0") for x in numbers)
while should_trim(trimmed): trimmed = [x[:-1] if is_number_with_decimal(x) else x for x in trimmed]
# leave one 0 after the decimal points if need be. result = [ x + "0" if is_number_with_decimal(x) and x.endswith(decimal) else x for x in trimmed ] return result
def _has_names(index: Index) -> bool: if isinstance(index, MultiIndex): return com.any_not_none(*index.names) else: return index.name is not None
class EngFormatter: """ Formats float values according to engineering format.
Based on matplotlib.ticker.EngFormatter """
# The SI engineering prefixes ENG_PREFIXES = { -24: "y", -21: "z", -18: "a", -15: "f", -12: "p", -9: "n", -6: "u", -3: "m", 0: "", 3: "k", 6: "M", 9: "G", 12: "T", 15: "P", 18: "E", 21: "Z", 24: "Y", }
def __init__( self, accuracy: int | None = None, use_eng_prefix: bool = False ) -> None: self.accuracy = accuracy self.use_eng_prefix = use_eng_prefix
def __call__(self, num: float) -> str: """ Formats a number in engineering notation, appending a letter representing the power of 1000 of the original number. Some examples: >>> format_eng = EngFormatter(accuracy=0, use_eng_prefix=True) >>> format_eng(0) ' 0' >>> format_eng = EngFormatter(accuracy=1, use_eng_prefix=True) >>> format_eng(1_000_000) ' 1.0M' >>> format_eng = EngFormatter(accuracy=2, use_eng_prefix=False) >>> format_eng("-1e-6") '-1.00E-06'
@param num: the value to represent @type num: either a numeric value or a string that can be converted to a numeric value (as per decimal.Decimal constructor)
@return: engineering formatted string """ dnum = Decimal(str(num))
if Decimal.is_nan(dnum): return "NaN"
if Decimal.is_infinite(dnum): return "inf"
sign = 1
if dnum < 0: # pragma: no cover sign = -1 dnum = -dnum
if dnum != 0: pow10 = Decimal(int(math.floor(dnum.log10() / 3) * 3)) else: pow10 = Decimal(0)
pow10 = pow10.min(max(self.ENG_PREFIXES.keys())) pow10 = pow10.max(min(self.ENG_PREFIXES.keys())) int_pow10 = int(pow10)
if self.use_eng_prefix: prefix = self.ENG_PREFIXES[int_pow10] elif int_pow10 < 0: prefix = f"E-{-int_pow10:02d}" else: prefix = f"E+{int_pow10:02d}"
mant = sign * dnum / (10**pow10)
if self.accuracy is None: # pragma: no cover format_str = "{mant: g}{prefix}" else: format_str = f"{{mant: .{self.accuracy:d}f}}{{prefix}}"
formatted = format_str.format(mant=mant, prefix=prefix)
return formatted
@set_module("pandas")def set_eng_float_format(accuracy: int = 3, use_eng_prefix: bool = False) -> None: """ Format float representation in DataFrame with SI notation.
Sets the floating-point display format for ``DataFrame`` objects using engineering notation (SI units), allowing easier readability of values across wide ranges.
Parameters ---------- accuracy : int, default 3 Number of decimal digits after the floating point. use_eng_prefix : bool, default False Whether to represent a value with SI prefixes.
Returns ------- None This method does not return a value. it updates the global display format for floats in DataFrames.
See Also -------- set_option : Set the value of the specified option or options. reset_option : Reset one or more options to their default value.
Examples -------- >>> df = pd.DataFrame([1e-9, 1e-3, 1, 1e3, 1e6]) >>> df 0 0 1.000000e-09 1 1.000000e-03 2 1.000000e+00 3 1.000000e+03 4 1.000000e+06
>>> pd.set_eng_float_format(accuracy=1) >>> df 0 0 1.0E-09 1 1.0E-03 2 1.0E+00 3 1.0E+03 4 1.0E+06
>>> pd.set_eng_float_format(use_eng_prefix=True) >>> df 0 0 1.000n 1 1.000m 2 1.000 3 1.000k 4 1.000M
>>> pd.set_eng_float_format(accuracy=1, use_eng_prefix=True) >>> df 0 0 1.0n 1 1.0m 2 1.0 3 1.0k 4 1.0M
>>> pd.set_option("display.float_format", None) # unset option """ set_option("display.float_format", EngFormatter(accuracy, use_eng_prefix))
def get_level_lengths( levels: Any, sentinel: bool | object | str = "") -> list[dict[int, int]]: """ For each index in each level the function returns lengths of indexes.
Parameters ---------- levels : list of lists List of values on for level. sentinel : string, optional Value which states that no new index starts on there.
Returns ------- Returns list of maps. For each level returns map of indexes (key is index in row and value is length of index). """ if len(levels) == 0: return []
control = [True] * len(levels[0])
result = [] for level in levels: last_index = 0
lengths = {} for i, key in enumerate(level): if control[i] and key == sentinel: pass else: control[i] = False lengths[last_index] = i - last_index last_index = i
lengths[last_index] = len(level) - last_index
result.append(lengths)
return result
def buffer_put_lines(buf: WriteBuffer[str], lines: list[str]) -> None: """ Appends lines to a buffer.
Parameters ---------- buf The buffer to write to lines The lines to append. """ if any(isinstance(x, str) for x in lines): lines = [str(x) for x in lines] buf.write("\n".join(lines))123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657"""Module for formatting output data in HTML."""
from __future__ import annotations
from textwrap import dedentfrom typing import ( TYPE_CHECKING, Any, Final, cast,)
from pandas._config import get_option
from pandas._libs import lib
from pandas import ( MultiIndex, option_context,)
from pandas.io.common import is_urlfrom pandas.io.formats.format import ( DataFrameFormatter, get_level_lengths,)from pandas.io.formats.printing import pprint_thing
if TYPE_CHECKING: from collections.abc import ( Hashable, Iterable, Mapping, )
class HTMLFormatter: """ Internal class for formatting output data in html. This class is intended for shared functionality between DataFrame.to_html() and DataFrame._repr_html_(). Any logic in common with other output formatting methods should ideally be inherited from classes in format.py and this class responsible for only producing html markup. """
indent_delta: Final = 2
def __init__( self, formatter: DataFrameFormatter, classes: str | list[str] | tuple[str, ...] | None = None, border: int | bool | None = None, table_id: str | None = None, render_links: bool = False, ) -> None: self.fmt = formatter self.classes = classes
self.frame = self.fmt.frame self.columns = self.fmt.tr_frame.columns self.elements: list[str] = [] self.bold_rows = self.fmt.bold_rows self.escape = self.fmt.escape self.show_dimensions = self.fmt.show_dimensions if border is None or border is True: border = cast(int, get_option("display.html.border")) elif not border: border = None
self.border = border self.table_id = table_id self.render_links = render_links
self.col_space = {} is_multi_index = isinstance(self.columns, MultiIndex) for column, value in self.fmt.col_space.items(): col_space_value = f"{value}px" if isinstance(value, int) else value self.col_space[column] = col_space_value # GH 53885: Handling case where column is index # Flatten the data in the multi index and add in the map if is_multi_index and isinstance(column, tuple): for column_index in column: self.col_space[str(column_index)] = col_space_value
def to_string(self) -> str: lines = self.render() if any(isinstance(x, str) for x in lines): lines = [str(x) for x in lines] return "\n".join(lines)
def render(self) -> list[str]: self._write_table()
if self.should_show_dimensions: by = chr(215) # × # noqa: RUF003 self.write( f"<p>{len(self.frame)} rows {by} {len(self.frame.columns)} columns</p>" )
return self.elements
@property def should_show_dimensions(self) -> bool: return self.fmt.should_show_dimensions
@property def show_row_idx_names(self) -> bool: return self.fmt.show_row_idx_names
@property def show_col_idx_names(self) -> bool: return self.fmt.show_col_idx_names
@property def row_levels(self) -> int: if self.fmt.index: # showing (row) index return self.frame.index.nlevels elif self.show_col_idx_names: # see gh-22579 # Column misalignment also occurs for # a standard index when the columns index is named. # If the row index is not displayed a column of # blank cells need to be included before the DataFrame values. return 1 # not showing (row) index return 0
def _get_columns_formatted_values(self) -> Iterable: return self.columns
@property def is_truncated(self) -> bool: return self.fmt.is_truncated
@property def ncols(self) -> int: return len(self.fmt.tr_frame.columns)
def write(self, s: Any, indent: int = 0) -> None: rs = pprint_thing(s) self.elements.append(" " * indent + rs)
def write_th( self, s: Any, header: bool = False, indent: int = 0, tags: str | None = None ) -> None: """ Method for writing a formatted <th> cell.
If col_space is set on the formatter then that is used for the value of min-width.
Parameters ---------- s : object The data to be written inside the cell. header : bool, default False Set to True if the <th> is for use inside <thead>. This will cause min-width to be set if there is one. indent : int, default 0 The indentation level of the cell. tags : str, default None Tags to include in the cell.
Returns ------- A written <th> cell. """ col_space = self.col_space.get(s, None)
if header and col_space is not None: tags = tags or "" tags += f'style="min-width: {col_space};"'
self._write_cell(s, kind="th", indent=indent, tags=tags)
def write_td(self, s: Any, indent: int = 0, tags: str | None = None) -> None: self._write_cell(s, kind="td", indent=indent, tags=tags)
def _write_cell( self, s: Any, kind: str = "td", indent: int = 0, tags: str | None = None ) -> None: if tags is not None: start_tag = f"<{kind} {tags}>" else: start_tag = f"<{kind}>"
if self.escape: # escape & first to prevent double escaping of & esc = {"&": r"&", "<": r"<", ">": r">"} else: esc = {}
rs = pprint_thing(s, escape_chars=esc).strip() # replace spaces betweens strings with non-breaking spaces rs = rs.replace(" ", " ")
if self.render_links and is_url(rs): rs_unescaped = pprint_thing(s, escape_chars={}).strip() start_tag += f'<a href="{rs_unescaped}" target="_blank">' end_a = "</a>" else: end_a = ""
self.write(f"{start_tag}{rs}{end_a}</{kind}>", indent)
def write_tr( self, line: Iterable, indent: int = 0, indent_delta: int = 0, header: bool = False, align: str | None = None, tags: dict[int, str] | None = None, nindex_levels: int = 0, ) -> None: if tags is None: tags = {}
if align is None: self.write("<tr>", indent) else: self.write(f'<tr style="text-align: {align};">', indent) indent += indent_delta
for i, s in enumerate(line): val_tag = tags.get(i, None) if header or (self.bold_rows and i < nindex_levels): self.write_th(s, indent=indent, header=header, tags=val_tag) else: self.write_td(s, indent, tags=val_tag)
indent -= indent_delta self.write("</tr>", indent)
def _write_table(self, indent: int = 0) -> None: _classes = ["dataframe"] # Default class. use_mathjax = get_option("display.html.use_mathjax") if not use_mathjax: _classes.append("tex2jax_ignore") _classes.append("mathjax_ignore") if self.classes is not None: if isinstance(self.classes, str): self.classes = self.classes.split() if not isinstance(self.classes, (list, tuple)): raise TypeError( "classes must be a string, list, " f"or tuple, not {type(self.classes)}" ) _classes.extend(self.classes)
if self.table_id is None: id_section = "" else: id_section = f' id="{self.table_id}"'
if self.border is None: border_attr = "" else: border_attr = f' border="{self.border}"'
self.write( f'<table{border_attr} class="{" ".join(_classes)}"{id_section}>', indent, )
if self.fmt.header or self.show_row_idx_names: self._write_header(indent + self.indent_delta)
self._write_body(indent + self.indent_delta)
self.write("</table>", indent)
def _write_col_header(self, indent: int) -> None: row: list[Hashable] is_truncated_horizontally = self.fmt.is_truncated_horizontally if isinstance(self.columns, MultiIndex): template = 'colspan="{span:d}" halign="left"'
sentinel: lib.NoDefault | bool if self.fmt.sparsify: # GH3547 sentinel = lib.no_default else: sentinel = False levels = self.columns._format_multi(sparsify=sentinel, include_names=False) level_lengths = get_level_lengths(levels, sentinel) inner_lvl = len(level_lengths) - 1 for lnum, (records, values) in enumerate( zip(level_lengths, levels, strict=True) ): if is_truncated_horizontally: # modify the header lines ins_col = self.fmt.tr_col_num if self.fmt.sparsify: recs_new = {} # Increment tags after ... col. for tag, span in list(records.items()): if tag >= ins_col: recs_new[tag + 1] = span elif tag + span > ins_col: recs_new[tag] = span + 1 if lnum == inner_lvl: values = ( *values[:ins_col], "...", *values[ins_col:], ) else: # sparse col headers do not receive a ... values = ( *values[:ins_col], values[ins_col - 1], *values[ins_col:], ) else: recs_new[tag] = span # if ins_col lies between tags, all col headers # get ... if tag + span == ins_col: recs_new[ins_col] = 1 values = (*values[:ins_col], "...", *values[ins_col:]) records = recs_new inner_lvl = len(level_lengths) - 1 if lnum == inner_lvl: records[ins_col] = 1 else: recs_new = {} for tag, span in list(records.items()): if tag >= ins_col: recs_new[tag + 1] = span else: recs_new[tag] = span recs_new[ins_col] = 1 records = recs_new values = [*values[:ins_col], "...", *values[ins_col:]]
# see gh-22579 # Column Offset Bug with to_html(index=False) with # MultiIndex Columns and Index. # Initially fill row with blank cells before column names. # TODO: Refactor to remove code duplication with code # block below for standard columns index. row = [""] * (self.row_levels - 1) if self.fmt.index or self.show_col_idx_names: # see gh-22747 # If to_html(index_names=False) do not show columns # index names. # TODO: Refactor to use _get_column_name_list from # DataFrameFormatter class and create a # _get_formatted_column_labels function for code # parity with DataFrameFormatter class. if self.fmt.show_index_names: name = self.columns.names[lnum] row.append(pprint_thing(name or "")) else: row.append("")
tags = {} j = len(row) for i, v in enumerate(values): if i in records: if records[i] > 1: tags[j] = template.format(span=records[i]) else: continue j += 1 row.append(v) self.write_tr(row, indent, self.indent_delta, tags=tags, header=True) else: # see gh-22579 # Column misalignment also occurs for # a standard index when the columns index is named. # Initially fill row with blank cells before column names. # TODO: Refactor to remove code duplication with code block # above for columns MultiIndex. row = [""] * (self.row_levels - 1) if self.fmt.index or self.show_col_idx_names: # see gh-22747 # If to_html(index_names=False) do not show columns # index names. # TODO: Refactor to use _get_column_name_list from # DataFrameFormatter class. if self.fmt.show_index_names: row.append(self.columns.name or "") else: row.append("") row.extend(self._get_columns_formatted_values()) align = self.fmt.justify
if is_truncated_horizontally: ins_col = self.row_levels + self.fmt.tr_col_num row.insert(ins_col, "...")
self.write_tr(row, indent, self.indent_delta, header=True, align=align)
def _write_row_header(self, indent: int) -> None: is_truncated_horizontally = self.fmt.is_truncated_horizontally row = [x if x is not None else "" for x in self.frame.index.names] + [""] * ( self.ncols + (1 if is_truncated_horizontally else 0) ) self.write_tr(row, indent, self.indent_delta, header=True)
def _write_header(self, indent: int) -> None: self.write("<thead>", indent)
if self.fmt.header: self._write_col_header(indent + self.indent_delta)
if self.show_row_idx_names: self._write_row_header(indent + self.indent_delta)
self.write("</thead>", indent)
def _get_formatted_values(self) -> dict[int, list[str]]: with option_context("display.max_colwidth", None): fmt_values = {i: self.fmt.format_col(i) for i in range(self.ncols)} return fmt_values
def _write_body(self, indent: int) -> None: self.write("<tbody>", indent) fmt_values = self._get_formatted_values()
# write values if self.fmt.index and isinstance(self.frame.index, MultiIndex): self._write_hierarchical_rows(fmt_values, indent + self.indent_delta) else: self._write_regular_rows(fmt_values, indent + self.indent_delta)
self.write("</tbody>", indent)
def _write_regular_rows( self, fmt_values: Mapping[int, list[str]], indent: int ) -> None: is_truncated_horizontally = self.fmt.is_truncated_horizontally is_truncated_vertically = self.fmt.is_truncated_vertically
nrows = len(self.fmt.tr_frame)
if self.fmt.index: fmt = self.fmt._get_formatter("__index__") if fmt is not None: index_values = self.fmt.tr_frame.index.map(fmt) else: # only reached with non-Multi index index_values = self.fmt.tr_frame.index._format_flat(include_name=False)
row: list[str] = [] for i in range(nrows): if is_truncated_vertically and i == (self.fmt.tr_row_num): str_sep_row = ["..."] * len(row) self.write_tr( str_sep_row, indent, self.indent_delta, tags=None, nindex_levels=self.row_levels, )
row = [] if self.fmt.index: row.append(index_values[i]) # see gh-22579 # Column misalignment also occurs for # a standard index when the columns index is named. # Add blank cell before data cells. elif self.show_col_idx_names: row.append("") row.extend(fmt_values[j][i] for j in range(self.ncols))
if is_truncated_horizontally: dot_col_ix = self.fmt.tr_col_num + self.row_levels row.insert(dot_col_ix, "...") self.write_tr( row, indent, self.indent_delta, tags=None, nindex_levels=self.row_levels )
def _write_hierarchical_rows( self, fmt_values: Mapping[int, list[str]], indent: int ) -> None: template = 'rowspan="{span}" valign="top"'
is_truncated_horizontally = self.fmt.is_truncated_horizontally is_truncated_vertically = self.fmt.is_truncated_vertically frame = self.fmt.tr_frame nrows = len(frame)
assert isinstance(frame.index, MultiIndex) idx_values = frame.index._format_multi(sparsify=False, include_names=False) idx_values = list(zip(*idx_values, strict=True))
if self.fmt.sparsify: # GH3547 sentinel = lib.no_default levels = frame.index._format_multi(sparsify=sentinel, include_names=False)
level_lengths = get_level_lengths(levels, sentinel) inner_lvl = len(level_lengths) - 1 if is_truncated_vertically: # Insert ... row and adjust idx_values and # level_lengths to take this into account. ins_row = self.fmt.tr_row_num inserted = False for lnum, records in enumerate(level_lengths): rec_new = {} for tag, span in list(records.items()): if tag >= ins_row: rec_new[tag + 1] = span elif tag + span > ins_row: rec_new[tag] = span + 1
# GH 14882 - Make sure insertion done once if not inserted: dot_row = list(idx_values[ins_row - 1]) dot_row[-1] = "..." idx_values.insert(ins_row, tuple(dot_row)) inserted = True else: dot_row = list(idx_values[ins_row]) dot_row[inner_lvl - lnum] = "..." idx_values[ins_row] = tuple(dot_row) else: rec_new[tag] = span # If ins_row lies between tags, all cols idx cols # receive ... if tag + span == ins_row: rec_new[ins_row] = 1 if lnum == 0: idx_values.insert( ins_row, tuple(["..."] * len(level_lengths)) )
# GH 14882 - Place ... in correct level elif inserted: dot_row = list(idx_values[ins_row]) dot_row[inner_lvl - lnum] = "..." idx_values[ins_row] = tuple(dot_row) level_lengths[lnum] = rec_new
level_lengths[inner_lvl][ins_row] = 1 for ix_col in fmt_values: fmt_values[ix_col].insert(ins_row, "...") nrows += 1
for i in range(nrows): row = [] tags = {}
sparse_offset = 0 j = 0 for records, v in zip(level_lengths, idx_values[i], strict=True): if i in records: if records[i] > 1: tags[j] = template.format(span=records[i]) else: sparse_offset += 1 continue
j += 1 row.append(v)
row.extend(fmt_values[j][i] for j in range(self.ncols)) if is_truncated_horizontally: row.insert( self.row_levels - sparse_offset + self.fmt.tr_col_num, "..." ) self.write_tr( row, indent, self.indent_delta, tags=tags, nindex_levels=len(levels) - sparse_offset, ) else: row = [] for i in range(len(frame)): if is_truncated_vertically and i == (self.fmt.tr_row_num): str_sep_row = ["..."] * len(row) self.write_tr( str_sep_row, indent, self.indent_delta, tags=None, nindex_levels=self.row_levels, )
idx_values = list( zip( *frame.index._format_multi(sparsify=False, include_names=False), strict=True, ) ) row = [] row.extend(idx_values[i]) row.extend(fmt_values[j][i] for j in range(self.ncols)) if is_truncated_horizontally: row.insert(self.row_levels + self.fmt.tr_col_num, "...") self.write_tr( row, indent, self.indent_delta, tags=None, nindex_levels=frame.index.nlevels, )
class NotebookFormatter(HTMLFormatter): """ Internal class for formatting output data in html for display in Jupyter Notebooks. This class is intended for functionality specific to DataFrame._repr_html_() and DataFrame.to_html(notebook=True) """
def _get_formatted_values(self) -> dict[int, list[str]]: return {i: self.fmt.format_col(i) for i in range(self.ncols)}
def _get_columns_formatted_values(self) -> list[str]: # only reached with non-Multi Index return self.columns._format_flat(include_name=False)
def write_style(self) -> None: # We use the "scoped" attribute here so that the desired # style properties for the data frame are not then applied # throughout the entire notebook. template_first = """\ <style scoped>""" template_last = """\ </style>""" template_select = """\ .dataframe %s { %s: %s; }""" element_props = [ ("tbody tr th:only-of-type", "vertical-align", "middle"), ("tbody tr th", "vertical-align", "top"), ] if isinstance(self.columns, MultiIndex): element_props.append(("thead tr th", "text-align", "left")) if self.show_row_idx_names: element_props.append( ("thead tr:last-of-type th", "text-align", "right") ) else: element_props.append(("thead th", "text-align", "right")) template_mid = "\n\n".join(template_select % t for t in element_props) template = dedent(f"{template_first}\n{template_mid}\n{template_last}") self.write(template)
def render(self) -> list[str]: self.write("<div>") self.write_style() super().render() self.write("</div>") return self.elements123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943from __future__ import annotations
from abc import ( ABC, abstractmethod,)import sysfrom textwrap import dedentfrom typing import TYPE_CHECKING
from pandas._config import get_option
from pandas.io.formats import format as fmtfrom pandas.io.formats.printing import pprint_thing
if TYPE_CHECKING: from collections.abc import ( Iterable, Iterator, Mapping, Sequence, )
from pandas._typing import ( Dtype, WriteBuffer, )
from pandas import ( DataFrame, Index, Series, )
show_counts_sub = dedent( """\ show_counts : bool, optional Whether to show the non-null counts. By default, this is shown only if the DataFrame is smaller than ``pandas.options.display.max_info_rows`` and ``pandas.options.display.max_info_columns``. A value of True always shows the counts, and False never shows the counts.""")
series_examples_sub = dedent( """\ >>> int_values = [1, 2, 3, 4, 5] >>> text_values = ['alpha', 'beta', 'gamma', 'delta', 'epsilon'] >>> s = pd.Series(text_values, index=int_values) >>> s.info() <class 'pandas.Series'> Index: 5 entries, 1 to 5 Series name: None Non-Null Count Dtype -------------- ----- 5 non-null object dtypes: object(1) memory usage: 80.0+ bytes
Prints a summary excluding information about its values:
>>> s.info(verbose=False) <class 'pandas.Series'> Index: 5 entries, 1 to 5 dtypes: object(1) memory usage: 80.0+ bytes
Pipe output of Series.info to buffer instead of sys.stdout, get buffer content and writes to a text file:
>>> import io >>> buffer = io.StringIO() >>> s.info(buf=buffer) >>> s = buffer.getvalue() >>> with open("df_info.txt", "w", ... encoding="utf-8") as f: # doctest: +SKIP ... f.write(s) 260
The `memory_usage` parameter allows deep introspection mode, specially useful for big Series and fine-tune memory optimization:
>>> random_strings_array = np.random.choice(['a', 'b', 'c'], 10 ** 6) >>> s = pd.Series(np.random.choice(['a', 'b', 'c'], 10 ** 6)) >>> s.info() <class 'pandas.Series'> RangeIndex: 1000000 entries, 0 to 999999 Series name: None Non-Null Count Dtype -------------- ----- 1000000 non-null object dtypes: object(1) memory usage: 7.6+ MB
>>> s.info(memory_usage='deep') <class 'pandas.Series'> RangeIndex: 1000000 entries, 0 to 999999 Series name: None Non-Null Count Dtype -------------- ----- 1000000 non-null object dtypes: object(1) memory usage: 55.3 MB""")
series_see_also_sub = dedent( """\ Series.describe: Generate descriptive statistics of Series. Series.memory_usage: Memory usage of Series.""")series_max_cols_sub = dedent( """\ max_cols : int, optional Unused, exists only for compatibility with DataFrame.info.""")
series_sub_kwargs = { "klass": "Series", "type_sub": "", "max_cols_sub": series_max_cols_sub, "show_counts_sub": show_counts_sub, "examples_sub": series_examples_sub, "see_also_sub": series_see_also_sub, "version_added_sub": "\n.. versionadded:: 1.4.0\n",}
def _put_str(s: str | Dtype, space: int) -> str: """ Make string of specified length, padding to the right if necessary.
Parameters ---------- s : Union[str, Dtype] String to be formatted. space : int Length to force string to be of.
Returns ------- str String coerced to given length.
Examples -------- >>> pd.io.formats.info._put_str("panda", 6) 'panda ' >>> pd.io.formats.info._put_str("panda", 4) 'pand' """ return str(s)[:space].ljust(space)
def _sizeof_fmt(num: float, size_qualifier: str) -> str: """ Return size in human readable format.
Parameters ---------- num : int Size in bytes. size_qualifier : str Either empty, or '+' (if lower bound).
Returns ------- str Size in human readable format.
Examples -------- >>> _sizeof_fmt(23028, "") '22.5 KB'
>>> _sizeof_fmt(23028, "+") '22.5+ KB' """ for x in ["bytes", "KB", "MB", "GB", "TB"]: if num < 1024.0: return f"{num:3.1f}{size_qualifier} {x}" num /= 1024.0 return f"{num:3.1f}{size_qualifier} PB"
def _initialize_memory_usage( memory_usage: bool | str | None = None,) -> bool | str: """Get memory usage based on inputs and display options.""" if memory_usage is None: memory_usage = get_option("display.memory_usage") return memory_usage
class _BaseInfo(ABC): """ Base class for DataFrameInfo and SeriesInfo.
Parameters ---------- data : DataFrame or Series Either dataframe or series. memory_usage : bool or str, optional If "deep", introspect the data deeply by interrogating object dtypes for system-level memory consumption, and include it in the returned values. """
data: DataFrame | Series memory_usage: bool | str
@property @abstractmethod def dtypes(self) -> Iterable[Dtype]: """ Dtypes.
Returns ------- dtypes : sequence Dtype of each of the DataFrame's columns (or one series column). """
@property @abstractmethod def dtype_counts(self) -> Mapping[str, int]: """Mapping dtype - number of counts."""
@property @abstractmethod def non_null_counts(self) -> list[int] | Series: """Sequence of non-null counts for all columns or column (if series)."""
@property @abstractmethod def memory_usage_bytes(self) -> int: """ Memory usage in bytes.
Returns ------- memory_usage_bytes : int Object's total memory usage in bytes. """
@property def memory_usage_string(self) -> str: """Memory usage in a form of human readable string.""" return f"{_sizeof_fmt(self.memory_usage_bytes, self.size_qualifier)}\n"
@property def size_qualifier(self) -> str: size_qualifier = "" if self.memory_usage: if self.memory_usage != "deep": # size_qualifier is just a best effort; not guaranteed to catch # all cases (e.g., it misses categorical data even with object # categories) if ( "object" in self.dtype_counts or self.data.index._is_memory_usage_qualified ): size_qualifier = "+" return size_qualifier
@abstractmethod def render( self, *, buf: WriteBuffer[str] | None, max_cols: int | None, verbose: bool | None, show_counts: bool | None, ) -> None: pass
class DataFrameInfo(_BaseInfo): """ Class storing dataframe-specific info. """
def __init__( self, data: DataFrame, memory_usage: bool | str | None = None, ) -> None: self.data: DataFrame = data self.memory_usage = _initialize_memory_usage(memory_usage)
@property def dtype_counts(self) -> Mapping[str, int]: return _get_dataframe_dtype_counts(self.data)
@property def dtypes(self) -> Iterable[Dtype]: """ Dtypes.
Returns ------- dtypes Dtype of each of the DataFrame's columns. """ return self.data.dtypes
@property def ids(self) -> Index: """ Column names.
Returns ------- ids : Index DataFrame's column names. """ return self.data.columns
@property def col_count(self) -> int: """Number of columns to be summarized.""" return len(self.ids)
@property def non_null_counts(self) -> Series: """Sequence of non-null counts for all columns or column (if series).""" return self.data.count()
@property def memory_usage_bytes(self) -> int: deep = self.memory_usage == "deep" return self.data.memory_usage(index=True, deep=deep).sum()
def render( self, *, buf: WriteBuffer[str] | None, max_cols: int | None, verbose: bool | None, show_counts: bool | None, ) -> None: printer = _DataFrameInfoPrinter( info=self, max_cols=max_cols, verbose=verbose, show_counts=show_counts, ) printer.to_buffer(buf)
class SeriesInfo(_BaseInfo): """ Class storing series-specific info. """
def __init__( self, data: Series, memory_usage: bool | str | None = None, ) -> None: self.data: Series = data self.memory_usage = _initialize_memory_usage(memory_usage)
def render( self, *, buf: WriteBuffer[str] | None = None, max_cols: int | None = None, verbose: bool | None = None, show_counts: bool | None = None, ) -> None: if max_cols is not None: raise ValueError( "Argument `max_cols` can only be passed " "in DataFrame.info, not Series.info" ) printer = _SeriesInfoPrinter( info=self, verbose=verbose, show_counts=show_counts, ) printer.to_buffer(buf)
@property def non_null_counts(self) -> list[int]: return [self.data.count()]
@property def dtypes(self) -> Iterable[Dtype]: return [self.data.dtypes]
@property def dtype_counts(self) -> Mapping[str, int]: from pandas.core.frame import DataFrame
return _get_dataframe_dtype_counts(DataFrame(self.data))
@property def memory_usage_bytes(self) -> int: """Memory usage in bytes.
Returns ------- memory_usage_bytes : int Object's total memory usage in bytes. """ deep = self.memory_usage == "deep" return self.data.memory_usage(index=True, deep=deep)
class _InfoPrinterAbstract: """ Class for printing dataframe or series info. """
def to_buffer(self, buf: WriteBuffer[str] | None = None) -> None: """Save dataframe info into buffer.""" table_builder = self._create_table_builder() lines = table_builder.get_lines() if buf is None: # pragma: no cover buf = sys.stdout fmt.buffer_put_lines(buf, lines)
@abstractmethod def _create_table_builder(self) -> _TableBuilderAbstract: """Create instance of table builder."""
class _DataFrameInfoPrinter(_InfoPrinterAbstract): """ Class for printing dataframe info.
Parameters ---------- info : DataFrameInfo Instance of DataFrameInfo. max_cols : int, optional When to switch from the verbose to the truncated output. verbose : bool, optional Whether to print the full summary. show_counts : bool, optional Whether to show the non-null counts. """
def __init__( self, info: DataFrameInfo, max_cols: int | None = None, verbose: bool | None = None, show_counts: bool | None = None, ) -> None: self.info = info self.data = info.data self.verbose = verbose self.max_cols = self._initialize_max_cols(max_cols) self.show_counts = self._initialize_show_counts(show_counts)
@property def max_rows(self) -> int: """Maximum info rows to be displayed.""" return get_option("display.max_info_rows")
@property def exceeds_info_cols(self) -> bool: """Check if number of columns to be summarized does not exceed maximum.""" return bool(self.col_count > self.max_cols)
@property def exceeds_info_rows(self) -> bool: """Check if number of rows to be summarized does not exceed maximum.""" return bool(len(self.data) > self.max_rows)
@property def col_count(self) -> int: """Number of columns to be summarized.""" return self.info.col_count
def _initialize_max_cols(self, max_cols: int | None) -> int: if max_cols is None: return get_option("display.max_info_columns") return max_cols
def _initialize_show_counts(self, show_counts: bool | None) -> bool: if show_counts is None: return bool(not self.exceeds_info_cols and not self.exceeds_info_rows) else: return show_counts
def _create_table_builder(self) -> _DataFrameTableBuilder: """ Create instance of table builder based on verbosity and display settings. """ if self.verbose: return _DataFrameTableBuilderVerbose( info=self.info, with_counts=self.show_counts, ) elif self.verbose is False: # specifically set to False, not necessarily None return _DataFrameTableBuilderNonVerbose(info=self.info) elif self.exceeds_info_cols: return _DataFrameTableBuilderNonVerbose(info=self.info) else: return _DataFrameTableBuilderVerbose( info=self.info, with_counts=self.show_counts, )
class _SeriesInfoPrinter(_InfoPrinterAbstract): """Class for printing series info.
Parameters ---------- info : SeriesInfo Instance of SeriesInfo. verbose : bool, optional Whether to print the full summary. show_counts : bool, optional Whether to show the non-null counts. """
def __init__( self, info: SeriesInfo, verbose: bool | None = None, show_counts: bool | None = None, ) -> None: self.info = info self.data = info.data self.verbose = verbose self.show_counts = self._initialize_show_counts(show_counts)
def _create_table_builder(self) -> _SeriesTableBuilder: """ Create instance of table builder based on verbosity. """ if self.verbose or self.verbose is None: return _SeriesTableBuilderVerbose( info=self.info, with_counts=self.show_counts, ) else: return _SeriesTableBuilderNonVerbose(info=self.info)
def _initialize_show_counts(self, show_counts: bool | None) -> bool: if show_counts is None: return True else: return show_counts
class _TableBuilderAbstract(ABC): """ Abstract builder for info table. """
_lines: list[str] info: _BaseInfo
@abstractmethod def get_lines(self) -> list[str]: """Product in a form of list of lines (strings)."""
@property def data(self) -> DataFrame | Series: return self.info.data
@property def dtypes(self) -> Iterable[Dtype]: """Dtypes of each of the DataFrame's columns.""" return self.info.dtypes
@property def dtype_counts(self) -> Mapping[str, int]: """Mapping dtype - number of counts.""" return self.info.dtype_counts
@property def display_memory_usage(self) -> bool: """Whether to display memory usage.""" return bool(self.info.memory_usage)
@property def memory_usage_string(self) -> str: """Memory usage string with proper size qualifier.""" return self.info.memory_usage_string
@property def non_null_counts(self) -> list[int] | Series: return self.info.non_null_counts
def add_object_type_line(self) -> None: """Add line with string representation of dataframe to the table.""" self._lines.append(str(type(self.data)))
def add_index_range_line(self) -> None: """Add line with range of indices to the table.""" self._lines.append(self.data.index._summary())
def add_dtypes_line(self) -> None: """Add summary line with dtypes present in dataframe.""" collected_dtypes = [ f"{key}({val:d})" for key, val in sorted(self.dtype_counts.items()) ] self._lines.append(f"dtypes: {', '.join(collected_dtypes)}")
class _DataFrameTableBuilder(_TableBuilderAbstract): """ Abstract builder for dataframe info table.
Parameters ---------- info : DataFrameInfo. Instance of DataFrameInfo. """
def __init__(self, *, info: DataFrameInfo) -> None: self.info: DataFrameInfo = info
def get_lines(self) -> list[str]: self._lines = [] if self.col_count == 0: self._fill_empty_info() else: self._fill_non_empty_info() return self._lines
def _fill_empty_info(self) -> None: """Add lines to the info table, pertaining to empty dataframe.""" self.add_object_type_line() self.add_index_range_line() self._lines.append(f"Empty {type(self.data).__name__}\n")
@abstractmethod def _fill_non_empty_info(self) -> None: """Add lines to the info table, pertaining to non-empty dataframe."""
@property def data(self) -> DataFrame: """DataFrame.""" return self.info.data
@property def ids(self) -> Index: """Dataframe columns.""" return self.info.ids
@property def col_count(self) -> int: """Number of dataframe columns to be summarized.""" return self.info.col_count
def add_memory_usage_line(self) -> None: """Add line containing memory usage.""" self._lines.append(f"memory usage: {self.memory_usage_string}")
class _DataFrameTableBuilderNonVerbose(_DataFrameTableBuilder): """ Dataframe info table builder for non-verbose output. """
def _fill_non_empty_info(self) -> None: """Add lines to the info table, pertaining to non-empty dataframe.""" self.add_object_type_line() self.add_index_range_line() self.add_columns_summary_line() self.add_dtypes_line() if self.display_memory_usage: self.add_memory_usage_line()
def add_columns_summary_line(self) -> None: self._lines.append(self.ids._summary(name="Columns"))
class _TableBuilderVerboseMixin(_TableBuilderAbstract): """ Mixin for verbose info output. """
SPACING: str = " " * 2 strrows: Sequence[Sequence[str]] gross_column_widths: Sequence[int] with_counts: bool
@property @abstractmethod def headers(self) -> Sequence[str]: """Headers names of the columns in verbose table."""
@property def header_column_widths(self) -> Sequence[int]: """Widths of header columns (only titles).""" return [len(col) for col in self.headers]
def _get_gross_column_widths(self) -> Sequence[int]: """Get widths of columns containing both headers and actual content.""" body_column_widths = self._get_body_column_widths() return [ max(*widths) for widths in zip( self.header_column_widths, body_column_widths, strict=False ) ]
def _get_body_column_widths(self) -> Sequence[int]: """Get widths of table content columns.""" strcols: Sequence[Sequence[str]] = list(zip(*self.strrows, strict=True)) return [max(len(x) for x in col) for col in strcols]
def _gen_rows(self) -> Iterator[Sequence[str]]: """ Generator function yielding rows content.
Each element represents a row comprising a sequence of strings. """ if self.with_counts: return self._gen_rows_with_counts() else: return self._gen_rows_without_counts()
@abstractmethod def _gen_rows_with_counts(self) -> Iterator[Sequence[str]]: """Iterator with string representation of body data with counts."""
@abstractmethod def _gen_rows_without_counts(self) -> Iterator[Sequence[str]]: """Iterator with string representation of body data without counts."""
def add_header_line(self) -> None: header_line = self.SPACING.join( [ _put_str(header, col_width) for header, col_width in zip( self.headers, self.gross_column_widths, strict=True ) ] ) self._lines.append(header_line)
def add_separator_line(self) -> None: separator_line = self.SPACING.join( [ _put_str("-" * header_colwidth, gross_colwidth) for header_colwidth, gross_colwidth in zip( self.header_column_widths, self.gross_column_widths, strict=True ) ] ) self._lines.append(separator_line)
def add_body_lines(self) -> None: for row in self.strrows: body_line = self.SPACING.join( [ _put_str(col, gross_colwidth) for col, gross_colwidth in zip( row, self.gross_column_widths, strict=True ) ] ) self._lines.append(body_line)
def _gen_non_null_counts(self) -> Iterator[str]: """Iterator with string representation of non-null counts.""" for count in self.non_null_counts: yield f"{count} non-null"
def _gen_dtypes(self) -> Iterator[str]: """Iterator with string representation of column dtypes.""" for dtype in self.dtypes: yield pprint_thing(dtype)
class _DataFrameTableBuilderVerbose(_DataFrameTableBuilder, _TableBuilderVerboseMixin): """ Dataframe info table builder for verbose output. """
def __init__( self, *, info: DataFrameInfo, with_counts: bool, ) -> None: self.info = info self.with_counts = with_counts self.strrows: Sequence[Sequence[str]] = list(self._gen_rows()) self.gross_column_widths: Sequence[int] = self._get_gross_column_widths()
def _fill_non_empty_info(self) -> None: """Add lines to the info table, pertaining to non-empty dataframe.""" self.add_object_type_line() self.add_index_range_line() self.add_columns_summary_line() self.add_header_line() self.add_separator_line() self.add_body_lines() self.add_dtypes_line() if self.display_memory_usage: self.add_memory_usage_line()
@property def headers(self) -> Sequence[str]: """Headers names of the columns in verbose table.""" if self.with_counts: return [" # ", "Column", "Non-Null Count", "Dtype"] return [" # ", "Column", "Dtype"]
def add_columns_summary_line(self) -> None: self._lines.append(f"Data columns (total {self.col_count} columns):")
def _gen_rows_without_counts(self) -> Iterator[Sequence[str]]: """Iterator with string representation of body data without counts.""" yield from zip( self._gen_line_numbers(), self._gen_columns(), self._gen_dtypes(), strict=True, )
def _gen_rows_with_counts(self) -> Iterator[Sequence[str]]: """Iterator with string representation of body data with counts.""" yield from zip( self._gen_line_numbers(), self._gen_columns(), self._gen_non_null_counts(), self._gen_dtypes(), strict=True, )
def _gen_line_numbers(self) -> Iterator[str]: """Iterator with string representation of column numbers.""" for i, _ in enumerate(self.ids): yield f" {i}"
def _gen_columns(self) -> Iterator[str]: """Iterator with string representation of column names.""" for col in self.ids: yield pprint_thing(col)
class _SeriesTableBuilder(_TableBuilderAbstract): """ Abstract builder for series info table.
Parameters ---------- info : SeriesInfo. Instance of SeriesInfo. """
def __init__(self, *, info: SeriesInfo) -> None: self.info: SeriesInfo = info
def get_lines(self) -> list[str]: self._lines = [] self._fill_non_empty_info() return self._lines
@property def data(self) -> Series: """Series.""" return self.info.data
def add_memory_usage_line(self) -> None: """Add line containing memory usage.""" self._lines.append(f"memory usage: {self.memory_usage_string}")
@abstractmethod def _fill_non_empty_info(self) -> None: """Add lines to the info table, pertaining to non-empty series."""
class _SeriesTableBuilderNonVerbose(_SeriesTableBuilder): """ Series info table builder for non-verbose output. """
def _fill_non_empty_info(self) -> None: """Add lines to the info table, pertaining to non-empty series.""" self.add_object_type_line() self.add_index_range_line() self.add_dtypes_line() if self.display_memory_usage: self.add_memory_usage_line()
class _SeriesTableBuilderVerbose(_SeriesTableBuilder, _TableBuilderVerboseMixin): """ Series info table builder for verbose output. """
def __init__( self, *, info: SeriesInfo, with_counts: bool, ) -> None: self.info = info self.with_counts = with_counts self.strrows: Sequence[Sequence[str]] = list(self._gen_rows()) self.gross_column_widths: Sequence[int] = self._get_gross_column_widths()
def _fill_non_empty_info(self) -> None: """Add lines to the info table, pertaining to non-empty series.""" self.add_object_type_line() self.add_index_range_line() self.add_series_name_line() self.add_header_line() self.add_separator_line() self.add_body_lines() self.add_dtypes_line() if self.display_memory_usage: self.add_memory_usage_line()
def add_series_name_line(self) -> None: self._lines.append(f"Series name: {self.data.name}")
@property def headers(self) -> Sequence[str]: """Headers names of the columns in verbose table.""" if self.with_counts: return ["Non-Null Count", "Dtype"] return ["Dtype"]
def _gen_rows_without_counts(self) -> Iterator[Sequence[str]]: """Iterator with string representation of body data without counts.""" yield from ([dtype] for dtype in self._gen_dtypes())
def _gen_rows_with_counts(self) -> Iterator[Sequence[str]]: """Iterator with string representation of body data with counts.""" yield from zip(self._gen_non_null_counts(), self._gen_dtypes(), strict=True)
def _get_dataframe_dtype_counts(df: DataFrame) -> Mapping[str, int]: """ Create mapping between datatypes and their number of occurrences. """ # groupby dtype.name to collect e.g. Categorical columns return df.dtypes.value_counts().groupby(lambda x: x.name).sum()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587"""Printing tools."""
from __future__ import annotations
from collections.abc import ( Callable, Iterable, Mapping, Sequence,)import sysfrom typing import ( TYPE_CHECKING, Any, TypeAlias, TypeVar,)from unicodedata import east_asian_width
from pandas._config import get_option
from pandas.core.dtypes.inference import is_sequence
from pandas.io.formats.console import get_console_size
if TYPE_CHECKING: from pandas._typing import ListLikeEscapeChars: TypeAlias = Mapping[str, str] | Iterable[str]_KT = TypeVar("_KT")_VT = TypeVar("_VT")
def adjoin(space: int, *lists: list[str], **kwargs: Any) -> str: """ Glues together two sets of strings using the amount of space requested. The idea is to prettify.
---------- space : int number of spaces for padding lists : str list of str which being joined strlen : callable function used to calculate the length of each str. Needed for unicode handling. justfunc : callable function used to justify str. Needed for unicode handling. """ strlen = kwargs.pop("strlen", len) justfunc = kwargs.pop("justfunc", _adj_justify)
newLists = [] lengths = [max(map(strlen, x)) + space for x in lists[:-1]] # not the last one lengths.append(max(map(len, lists[-1]))) maxLen = max(map(len, lists)) for i, lst in enumerate(lists): nl = justfunc(lst, lengths[i], mode="left") nl = ([" " * lengths[i]] * (maxLen - len(lst))) + nl newLists.append(nl) toJoin = zip(*newLists, strict=True) return "\n".join("".join(lines) for lines in toJoin)
def _adj_justify(texts: Iterable[str], max_len: int, mode: str = "right") -> list[str]: """ Perform ljust, center, rjust against string or list-like """ if mode == "left": return [x.ljust(max_len) for x in texts] elif mode == "center": return [x.center(max_len) for x in texts] else: return [x.rjust(max_len) for x in texts]
# Unicode consolidation# ---------------------## pprinting utility functions for generating Unicode text or# bytes(3.x)/str(2.x) representations of objects.# Try to use these as much as possible rather than rolling your own.## When to use# -----------## 1) If you're writing code internal to pandas (no I/O directly involved),# use pprint_thing().## It will always return unicode text which can handled by other# parts of the package without breakage.## 2) if you need to write something out to file, use# pprint_thing_encoded(encoding).## If no encoding is specified, it defaults to utf-8. Since encoding pure# ascii with utf-8 is a no-op you can safely use the default utf-8 if you're# working with straight ascii.
def _pprint_seq( seq: ListLike, _nest_lvl: int = 0, max_seq_items: int | None = None, **kwds: Any) -> str: """ internal. pprinter for iterables. you should probably use pprint_thing() rather than calling this directly.
bounds length of printed sequence, depending on options """ if isinstance(seq, set): fmt = "{{{body}}}" elif isinstance(seq, frozenset): fmt = "frozenset({{{body}}})" else: fmt = "[{body}]" if hasattr(seq, "__setitem__") else "({body})"
if max_seq_items is False: max_items = None else: max_items = max_seq_items or get_option("max_seq_items") or len(seq)
s = iter(seq) # handle sets, no slicing r = [] max_items_reached = False for i, item in enumerate(s): if (max_items is not None) and (i >= max_items): max_items_reached = True break r.append(pprint_thing(item, _nest_lvl + 1, max_seq_items=max_seq_items, **kwds)) body = ", ".join(r)
if max_items_reached: body += ", ..." elif isinstance(seq, tuple) and len(seq) == 1: body += ","
return fmt.format(body=body)
def _pprint_dict( seq: Mapping, _nest_lvl: int = 0, max_seq_items: int | None = None, **kwds: Any) -> str: """ internal. pprinter for iterables. you should probably use pprint_thing() rather than calling this directly. """ fmt = "{{{things}}}" pairs = []
pfmt = "{key}: {val}"
if max_seq_items is False: nitems = len(seq) else: nitems = max_seq_items or get_option("max_seq_items") or len(seq)
for k, v in list(seq.items())[:nitems]: pairs.append( pfmt.format( key=pprint_thing(k, _nest_lvl + 1, max_seq_items=max_seq_items, **kwds), val=pprint_thing(v, _nest_lvl + 1, max_seq_items=max_seq_items, **kwds), ) )
if nitems < len(seq): return fmt.format(things=", ".join(pairs) + ", ...") else: return fmt.format(things=", ".join(pairs))
def pprint_thing( thing: object, _nest_lvl: int = 0, escape_chars: EscapeChars | None = None, default_escapes: bool = False, quote_strings: bool = False, max_seq_items: int | None = None,) -> str: """ This function is the sanctioned way of converting objects to a string representation and properly handles nested sequences.
Parameters ---------- thing : anything to be formatted _nest_lvl : internal use only. pprint_thing() is mutually-recursive with pprint_sequence, this argument is used to keep track of the current nesting level, and limit it. escape_chars : list[str] or Mapping[str, str], optional Characters to escape. If a Mapping is passed the values are the replacements default_escapes : bool, default False Whether the input escape characters replaces or adds to the defaults max_seq_items : int or None, default None Pass through to other pretty printers to limit sequence printing
Returns ------- str """
def as_escaped_string( thing: Any, escape_chars: EscapeChars | None = escape_chars ) -> str: translate = {"\t": r"\t", "\n": r"\n", "\r": r"\r", "'": r"\'"} if isinstance(escape_chars, Mapping): if default_escapes: translate.update(escape_chars) else: translate = escape_chars # type: ignore[assignment] escape_chars = list(escape_chars.keys()) else: escape_chars = escape_chars or ()
result = str(thing) for c in escape_chars: result = result.replace(c, translate[c]) return result
if hasattr(thing, "__next__"): return str(thing) elif isinstance(thing, Mapping) and _nest_lvl < get_option( "display.pprint_nest_depth" ): result = _pprint_dict( thing, _nest_lvl, quote_strings=True, max_seq_items=max_seq_items ) elif is_sequence(thing) and _nest_lvl < get_option("display.pprint_nest_depth"): result = _pprint_seq( # error: Argument 1 to "_pprint_seq" has incompatible type "object"; # expected "ExtensionArray | ndarray[Any, Any] | Index | Series | # SequenceNotStr[Any] | range" thing, # type: ignore[arg-type] _nest_lvl, escape_chars=escape_chars, quote_strings=quote_strings, max_seq_items=max_seq_items, ) elif isinstance(thing, str) and quote_strings: result = f"'{as_escaped_string(thing)}'" else: result = as_escaped_string(thing)
return result
def pprint_thing_encoded( object: object, encoding: str = "utf-8", errors: str = "replace") -> bytes: value = pprint_thing(object) # get unicode representation of object return value.encode(encoding, errors)
def enable_data_resource_formatter(enable: bool) -> None: if "IPython" not in sys.modules: # definitely not in IPython return from IPython import get_ipython
# error: Call to untyped function "get_ipython" in typed context ip = get_ipython() # type: ignore[no-untyped-call] if ip is None: # still not in IPython return
formatters = ip.display_formatter.formatters mimetype = "application/vnd.dataresource+json"
if enable: if mimetype not in formatters: # define tableschema formatter from IPython.core.formatters import BaseFormatter from traitlets import ObjectName
class TableSchemaFormatter(BaseFormatter): print_method = ObjectName("_repr_data_resource_") _return_type = (dict,)
# register it: formatters[mimetype] = TableSchemaFormatter() # enable it if it's been disabled: formatters[mimetype].enabled = True # unregister tableschema mime-type elif mimetype in formatters: formatters[mimetype].enabled = False
def default_pprint(thing: Any, max_seq_items: int | None = None) -> str: return pprint_thing( thing, escape_chars=("\t", "\r", "\n"), quote_strings=True, max_seq_items=max_seq_items, )
def format_object_summary( obj: ListLike, formatter: Callable, is_justify: bool = True, name: str | None = None, indent_for_name: bool = True, line_break_each_value: bool = False,) -> str: """ Return the formatted obj as a unicode string
Parameters ---------- obj : object must be iterable and support __getitem__ formatter : callable string formatter for an element is_justify : bool should justify the display name : name, optional defaults to the class name of the obj indent_for_name : bool, default True Whether subsequent lines should be indented to align with the name. line_break_each_value : bool, default False If True, inserts a line break for each value of ``obj``. If False, only break lines when the a line of values gets wider than the display width.
Returns ------- summary string """ display_width, _ = get_console_size() if display_width is None: display_width = get_option("display.width") or 80 if name is None: name = type(obj).__name__
if indent_for_name: name_len = len(name) space1 = f"\n{(' ' * (name_len + 1))}" space2 = f"\n{(' ' * (name_len + 2))}" else: space1 = "\n" space2 = "\n " # space for the opening '['
n = len(obj) if line_break_each_value: # If we want to vertically align on each value of obj, we need to # separate values by a line break and indent the values sep = ",\n " + " " * len(name) else: sep = "," max_seq_items = get_option("display.max_seq_items") or n
# are we a truncated display is_truncated = n > max_seq_items
# adj can optionally handle unicode eastern asian width adj = get_adjustment()
def _extend_line( s: str, line: str, value: str, display_width: int, next_line_prefix: str ) -> tuple[str, str]: if adj.len(line.rstrip()) + adj.len(value.rstrip()) >= display_width: s += line.rstrip() line = next_line_prefix line += value return s, line
def best_len(values: list[str]) -> int: if values: return max(adj.len(x) for x in values) else: return 0
close = ", "
if n == 0: summary = f"[]{close}" elif n == 1 and not line_break_each_value: first = formatter(obj[0]) summary = f"[{first}]{close}" elif n == 2 and not line_break_each_value: first = formatter(obj[0]) last = formatter(obj[-1]) summary = f"[{first}, {last}]{close}" else: if max_seq_items == 1: # If max_seq_items=1 show only last element head = [] tail = [formatter(x) for x in obj[-1:]] elif n > max_seq_items: n = min(max_seq_items // 2, 10) head = [formatter(x) for x in obj[:n]] tail = [formatter(x) for x in obj[-n:]] else: head = [] tail = [formatter(x) for x in obj]
# adjust all values to max length if needed if is_justify: if line_break_each_value: # Justify each string in the values of head and tail, so the # strings will right align when head and tail are stacked # vertically. head, tail = _justify(head, tail) elif is_truncated or not ( len(", ".join(head)) < display_width and len(", ".join(tail)) < display_width ): # Each string in head and tail should align with each other max_length = max(best_len(head), best_len(tail)) head = [x.rjust(max_length) for x in head] tail = [x.rjust(max_length) for x in tail] # If we are not truncated and we are only a single # line, then don't justify
if line_break_each_value: # Now head and tail are of type List[Tuple[str]]. Below we # convert them into List[str], so there will be one string per # value. Also truncate items horizontally if wider than # max_space max_space = display_width - len(space2) value = tail[0] max_items = 1 for num_items in reversed(range(1, len(value) + 1)): pprinted_seq = _pprint_seq(value, max_seq_items=num_items) if len(pprinted_seq) < max_space: max_items = num_items break head = [_pprint_seq(x, max_seq_items=max_items) for x in head] tail = [_pprint_seq(x, max_seq_items=max_items) for x in tail]
summary = "" line = space2
for head_value in head: word = head_value + sep + " " summary, line = _extend_line(summary, line, word, display_width, space2)
if is_truncated: # remove trailing space of last line summary += line.rstrip() + space2 + "..." line = space2
for tail_item in tail[:-1]: word = tail_item + sep + " " summary, line = _extend_line(summary, line, word, display_width, space2)
# last value: no sep added + 1 space of width used for trailing ',' summary, line = _extend_line(summary, line, tail[-1], display_width - 2, space2) summary += line
# right now close is either '' or ', ' # Now we want to include the ']', but not the maybe space. close = "]" + close.rstrip(" ") summary += close
if len(summary) > (display_width) or line_break_each_value: summary += space1 else: # one row summary += " "
# remove initial space summary = "[" + summary[len(space2) :]
return summary
def _justify( head: list[Sequence[str]], tail: list[Sequence[str]]) -> tuple[list[tuple[str, ...]], list[tuple[str, ...]]]: """ Justify items in head and tail, so they are right-aligned when stacked.
Parameters ---------- head : list-like of list-likes of strings tail : list-like of list-likes of strings
Returns ------- tuple of list of tuples of strings Same as head and tail, but items are right aligned when stacked vertically.
Examples -------- >>> _justify([["a", "b"]], [["abc", "abcd"]]) ([(' a', ' b')], [('abc', 'abcd')]) """ combined = head + tail
# For each position for the sequences in ``combined``, # find the length of the largest string. max_length = [0] * len(combined[0]) for inner_seq in combined: length = [len(item) for item in inner_seq] max_length = [max(x, y) for x, y in zip(max_length, length, strict=True)]
# justify each item in each list-like in head and tail using max_length head_tuples = [ tuple(x.rjust(max_len) for x, max_len in zip(seq, max_length, strict=True)) for seq in head ] tail_tuples = [ tuple(x.rjust(max_len) for x, max_len in zip(seq, max_length, strict=True)) for seq in tail ] return head_tuples, tail_tuples
class PrettyDict(dict[_KT, _VT]): """Dict extension to support abbreviated __repr__"""
def __repr__(self) -> str: return pprint_thing(self)
class _TextAdjustment: def __init__(self) -> None: self.encoding = get_option("display.encoding")
def len(self, text: str) -> int: return len(text)
def justify(self, texts: Any, max_len: int, mode: str = "right") -> list[str]: """ Perform ljust, center, rjust against string or list-like """ if mode == "left": return [x.ljust(max_len) for x in texts] elif mode == "center": return [x.center(max_len) for x in texts] else: return [x.rjust(max_len) for x in texts]
def adjoin(self, space: int, *lists: Any, **kwargs: Any) -> str: return adjoin(space, *lists, strlen=self.len, justfunc=self.justify, **kwargs)
class _EastAsianTextAdjustment(_TextAdjustment): def __init__(self) -> None: super().__init__() if get_option("display.unicode.ambiguous_as_wide"): self.ambiguous_width = 2 else: self.ambiguous_width = 1
# Definition of East Asian Width # https://unicode.org/reports/tr11/ # Ambiguous width can be changed by option self._EAW_MAP = {"Na": 1, "N": 1, "W": 2, "F": 2, "H": 1}
def len(self, text: str) -> int: """ Calculate display width considering unicode East Asian Width """ if not isinstance(text, str): return len(text)
return sum( self._EAW_MAP.get(east_asian_width(c), self.ambiguous_width) for c in text )
def justify( self, texts: Iterable[str], max_len: int, mode: str = "right" ) -> list[str]: # re-calculate padding space per str considering East Asian Width def _get_pad(t: str) -> int: return max_len - self.len(t) + len(t)
if mode == "left": return [x.ljust(_get_pad(x)) for x in texts] elif mode == "center": return [x.center(_get_pad(x)) for x in texts] else: return [x.rjust(_get_pad(x)) for x in texts]
def get_adjustment() -> _TextAdjustment: use_east_asian_width = get_option("display.unicode.east_asian_width") if use_east_asian_width: return _EastAsianTextAdjustment() else: return _TextAdjustment()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207"""Module for formatting output data in console (to string)."""
from __future__ import annotations
from shutil import get_terminal_sizefrom typing import TYPE_CHECKING
import numpy as np
from pandas.io.formats.printing import pprint_thing
if TYPE_CHECKING: from collections.abc import Iterable
from pandas.io.formats.format import DataFrameFormatter
class StringFormatter: """Formatter for string representation of a dataframe."""
def __init__(self, fmt: DataFrameFormatter, line_width: int | None = None) -> None: self.fmt = fmt self.adj = fmt.adj self.frame = fmt.frame self.line_width = line_width
def to_string(self) -> str: text = self._get_string_representation() if self.fmt.should_show_dimensions: text = f"{text}{self.fmt.dimensions_info}" return text
def _get_strcols(self) -> list[list[str]]: strcols = self.fmt.get_strcols() if self.fmt.is_truncated: strcols = self._insert_dot_separators(strcols) return strcols
def _get_string_representation(self) -> str: if self.fmt.frame.empty: return self._empty_info_line
strcols = self._get_strcols()
if self.line_width is None: # no need to wrap around just print the whole frame return self.adj.adjoin(1, *strcols)
if self._need_to_wrap_around: return self._join_multiline(strcols)
return self._fit_strcols_to_terminal_width(strcols)
@property def _empty_info_line(self) -> str: return ( f"Empty {type(self.frame).__name__}\n" f"Columns: {pprint_thing(self.frame.columns)}\n" f"Index: {pprint_thing(self.frame.index)}" )
@property def _need_to_wrap_around(self) -> bool: return bool(self.fmt.max_cols is None or self.fmt.max_cols > 0)
def _insert_dot_separators(self, strcols: list[list[str]]) -> list[list[str]]: str_index = self.fmt._get_formatted_index(self.fmt.tr_frame) index_length = len(str_index)
if self.fmt.is_truncated_horizontally: strcols = self._insert_dot_separator_horizontal(strcols, index_length)
if self.fmt.is_truncated_vertically: strcols = self._insert_dot_separator_vertical(strcols, index_length)
return strcols
@property def _adjusted_tr_col_num(self) -> int: return self.fmt.tr_col_num + 1 if self.fmt.index else self.fmt.tr_col_num
def _insert_dot_separator_horizontal( self, strcols: list[list[str]], index_length: int ) -> list[list[str]]: strcols.insert(self._adjusted_tr_col_num, [" ..."] * index_length) return strcols
def _insert_dot_separator_vertical( self, strcols: list[list[str]], index_length: int ) -> list[list[str]]: n_header_rows = index_length - len(self.fmt.tr_frame) row_num = self.fmt.tr_row_num for ix, col in enumerate(strcols): cwidth = self.adj.len(col[row_num])
if self.fmt.is_truncated_horizontally: is_dot_col = ix == self._adjusted_tr_col_num else: is_dot_col = False
if cwidth > 3 or is_dot_col: dots = "..." else: dots = ".."
if ix == 0 and self.fmt.index: dot_mode = "left" elif is_dot_col: cwidth = 4 dot_mode = "right" else: dot_mode = "right"
dot_str = self.adj.justify([dots], cwidth, mode=dot_mode)[0] col.insert(row_num + n_header_rows, dot_str) return strcols
def _join_multiline(self, strcols_input: Iterable[list[str]]) -> str: lwidth = self.line_width adjoin_width = 1 strcols = list(strcols_input)
if self.fmt.index: idx = strcols.pop(0) lwidth -= np.array([self.adj.len(x) for x in idx]).max() + adjoin_width
col_widths = [ np.array([self.adj.len(x) for x in col]).max() if len(col) > 0 else 0 for col in strcols ]
assert lwidth is not None col_bins = _binify(col_widths, lwidth) nbins = len(col_bins)
str_lst = [] start = 0 for i, end in enumerate(col_bins): row = strcols[start:end] if self.fmt.index: row.insert(0, idx) if nbins > 1: nrows = len(row[-1]) if end <= len(strcols) and i < nbins - 1: row.append([" \\"] + [" "] * (nrows - 1)) else: row.append([" "] * nrows) str_lst.append(self.adj.adjoin(adjoin_width, *row)) start = end return "\n\n".join(str_lst)
def _fit_strcols_to_terminal_width(self, strcols: list[list[str]]) -> str: from pandas import Series
lines = self.adj.adjoin(1, *strcols).split("\n") max_len = Series(lines).str.len().max() # plus truncate dot col width, _ = get_terminal_size() dif = max_len - width # '+ 1' to avoid too wide repr (GH PR #17023) adj_dif = dif + 1 col_lens = Series([Series(ele).str.len().max() for ele in strcols]) n_cols = len(col_lens) counter = 0 while adj_dif > 0 and n_cols > 1: counter += 1 mid = round(n_cols / 2) mid_ix = col_lens.index[mid] col_len = col_lens[mid_ix] # adjoin adds one adj_dif -= col_len + 1 col_lens = col_lens.drop(mid_ix) n_cols = len(col_lens)
# subtract index column max_cols_fitted = n_cols - self.fmt.index # GH-21180. Ensure that we print at least two. max_cols_fitted = max(max_cols_fitted, 2) self.fmt.max_cols_fitted = max_cols_fitted
# Call again _truncate to cut frame appropriately # and then generate string representation self.fmt.truncate() strcols = self._get_strcols() return self.adj.adjoin(1, *strcols)
def _binify(cols: list[int], line_width: int) -> list[int]: adjoin_width = 1 bins = [] curr_width = 0 i_last_column = len(cols) - 1 for i, w in enumerate(cols): w_adjoined = w + adjoin_width curr_width += w_adjoined if i_last_column == i: wrap = curr_width + 1 > line_width and i > 0 else: wrap = curr_width + 2 > line_width and i > 0 if wrap: bins.append(i) curr_width = w_adjoined
bins.append(len(cols)) return bins.gitattributes+3
.venv/lib/python3.12/site-packages/pandas/io/__pycache__/parquet.cpython-312.pycAdded
.venv/lib/python3.12/site-packages/pandas/io/__pycache__/pickle.cpython-312.pycAdded
.venv/lib/python3.12/site-packages/pandas/io/__pycache__/pytables.cpython-312.pycAdded+3
.venv/lib/python3.12/site-packages/pandas/io/__pycache__/spss.cpython-312.pycAdded
.venv/lib/python3.12/site-packages/pandas/io/__pycache__/sql.cpython-312.pycAdded+3
.venv/lib/python3.12/site-packages/pandas/io/__pycache__/stata.cpython-312.pycAdded+3
.venv/lib/python3.12/site-packages/pandas/io/__pycache__/xml.cpython-312.pycAdded
.venv/lib/python3.12/site-packages/pandas/io/_util.pyAdded+310
.venv/lib/python3.12/site-packages/pandas/io/api.pyAdded+65
.venv/lib/python3.12/site-packages/pandas/io/clipboard/__init__.pyAdded+747
.venv/lib/python3.12/site-packages/pandas/io/clipboards.pyAdded+200
.venv/lib/python3.12/site-packages/pandas/io/common.pyAdded+1332
.venv/lib/python3.12/site-packages/pandas/io/excel/__init__.pyAdded+19
.venv/lib/python3.12/site-packages/pandas/io/excel/__pycache__/__init__.cpython-312.pycAdded
.venv/lib/python3.12/site-packages/pandas/io/excel/__pycache__/_base.cpython-312.pycAdded
.venv/lib/python3.12/site-packages/pandas/io/excel/__pycache__/_calamine.cpython-312.pycAdded
.venv/lib/python3.12/site-packages/pandas/io/excel/__pycache__/_odfreader.cpython-312.pycAdded
.venv/lib/python3.12/site-packages/pandas/io/excel/__pycache__/_odswriter.cpython-312.pycAdded
.venv/lib/python3.12/site-packages/pandas/io/excel/__pycache__/_openpyxl.cpython-312.pycAdded
.venv/lib/python3.12/site-packages/pandas/io/excel/__pycache__/_pyxlsb.cpython-312.pycAdded
.venv/lib/python3.12/site-packages/pandas/io/excel/__pycache__/_util.cpython-312.pycAdded
.venv/lib/python3.12/site-packages/pandas/io/excel/__pycache__/_xlrd.cpython-312.pycAdded
.venv/lib/python3.12/site-packages/pandas/io/excel/__pycache__/_xlsxwriter.cpython-312.pycAdded
.venv/lib/python3.12/site-packages/pandas/io/excel/_base.pyAdded+1871
.venv/lib/python3.12/site-packages/pandas/io/excel/_calamine.pyAdded+129
.venv/lib/python3.12/site-packages/pandas/io/excel/_odfreader.pyAdded+249
.venv/lib/python3.12/site-packages/pandas/io/excel/_odswriter.pyAdded+362
.venv/lib/python3.12/site-packages/pandas/io/excel/_openpyxl.pyAdded+646
.venv/lib/python3.12/site-packages/pandas/io/excel/_pyxlsb.pyAdded+131
.venv/lib/python3.12/site-packages/pandas/io/excel/_util.pyAdded+328
.venv/lib/python3.12/site-packages/pandas/io/excel/_xlrd.pyAdded+147
.venv/lib/python3.12/site-packages/pandas/io/excel/_xlsxwriter.pyAdded+288
.venv/lib/python3.12/site-packages/pandas/io/feather_format.pyAdded+205
.venv/lib/python3.12/site-packages/pandas/io/formats/__init__.pyAdded+9
.venv/lib/python3.12/site-packages/pandas/io/formats/__pycache__/__init__.cpython-312.pycAdded
.venv/lib/python3.12/site-packages/pandas/io/formats/__pycache__/console.cpython-312.pycAdded
.venv/lib/python3.12/site-packages/pandas/io/formats/__pycache__/format.cpython-312.pycAdded
.venv/lib/python3.12/site-packages/pandas/io/formats/__pycache__/info.cpython-312.pycAdded
.venv/lib/python3.12/site-packages/pandas/io/formats/__pycache__/printing.cpython-312.pycAdded
.venv/lib/python3.12/site-packages/pandas/io/formats/_color_data.pyAdded+157
.venv/lib/python3.12/site-packages/pandas/io/formats/console.pyAdded+95
.venv/lib/python3.12/site-packages/pandas/io/formats/css.pyAdded+425
.venv/lib/python3.12/site-packages/pandas/io/formats/csvs.pyAdded+336
.venv/lib/python3.12/site-packages/pandas/io/formats/excel.pyAdded+1023
.venv/lib/python3.12/site-packages/pandas/io/formats/format.pyAdded+2080
.venv/lib/python3.12/site-packages/pandas/io/formats/html.pyAdded+657
.venv/lib/python3.12/site-packages/pandas/io/formats/info.pyAdded+943
.venv/lib/python3.12/site-packages/pandas/io/formats/printing.pyAdded+587
.venv/lib/python3.12/site-packages/pandas/io/formats/string.pyAdded+207