IO Module Description¶
Dispatcher Classes Workflow Overview¶
Call from read_*
function of execution-specific IO class (for example, PandasOnRayIO
for
Ray engine and pandas storage format) is forwarded to the _read
function of file
format-specific class (for example CSVDispatcher
for CSV files), where function parameters are
preprocessed to check if they are supported (otherwise default pandas implementation
is used) and compute some metadata common for all partitions. Then file is splitted
into chunks (mechanism of splitting is described below) and using this data, tasks
are launched on the remote workers. After remote tasks are finished, additional
results postprocessing is performed, and new query compiler with imported data will
be returned.
Data File Splitting Mechanism¶
Modin file splitting mechanism differs depending on the data format type:
text format type - file is splitted into bytes according user specified needs. In the simplest case, when no row related parameters (such as
nrows
orskiprows
) are passed, data chunks limits (start and end bytes) are derived by just roughly dividing the file size by the number of partitions (chunks can slightly differ between each other because usually end byte may occurs inside a line and in that case the last byte of the line should be used instead of initial value). In other cases the same splitting into bytes is used, but chunks sizes are defined according to the number of lines that each partition should contain.columnar store type - file is splitted by even distribution of columns that should be read between chunks.
SQL type - chunking is obtained by wrapping initial SQL query into query that specifies initial row offset and number of rows in the chunk.
After file splitting is complete, chunks data is passed to the parser functions
(PandasCSVParser.parse
for read_csv
function with pandas storage format) for
further processing on each worker.
Submodules Description¶
modin.core.io
module is used mostly for storing utils and dispatcher
classes for reading files of different formats.
io.py
- class containing basic utils and default implementation of IO functions.file_dispatcher.py
- class reading data from different kinds of files and handling some util functions common for all formats. Also this class containsread
function which is entry point function for all dispatchers_read
functions.text - directory for storing all text file format dispatcher classes
text_file_dispatcher.py
- class for reading text formats files. This class holdspartitioned_file
function for splitting text format files into chunks,offset
function for moving file offset at the specified amount of bytes,_read_rows
function for moving file offset at the specified amount of rows and many other functions.format/feature specific dispatchers:
csv_dispatcher.py
,csv_glob_dispatcher.py
(reading multiple files simultaneously, experimental feature),excel_dispatcher.py
,fwf_dispatcher.py
andjson_dispatcher.py
.
column_stores - directory for storing all columnar store file format dispatcher classes
column_store_dispatcher.py
- class for reading columnar type files. This class holdsbuild_query_compiler
function that performs file splitting, deploying remote tasks and results postprocessing and many other functions.format/feature specific dispatchers:
feather_dispatcher.py
,hdf_dispatcher.py
andparquet_dispatcher.py
.
sql - directory for storing SQL dispatcher class
sql_dispatcher.py
- class for reading SQL queries or database tables.
Public API¶
IO functions implementations.
- class modin.core.io.BaseIO¶
Class for basic utils and default implementation of IO functions.
- classmethod from_arrow(at)¶
Create a Modin query_compiler from a pyarrow.Table.
- Parameters
at (Arrow Table) – The Arrow Table to convert from.
- Returns
QueryCompiler containing data from the Arrow Table.
- Return type
- classmethod from_non_pandas(*args, **kwargs)¶
Create a Modin query_compiler from a non-pandas object.
- Parameters
*args (iterable) – Positional arguments to be passed into func.
**kwargs (dict) – Keyword arguments to be passed into func.
- classmethod from_pandas(df)¶
Create a Modin query_compiler from a pandas.DataFrame.
- Parameters
df (pandas.DataFrame) – The pandas DataFrame to convert from.
- Returns
QueryCompiler containing data from the pandas.DataFrame.
- Return type
- classmethod read_clipboard(sep='\\s+', **kwargs)¶
Read text from clipboard into query compiler using pandas.
For parameters description please refer to pandas API.
- Returns
QueryCompiler with read data.
- Return type
Notes
See pandas API documentation for pandas.read_clipboard for more.
- classmethod read_csv(filepath_or_buffer, sep=NoDefault.no_default, delimiter=None, header='infer', names=NoDefault.no_default, index_col=None, usecols=None, squeeze=False, prefix=NoDefault.no_default, mangle_dupe_cols=True, dtype=None, engine=None, converters=None, true_values=None, false_values=None, skipinitialspace=False, skiprows=None, nrows=None, na_values=None, keep_default_na=True, na_filter=True, verbose=False, skip_blank_lines=True, parse_dates=False, infer_datetime_format=False, keep_date_col=False, date_parser=None, dayfirst=False, cache_dates=True, iterator=False, chunksize=None, compression='infer', thousands=None, decimal=b'.', lineterminator=None, quotechar='"', quoting=0, escapechar=None, comment=None, encoding=None, encoding_errors='strict', dialect=None, error_bad_lines=None, warn_bad_lines=None, on_bad_lines=None, skipfooter=0, doublequote=True, delim_whitespace=False, low_memory=True, memory_map=False, float_precision=None, storage_options=None)¶
Read a comma-separated values (CSV) file into query compiler using pandas.
For parameters description please refer to pandas API.
- Returns
QueryCompiler or TextParser with read data.
- Return type
BaseQueryCompiler or TextParser
Notes
See pandas API documentation for pandas.read_csv for more.
- classmethod read_excel(io, sheet_name=0, header=0, names=None, index_col=None, usecols=None, squeeze=False, dtype=None, engine=None, converters=None, true_values=None, false_values=None, skiprows=None, nrows=None, na_values=None, keep_default_na=True, verbose=False, parse_dates=False, date_parser=None, thousands=None, comment=None, skip_footer=0, skipfooter=0, convert_float=True, mangle_dupe_cols=True, na_filter=True, **kwds)¶
Read an Excel file into query compiler using pandas.
For parameters description please refer to pandas API.
- Returns
QueryCompiler or OrderedDict/dict with read data.
- Return type
BaseQueryCompiler or dict/OrderedDict
Notes
See pandas API documentation for pandas.read_excel for more.
- classmethod read_feather(path, columns=None, use_threads=True, storage_options=None)¶
Load a feather-format object from the file path into query compiler using pandas.
For parameters description please refer to pandas API.
- Returns
QueryCompiler with read data.
- Return type
Notes
See pandas API documentation for pandas.read_feather for more.
- classmethod read_fwf(filepath_or_buffer, colspecs='infer', widths=None, infer_nrows=100, **kwds)¶
Read a table of fixed-width formatted lines into query compiler using pandas.
For parameters description please refer to pandas API.
- Returns
QueryCompiler or TextParser with read data.
- Return type
BaseQueryCompiler or TextParser
Notes
See pandas API documentation for pandas.read_fwf for more.
- classmethod read_gbq(query: str, project_id=None, index_col=None, col_order=None, reauth=False, auth_local_webserver=False, dialect=None, location=None, configuration=None, credentials=None, use_bqstorage_api=None, private_key=None, verbose=None, progress_bar_type=None, max_results=None)¶
Load data from Google BigQuery into query compiler using pandas.
For parameters description please refer to pandas API.
- Returns
QueryCompiler with read data.
- Return type
Notes
See pandas API documentation for pandas.read_gbq for more.
- classmethod read_hdf(path_or_buf, key=None, mode: str = 'r', errors: str = 'strict', where=None, start=None, stop=None, columns=None, iterator=False, chunksize=None, **kwargs)¶
Read data from hdf store into query compiler using pandas.
For parameters description please refer to pandas API.
- Returns
QueryCompiler with read data.
- Return type
Notes
See pandas API documentation for pandas.read_hdf for more.
- classmethod read_html(io, match='.+', flavor=None, header=None, index_col=None, skiprows=None, attrs=None, parse_dates=False, thousands=',', encoding=None, decimal='.', converters=None, na_values=None, keep_default_na=True, displayed_only=True)¶
Read HTML tables into query compiler using pandas.
For parameters description please refer to pandas API.
- Returns
QueryCompiler with read data.
- Return type
Notes
See pandas API documentation for pandas.read_html for more.
- classmethod read_json(path_or_buf=None, orient=None, typ='frame', dtype=True, convert_axes=True, convert_dates=True, keep_default_dates=True, numpy=False, precise_float=False, date_unit=None, encoding=None, encoding_errors='strict', lines=False, chunksize=None, compression='infer', nrows: Optional[int] = None, storage_options=None)¶
Convert a JSON string to query compiler using pandas.
For parameters description please refer to pandas API.
- Returns
QueryCompiler with read data.
- Return type
Notes
See pandas API documentation for pandas.read_json for more.
- classmethod read_parquet(path, engine, columns, storage_options, use_nullable_dtypes, **kwargs)¶
Load a parquet object from the file path, returning a query compiler using pandas.
For parameters description please refer to pandas API.
- Returns
QueryCompiler with read data.
- Return type
Notes
See pandas API documentation for pandas.read_parquet for more.
- classmethod read_pickle(filepath_or_buffer, compression='infer', storage_options=None)¶
Load pickled pandas object (or any object) from file into query compiler using pandas.
For parameters description please refer to pandas API.
- Returns
QueryCompiler with read data.
- Return type
Notes
See pandas API documentation for pandas.read_pickle for more.
- classmethod read_sas(filepath_or_buffer, format=None, index=None, encoding=None, chunksize=None, iterator=False)¶
Read SAS files stored as either XPORT or SAS7BDAT format files into query compiler using pandas.
For parameters description please refer to pandas API.
- Returns
QueryCompiler with read data.
- Return type
Notes
See pandas API documentation for pandas.read_sas for more.
- classmethod read_spss(path, usecols, convert_categoricals)¶
Load an SPSS file from the file path, returning a query compiler using pandas.
For parameters description please refer to pandas API.
- Returns
QueryCompiler with read data.
- Return type
Notes
See pandas API documentation for pandas.read_spss for more.
- classmethod read_sql(sql, con, index_col=None, coerce_float=True, params=None, parse_dates=None, columns=None, chunksize=None)¶
Read SQL query or database table into query compiler using pandas.
For parameters description please refer to pandas API.
- Returns
QueryCompiler with read data.
- Return type
Notes
See pandas API documentation for pandas.read_sql for more.
- classmethod read_sql_query(sql, con, index_col=None, coerce_float=True, params=None, parse_dates=None, chunksize=None, dtype=None)¶
Read SQL query into query compiler using pandas.
For parameters description please refer to pandas API.
- Returns
QueryCompiler with read data.
- Return type
Notes
See pandas API documentation for pandas.read_sql_query for more.
- classmethod read_sql_table(table_name, con, schema=None, index_col=None, coerce_float=True, parse_dates=None, columns=None, chunksize=None)¶
Read SQL database table into query compiler using pandas.
For parameters description please refer to pandas API.
- Returns
QueryCompiler with read data.
- Return type
Notes
See pandas API documentation for pandas.read_sql_table for more.
- classmethod read_stata(filepath_or_buffer, convert_dates=True, convert_categoricals=True, index_col=None, convert_missing=False, preserve_dtypes=True, columns=None, order_categoricals=True, chunksize=None, iterator=False, compression='infer', storage_options=None)¶
Read Stata file into query compiler using pandas.
For parameters description please refer to pandas API.
- Returns
QueryCompiler with read data.
- Return type
Notes
See pandas API documentation for pandas.read_stata for more.
- classmethod to_csv(obj, **kwargs)¶
Write object to a comma-separated values (CSV) file using pandas.
For parameters description please refer to pandas API.
Notes
See pandas API documentation for pandas.DataFrame.to_csv for more.
- classmethod to_parquet(obj, **kwargs)¶
Write object to the binary parquet format using pandas.
For parameters description please refer to pandas API.
Notes
See pandas API documentation for pandas.DataFrame.to_parquet for more.
- classmethod to_pickle(obj: Any, filepath_or_buffer, compression: Optional[Union[Literal['infer', 'gzip', 'bz2', 'zip', 'xz', 'zstd'], Dict[str, Any]]] = 'infer', protocol: int = 5, storage_options: Optional[Dict[str, Any]] = None)¶
Pickle (serialize) object to file.
- Parameters
path (str) – File path where the pickled object will be stored.
compression (str or dict, default 'infer') – For on-the-fly compression of the output data. If ‘infer’ and ‘path’ path-like, then detect compression from the following extensions: ‘.gz’, ‘.bz2’, ‘.zip’, ‘.xz’, or ‘.zst’ (otherwise no compression). Set to
None
for no compression. Can also be a dict with key'method'
set to one of {'zip'
,'gzip'
,'bz2'
,'zstd'
} and other key-value pairs are forwarded tozipfile.ZipFile
,gzip.GzipFile
,bz2.BZ2File
, orzstandard.ZstdDecompressor
, respectively. As an example, the following could be passed for faster compression and to create a reproducible gzip archive:compression={'method': 'gzip', 'compresslevel': 1, 'mtime': 1}
.protocol (int) –
Int which indicates which protocol should be used by the pickler, default HIGHEST_PROTOCOL (see 1 paragraph 12.1.2). The possible values are 0, 1, 2, 3, 4, 5. A negative value for the protocol parameter is equivalent to setting its value to HIGHEST_PROTOCOL.
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
as header options. For other URLs (e.g. starting with “s3://”, and “gcs://”) the key-value pairs are forwarded tofsspec
. Please seefsspec
andurllib
for more details.New in version 1.2.0.
See also
read_pickle
Load pickled pandas object (or any object) from file.
DataFrame.to_hdf
Write DataFrame to an HDF5 file.
DataFrame.to_sql
Write DataFrame to a SQL database.
DataFrame.to_parquet
Write a DataFrame to the binary parquet format.
Examples
>>> original_df = pd.DataFrame({"foo": range(5), "bar": range(5, 10)}) >>> original_df foo bar 0 0 5 1 1 6 2 2 7 3 3 8 4 4 9 >>> original_df.to_pickle("./dummy.pkl")
>>> unpickled_df = pd.read_pickle("./dummy.pkl") >>> unpickled_df foo bar 0 0 5 1 1 6 2 2 7 3 3 8 4 4 9
Notes
See pandas API documentation for pandas.DataFrame.to_pickle for more.
- classmethod to_sql(qc, name, con, schema=None, if_exists='fail', index=True, index_label=None, chunksize=None, dtype=None, method=None)¶
Write records stored in a DataFrame to a SQL database using pandas.
For parameters description please refer to pandas API.
Notes
See pandas API documentation for pandas.DataFrame.to_sql for more.
- class modin.core.io.CSVDispatcher¶
Class handles utils for reading .csv files.
- read_callback(sep=NoDefault.no_default, delimiter=None, header='infer', names=NoDefault.no_default, index_col=None, usecols=None, squeeze=None, prefix=NoDefault.no_default, mangle_dupe_cols=True, dtype: DtypeArg | None = None, engine: CSVEngine | None = None, converters=None, true_values=None, false_values=None, skipinitialspace=False, skiprows=None, skipfooter=0, nrows=None, na_values=None, keep_default_na=True, na_filter=True, verbose=False, skip_blank_lines=True, parse_dates=None, infer_datetime_format=False, keep_date_col=False, date_parser=None, dayfirst=False, cache_dates=True, iterator=False, chunksize=None, compression: CompressionOptions = 'infer', thousands=None, decimal: str = '.', lineterminator=None, quotechar='"', quoting=0, doublequote=True, escapechar=None, comment=None, encoding=None, encoding_errors: str | None = 'strict', dialect=None, error_bad_lines=None, warn_bad_lines=None, on_bad_lines=None, delim_whitespace=False, low_memory=True, memory_map=False, float_precision=None, storage_options: StorageOptions = None)¶
Read a comma-separated values (csv) file into DataFrame.
Also supports optionally iterating or breaking of the file into chunks.
Additional help can be found in the online docs for IO Tools.
- Parameters
filepath_or_buffer (str, 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, gs, and file. For file URLs, a host is expected. A local file could be: file://localhost/path/to/table.csv.
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 builtinopen
function) orStringIO
.sep (str, default ',') – Delimiter to use. If sep is None, the C engine cannot automatically detect the separator, but the Python parsing engine can, meaning the latter will be used and automatically detect the separator by Python’s builtin sniffer tool,
csv.Sniffer
. In addition, separators longer than 1 character and different from'\s+'
will be interpreted as regular expressions and will also force the use of the Python parsing engine. Note that regex delimiters are prone to ignoring quoted data. Regex example:'\r\t'
.delimiter (str, default
None
) – Alias for sep.header (int, list of int, None, default 'infer') – Row number(s) to use as the column names, and the start of the data. Default behavior is to infer the column names: if no names are passed the behavior is identical to
header=0
and column names are inferred from the first line of the file, if column names are passed explicitly then the behavior is identical toheader=None
. Explicitly passheader=0
to be able to replace existing names. The header can be a list of integers that specify row locations for a multi-index on the columns e.g. [0,1,3]. Intervening rows that are not specified will be skipped (e.g. 2 in this example is skipped). Note that this parameter ignores commented lines and empty lines ifskip_blank_lines=True
, soheader=0
denotes the first line of data rather than the first line of the file.names (array-like, optional) – List of column names to use. If the file contains a header row, then you should explicitly pass
header=0
to override the column names. Duplicates in this list are not allowed.index_col (int, str, sequence of int / str, or False, optional, default
None
) –Column(s) to use as the row labels of the
DataFrame
, either given as string name or column index. If a sequence of int / str is given, a MultiIndex is used.Note:
index_col=False
can be used to force pandas to not use the first column as the index, e.g. when you have a malformed file with delimiters at the end of each line.usecols (list-like or callable, optional) –
Return a subset of the columns. If list-like, all elements must either be positional (i.e. integer indices into the document columns) or strings that correspond to column names provided either by the user in names or inferred from the document header row(s). If
names
are given, the document header row(s) are not taken into account. For example, a valid list-like usecols parameter would be[0, 1, 2]
or['foo', 'bar', 'baz']
. Element order is ignored, sousecols=[0, 1]
is the same as[1, 0]
. To instantiate a DataFrame fromdata
with element order preserved usepd.read_csv(data, usecols=['foo', 'bar'])[['foo', 'bar']]
for columns in['foo', 'bar']
order orpd.read_csv(data, usecols=['foo', 'bar'])[['bar', 'foo']]
for['bar', 'foo']
order.If callable, the callable function will be evaluated against the column names, returning names where the callable function evaluates to True. An example of a valid callable argument would be
lambda x: x.upper() in ['AAA', 'BBB', 'DDD']
. Using this parameter results in much faster parsing time and lower memory usage.squeeze (bool, default False) –
If the parsed data only contains one column then return a Series.
Deprecated since version 1.4.0: Append
.squeeze("columns")
to the call toread_csv
to squeeze the data.prefix (str, optional) –
Prefix to add to column numbers when no header, e.g. ‘X’ for X0, X1, …
Deprecated since version 1.4.0: Use a list comprehension on the DataFrame’s columns after calling
read_csv
.mangle_dupe_cols (bool, default True) – Duplicate columns will be specified as ‘X’, ‘X.1’, …’X.N’, rather than ‘X’…’X’. Passing in False will cause data to be overwritten if there are duplicate names in the columns.
dtype (Type name or dict of column -> type, optional) – Data type for data or columns. E.g. {‘a’: np.float64, ‘b’: np.int32, ‘c’: ‘Int64’} Use str or object together with suitable na_values settings to preserve and not interpret dtype. If converters are specified, they will be applied INSTEAD of dtype conversion.
engine ({'c', 'python', 'pyarrow'}, optional) –
Parser engine to use. The C and pyarrow engines are faster, while the python engine is currently more feature-complete. Multithreading is currently only supported by the pyarrow engine.
New in version 1.4.0: The “pyarrow” engine was added as an experimental engine, and some features are unsupported, or may not work correctly, with this engine.
converters (dict, optional) – Dict of functions for converting values in certain columns. Keys can either be integers or column labels.
true_values (list, optional) – Values to consider as True.
false_values (list, optional) – Values to consider as False.
skipinitialspace (bool, default False) – Skip spaces after delimiter.
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]
.skipfooter (int, default 0) – Number of lines at bottom of file to skip (Unsupported with engine=’c’).
nrows (int, optional) – Number of rows of file to read. Useful for reading pieces of large files.
na_values (scalar, str, list-like, or dict, optional) – 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’, ‘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.
skip_blank_lines (bool, default True) – If True, skip over blank lines rather than interpreting as NaN values.
parse_dates (bool or list of int or names or list of lists or dict, default False) –
The behavior is as follows:
boolean. 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 cannot be represented as an array of datetimes, say because of an unparsable value or a mixture of timezones, the column or index will be returned unaltered as an object data type. For non-standard datetime parsing, use
pd.to_datetime
afterpd.read_csv
. To parse an index or column with a mixture of timezones, specifydate_parser
to be a partially-appliedpandas.to_datetime()
withutc=True
. See io.csv.mixed_timezones for more.Note: A fast-path exists for iso8601-formatted dates.
infer_datetime_format (bool, default False) – If True and parse_dates is enabled, pandas will attempt to infer the format of the datetime strings in the columns, and if it can be inferred, switch to a faster method of parsing them. In some cases this can increase the parsing speed by 5-10x.
keep_date_col (bool, default False) – If True and parse_dates specifies combining multiple columns then keep the original columns.
date_parser (function, optional) – Function to use for converting a sequence of string columns to an array of datetime instances. The default uses
dateutil.parser.parser
to do the conversion. Pandas will try to call date_parser in three different ways, advancing to the next if an exception occurs: 1) Pass one or more arrays (as defined by parse_dates) as arguments; 2) concatenate (row-wise) the string values from the columns defined by parse_dates into a single array and pass that; and 3) call date_parser once for each row using one or more strings (corresponding to the columns defined by parse_dates) as arguments.dayfirst (bool, default False) – DD/MM format dates, international and European format.
cache_dates (bool, default True) –
If True, use a cache of unique, converted dates to apply the datetime conversion. May produce significant speed-up when parsing duplicate date strings, especially ones with timezone offsets.
New in version 0.25.0.
iterator (bool, default False) –
Return TextFileReader object for iteration or getting chunks with
get_chunk()
.Changed in version 1.2:
TextFileReader
is a context manager.chunksize (int, optional) –
Return TextFileReader object for iteration. See the IO Tools docs for more information on
iterator
andchunksize
.Changed in version 1.2:
TextFileReader
is a context manager.compression (str or dict, default 'infer') –
For on-the-fly decompression of on-disk data. If ‘infer’ and ‘%s’ is path-like, then detect compression from the following extensions: ‘.gz’, ‘.bz2’, ‘.zip’, ‘.xz’, or ‘.zst’ (otherwise no compression). If using ‘zip’, the ZIP file must contain only one data file to be read in. Set to
None
for no decompression. Can also be a dict with key'method'
set to one of {'zip'
,'gzip'
,'bz2'
,'zstd'
} and other key-value pairs are forwarded tozipfile.ZipFile
,gzip.GzipFile
,bz2.BZ2File
, orzstandard.ZstdDecompressor
, respectively. As an example, the following could be passed for Zstandard decompression using a custom compression dictionary:compression={'method': 'zstd', 'dict_data': my_compression_dict}
.Changed in version 1.4.0: Zstandard support.
thousands (str, optional) – Thousands separator.
decimal (str, default '.') – Character to recognize as decimal point (e.g. use ‘,’ for European data).
lineterminator (str (length 1), optional) – Character to break file into lines. Only valid with C parser.
quotechar (str (length 1), optional) – The character used to denote the start and end of a quoted item. Quoted items can include the delimiter and it will be ignored.
quoting (int or csv.QUOTE_* instance, default 0) – Control field quoting behavior per
csv.QUOTE_*
constants. Use one of QUOTE_MINIMAL (0), QUOTE_ALL (1), QUOTE_NONNUMERIC (2) or QUOTE_NONE (3).doublequote (bool, default
True
) – When quotechar is specified and quoting is notQUOTE_NONE
, indicate whether or not to interpret two consecutive quotechar elements INSIDE a field as a singlequotechar
element.escapechar (str (length 1), optional) – One-character string used to escape other characters.
comment (str, optional) – Indicates remainder of line should not be parsed. If found at the beginning of a line, the line will be ignored altogether. This parameter must be a single character. Like empty lines (as long as
skip_blank_lines=True
), fully commented lines are ignored by the parameter header but not by skiprows. For example, ifcomment='#'
, parsing#empty\na,b,c\n1,2,3
withheader=0
will result in ‘a,b,c’ being treated as the header.encoding (str, optional) –
Encoding to use for UTF when reading/writing (ex. ‘utf-8’). List of Python standard encodings .
Changed in version 1.2: When
encoding
isNone
,errors="replace"
is passed toopen()
. Otherwise,errors="strict"
is passed toopen()
. This behavior was previously only the case forengine="python"
.Changed in version 1.3.0:
encoding_errors
is a new argument.encoding
has no longer an influence on how encoding errors are handled.encoding_errors (str, optional, default "strict") –
How encoding errors are treated. List of possible values .
New in version 1.3.0.
dialect (str or csv.Dialect, optional) – If provided, this parameter will override values (default or not) for the following parameters: delimiter, doublequote, escapechar, skipinitialspace, quotechar, and quoting. If it is necessary to override values, a ParserWarning will be issued. See csv.Dialect documentation for more details.
error_bad_lines (bool, optional, default
None
) –Lines with too many fields (e.g. a csv line with too many commas) will by default cause an exception to be raised, and no DataFrame will be returned. If False, then these “bad lines” will be dropped from the DataFrame that is returned.
Deprecated since version 1.3.0: The
on_bad_lines
parameter should be used instead to specify behavior upon encountering a bad line instead.warn_bad_lines (bool, optional, default
None
) –If error_bad_lines is False, and warn_bad_lines is True, a warning for each “bad line” will be output.
Deprecated since version 1.3.0: The
on_bad_lines
parameter should be used instead to specify behavior upon encountering a bad line instead.on_bad_lines ({'error', 'warn', 'skip'} or callable, default 'error') –
Specifies what to do upon encountering a bad line (a line with too many fields). Allowed values are :
’error’, raise an Exception when a bad line is encountered.
’warn’, raise a warning when a bad line is encountered and skip that line.
’skip’, skip bad lines without raising or warning when they are encountered.
New in version 1.3.0:
callable, function with signature
(bad_line: list[str]) -> list[str] | None
that will process a single bad line.bad_line
is a list of strings split by thesep
. If the function returnsNone
, the bad line will be ignored. If the function returns a new list of strings with more elements than expected, aParserWarning
will be emitted while dropping extra elements. Only supported whenengine="python"
New in version 1.4.0.
delim_whitespace (bool, default False) – Specifies whether or not whitespace (e.g.
' '
or' '
) will be used as the sep. Equivalent to settingsep='\s+'
. If this option is set to True, nothing should be passed in for thedelimiter
parameter.low_memory (bool, default True) – Internally process the file in chunks, resulting in lower memory use while parsing, but possibly mixed type inference. To ensure no mixed types either set False, or specify the type with the dtype parameter. Note that the entire file is read into a single DataFrame regardless, use the chunksize or iterator parameter to return the data in chunks. (Only valid with C parser).
memory_map (bool, default False) – If a filepath is provided for filepath_or_buffer, map the file object directly onto memory and access the data directly from there. Using this option can improve performance because there is no longer any I/O overhead.
float_precision (str, optional) –
Specifies which converter the C engine should use for floating-point values. The options are
None
or ‘high’ for the ordinary converter, ‘legacy’ for the original lower precision pandas converter, and ‘round_trip’ for the round-trip converter.Changed in version 1.2.
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
as header options. For other URLs (e.g. starting with “s3://”, and “gcs://”) the key-value pairs are forwarded tofsspec
. Please seefsspec
andurllib
for more details.New in version 1.2.
- Returns
A comma-separated values (csv) file is returned as two-dimensional data structure with labeled axes.
- Return type
DataFrame or TextParser
See also
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
>>> pd.read_csv('data.csv')
- class modin.core.io.CSVGlobDispatcher¶
Class contains utils for reading multiple .csv files simultaneously.
- classmethod file_exists(file_path: str) bool ¶
Check if the file_path is valid.
- Parameters
file_path (str) – String representing a path.
- Returns
True if the path is valid.
- Return type
bool
- classmethod get_path(file_path: str) list ¶
Return the path of the file(s).
- Parameters
file_path (str) – String representing a path.
- Returns
List of strings of absolute file paths.
- Return type
list
- classmethod partitioned_file(files, fnames: List[str], num_partitions: Optional[int] = None, nrows: Optional[int] = None, skiprows: Optional[int] = None, skip_header: Optional[int] = None, quotechar: bytes = b'"', is_quoting: bool = True) List[List[Tuple[str, int, int]]] ¶
Compute chunk sizes in bytes for every partition.
- Parameters
files (file or list of files) – File(s) to be partitioned.
fnames (str or list of str) – File name(s) to be partitioned.
num_partitions (int, optional) – For what number of partitions split a file. If not specified grabs the value from modin.config.NPartitions.get().
nrows (int, optional) – Number of rows of file to read.
skiprows (int, optional) – Specifies rows to skip.
skip_header (int, optional) – Specifies header rows to skip.
quotechar (bytes, default: b'"') – Indicate quote in a file.
is_quoting (bool, default: True) – Whether or not to consider quotes.
- Returns
List, where each element of the list is a list of tuples. The inner lists of tuples contains the data file name of the chunk, chunk start offset, and chunk end offsets for its corresponding file.
- Return type
list
Notes
The logic gets really complicated if we try to use the TextFileDispatcher.partitioned_file.
- class modin.core.io.ExcelDispatcher¶
Class handles utils for reading excel files.
- class modin.core.io.FWFDispatcher¶
Class handles utils for reading of tables with fixed-width formatted lines.
- classmethod check_parameters_support(filepath_or_buffer, read_kwargs: dict)¶
Check support of parameters of read_fwf function.
- Parameters
filepath_or_buffer (str, path object or file-like object) – filepath_or_buffer parameter of read_fwf function.
read_kwargs (dict) – Parameters of read_fwf function.
- Returns
Whether passed parameters are supported or not.
- Return type
bool
- read_callback(colspecs: list[tuple[int, int]] | str | None = 'infer', widths: list[int] | None = None, infer_nrows: int = 100, **kwds) DataFrame | TextFileReader ¶
Read a table of fixed-width formatted lines into DataFrame.
Also supports optionally iterating or breaking of the file into chunks.
Additional help can be found in the online docs for IO Tools.
- Parameters
filepath_or_buffer (str, path object, or file-like object) – String, path object (implementing
os.PathLike[str]
), or file-like object implementing a textread()
function.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.csv
.colspecs (list of tuple (int, int) or 'infer'. optional) – A list of tuples giving the extents of the fixed-width fields of each line as half-open intervals (i.e., [from, to[ ). String value ‘infer’ can be used to instruct the parser to try detecting the column specifications from the first 100 rows of the data which are not being skipped via skiprows (default=’infer’).
widths (list of int, optional) – A list of field widths which can be used instead of ‘colspecs’ if the intervals are contiguous.
infer_nrows (int, default 100) – The number of rows to consider when letting the parser determine the colspecs.
**kwds (optional) – Optional keyword arguments can be passed to
TextFileReader
.
- Returns
A comma-separated values (csv) file is returned as two-dimensional data structure with labeled axes.
- Return type
DataFrame or TextFileReader
See also
DataFrame.to_csv
Write DataFrame to a comma-separated values (csv) file.
read_csv
Read a comma-separated values (csv) file into DataFrame.
Examples
>>> pd.read_fwf('data.csv')
- class modin.core.io.FeatherDispatcher¶
Class handles utils for reading .feather files.
- class modin.core.io.FileDispatcher¶
Class handles util functions for reading data from different kinds of files.
Notes
_read, deploy, parse and materialize are abstract methods and should be implemented in the child classes (functions signatures can differ between child classes).
- classmethod build_partition(partition_ids, row_lengths, column_widths)¶
Build array with partitions of cls.frame_partition_cls class.
- Parameters
partition_ids (list) – Array with references to the partitions data.
row_lengths (list) – Partitions rows lengths.
column_widths (list) – Number of columns in each partition.
- Returns
array with shape equals to the shape of partition_ids and filed with partition objects.
- Return type
np.ndarray
- classmethod deploy(func, args, num_returns)¶
Deploy remote task.
Should be implemented in the task class (for example in the RayTask).
- classmethod file_exists(file_path)¶
Check if file_path exists.
- Parameters
file_path (str) – String that represents the path to the file (paths to S3 buckets are also acceptable).
- Returns
Whether file exists or not.
- Return type
bool
- classmethod file_size(f)¶
Get the size of file associated with file handle f.
- Parameters
f (file-like object) – File-like object, that should be used to get file size.
- Returns
File size in bytes.
- Return type
int
- classmethod get_path(file_path)¶
Process file_path in accordance to it’s type.
- Parameters
file_path (str) – String that represents the path to the file (paths to S3 buckets are also acceptable).
- Returns
Updated or verified file_path parameter.
- Return type
str
Notes
if file_path is an S3 bucket, parameter will be returned as is, otherwise absolute path will be returned.
- classmethod materialize(obj_id)¶
Get results from worker.
Should be implemented in the task class (for example in the RayTask).
- parse(func, args, num_returns)¶
Parse file’s data in the worker process.
Should be implemented in the parser class (for example in the PandasCSVParser).
- classmethod read(*args, **kwargs)¶
Read data according passed args and kwargs.
- Parameters
*args (iterable) – Positional arguments to be passed into _read function.
**kwargs (dict) – Keywords arguments to be passed into _read function.
- Returns
query_compiler – Query compiler with imported data for further processing.
- Return type
Notes
read is high-level function that calls specific for defined storage format, engine and dispatcher class _read function with passed parameters and performs some postprocessing work on the resulting query_compiler object.
- class modin.core.io.HDFDispatcher¶
Class handles utils for reading hdf data.
Inherits some common for columnar store files util functions from ColumnStoreDispatcher class.
- class modin.core.io.JSONDispatcher¶
Class handles utils for reading .json files.
- class modin.core.io.ParquetDispatcher¶
Class handles utils for reading .parquet files.
- class modin.core.io.PickleExperimentalDispatcher¶
Class handles utils for reading pickle files.
- class modin.core.io.SQLDispatcher¶
Class handles utils for reading SQL queries or database tables.
- class modin.core.io.TextFileDispatcher¶
Class handles utils for reading text formats files.
- classmethod build_partition(partition_ids, row_lengths, column_widths)¶
Build array with partitions of cls.frame_partition_cls class.
- Parameters
partition_ids (list) – Array with references to the partitions data.
row_lengths (list) – Partitions rows lengths.
column_widths (list) – Number of columns in each partition.
- Returns
array with shape equals to the shape of partition_ids and filed with partitions objects.
- Return type
np.ndarray
- classmethod check_parameters_support(filepath_or_buffer, read_kwargs: dict) bool ¶
Check support of only general parameters of read_* function.
- Parameters
filepath_or_buffer (str, path object or file-like object) – filepath_or_buffer parameter of read_* function.
read_kwargs (dict) – Parameters of read_* function.
- Returns
Whether passed parameters are supported or not.
- Return type
bool
- classmethod compute_newline(file_like, encoding, quotechar)¶
Compute byte or sequence of bytes indicating line endings.
- Parameters
file_like (file-like object) – File handle that should be used for line endings computing.
encoding (str) – Encoding of file_like.
quotechar (str) – Quotechar used for parsing file-like.
- Returns
line endings
- Return type
bytes
- classmethod get_path_or_buffer(filepath_or_buffer)¶
Extract path from filepath_or_buffer.
- Parameters
filepath_or_buffer (str, path object or file-like object) – filepath_or_buffer parameter of read_csv function.
- Returns
verified filepath_or_buffer parameter.
- Return type
str or path object
Notes
Given a buffer, try and extract the filepath from it so that we can use it without having to fall back to pandas and share file objects between workers. Given a filepath, return it immediately.
- classmethod offset(f, offset_size: int, quotechar: bytes = b'"', is_quoting: bool = True, encoding: Optional[str] = None, newline: Optional[bytes] = None)¶
Move the file offset at the specified amount of bytes.
- Parameters
f (file-like object) – File handle that should be used for offset movement.
offset_size (int) – Number of bytes to read and ignore.
quotechar (bytes, default: b'"') – Indicate quote in a file.
is_quoting (bool, default: True) – Whether or not to consider quotes.
encoding (str, optional) – Encoding of f.
newline (bytes, optional) – Byte or sequence of bytes indicating line endings.
- Returns
If file pointer reached the end of the file, but did not find closing quote returns False. True in any other case.
- Return type
bool
- classmethod partitioned_file(f, num_partitions: Optional[int] = None, nrows: Optional[int] = None, skiprows: Optional[int] = None, quotechar: bytes = b'"', is_quoting: bool = True, encoding: Optional[str] = None, newline: Optional[bytes] = None, header_size: int = 0, pre_reading: int = 0)¶
Compute chunk sizes in bytes for every partition.
- Parameters
f (file-like object) – File handle of file to be partitioned.
num_partitions (int, optional) – For what number of partitions split a file. If not specified grabs the value from modin.config.NPartitions.get().
nrows (int, optional) – Number of rows of file to read.
skiprows (int, optional) – Specifies rows to skip.
quotechar (bytes, default: b'"') – Indicate quote in a file.
is_quoting (bool, default: True) – Whether or not to consider quotes.
encoding (str, optional) – Encoding of f.
newline (bytes, optional) – Byte or sequence of bytes indicating line endings.
header_size (int, default: 0) – Number of rows, that occupied by header.
pre_reading (int, default: 0) – Number of rows between header and skipped rows, that should be read.
- Returns
- List with the next elements:
int : partition start read byte int : partition end read byte
- Return type
list
- classmethod pathlib_or_pypath(filepath_or_buffer)¶
Check if filepath_or_buffer is instance of py.path.local or pathlib.Path.
- Parameters
filepath_or_buffer (str, path object or file-like object) – filepath_or_buffer parameter of read_csv function.
- Returns
Whether or not filepath_or_buffer is instance of py.path.local or pathlib.Path.
- Return type
bool
- classmethod rows_skipper_builder(f, quotechar, is_quoting, encoding=None, newline=None)¶
Build object for skipping passed number of lines.
- Parameters
f (file-like object) – File handle that should be used for offset movement.
quotechar (bytes) – Indicate quote in a file.
is_quoting (bool) – Whether or not to consider quotes.
encoding (str, optional) – Encoding of f.
newline (bytes, optional) – Byte or sequence of bytes indicating line endings.
- Returns
skipper object.
- Return type
object
Handling skiprows
Parameter¶
Handling skiprows
parameter by pandas import functions can be very tricky, especially
for read_csv
function because of interconnection with header
parameter. In this section
the techniques of skiprows
processing by both pandas and Modin are covered.
Processing skiprows
by pandas¶
Let’s consider a simple snippet with pandas.read_csv
in order to understand interconnection
of header
and skiprows
parameters:
import pandas
from io import StringIO
data = """0
1
2
3
4
5
6
7
8
"""
# `header` parameter absence is equivalent to `header="infer"` or `header=0`
# rows 1, 5, 6, 7, 8 are read with header "0"
df = pandas.read_csv(StringIO(data), skiprows=[2, 3, 4])
# rows 5, 6, 7, 8 are read with header "1", row 0 is skipped additionally
df = pandas.read_csv(StringIO(data), skiprows=[2, 3, 4], header=1)
# rows 6, 7, 8 are read with header "5", rows 0, 1 are skipped additionally
df = pandas.read_csv(StringIO(data), skiprows=[2, 3, 4], header=2)
In the examples above list-like skiprows
values are fixed and header
is varied. In the first
example with no header
provided, rows 2, 3, 4 are skipped and row 0 is considered as a header.
In the second example header == 1
, so 0th row is skipped and the next available row is
considered as a header. The third example shows the case when header
and skiprows
parameters
values are intersected - in this case skipped rows are dropped first and only then header
is got
from the remaining rows (rows before header are skipped too).
In the examples above only list-like skiprows
and integer header
parameters are considered,
but the same logic is applicable for other types of the parameters.
Processing skiprows
by Modin¶
As it can be seen, skipping rows in the pandas import functions is complicated and distributing this logic across multiple workers can complicate it even more. Thus in some rare corner cases default pandas implementation is used in Modin to avoid excessive Modin code complication.
Modin uses two techniques for skipping rows:
1) During file partitioning (setting file limits that should be read by each partition)
exact rows can be excluded from partitioning scope, thus they won’t be read at all and can be
considered as skipped. This is the most effective way of skipping rows since it doesn’t require
any actual data reading and postprocessing, but in this case skiprows
parameter can be an
integer only. When it is possible Modin always uses this approach.
2) Rows for skipping can be dropped after full dataset import. This is more expensive way since
it requires extra IO work and postprocessing afterwards, but skiprows
parameter can be of any
non-integer type supported by pandas.read_csv
.
In some cases, if skiprows
is uniformly distributed array (e.g. [1, 2, 3]), skiprows
can be
“squashed” and represented as an integer to make a fastpath by skipping these rows during file partitioning
(using the first option). But if there is a gap between the first row for skipping
and the last line of the header (that will be skipped too since header is read by each partition
to ensure metadata is defined properly), then this gap should be assigned for reading first
by assigning the first partition to read these rows by setting pre_reading
parameter.
Let’s consider an example of skipping rows during partitioning when header="infer"
and
skiprows=[3, 4, 5]
. In this specific case fastpath can be done since skiprows
is uniformly
distributed array, so we can “squash” it to an integer and set “partitioning” skiprows to 3. But
if no additional action is done, these three rows will be skipped right after header line,
that corresponds to skiprows=[1, 2, 3]
. To avoid this discrepancy, we need to assign the first
partition to read data between header line and the first row for skipping by setting special
pre_reading
parameter to 2. Then, after the skipping of rows considered to be skipped during
partitioning, the rest data will be divided between the rest of partitions, see rows assignment
below:
0 - header line (skip during partitioning)
1 - pre reading (assign to read by the first partition)
2 - pre reading (assign to read by the first partition)
3 - "partitioning" skiprows (skip during partitioning)
4 - "partitioning" skiprows (skip during partitioning)
5 - "partitioning" skiprows (skip during partitioning)
6 - data to partition (divide between the rest of partitions)
7 - data to partition (divide between the rest of partitions)