apache_beam.dataframe.io module

Sources and sinks for the Beam DataFrame API.

Sources

This module provides analogs for pandas read methods, like pandas.read_csv(). However Beam sources like read_csv() create a Beam PTransform, and return a DeferredDataFrame or DeferredSeries representing the contents of the referenced file(s) or data source.

The result of these methods must be applied to a Pipeline object, for example:

df = p | beam.dataframe.io.read_csv(...)

Sinks

This module also defines analogs for pandas sink, or to, methods that generate a Beam PTransform. Users should prefer calling these operations from DeferredDataFrame instances (for example with DeferredDataFrame.to_csv).

apache_beam.dataframe.io.read_csv(path, *args, splittable=False, **kwargs)[source]

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 builtin open function) or StringIO.

  • 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, default 'infer') – Row number(s) to use as the column names, and the start of the data. Default behavior is to infer the column names: if no names are passed the behavior is identical to header=0 and column names are inferred from the first line of the file, if column names are passed explicitly then the behavior is identical to header=None. Explicitly pass header=0 to be able to replace existing names. The header can be a list of 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 if skip_blank_lines=True, so header=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, default None) –

    Column(s) to use as the row labels of the DeferredDataFrame, 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). For example, a valid list-like usecols parameter would be [0, 1, 2] or ['foo', 'bar', 'baz']. Element order is ignored, so usecols=[0, 1] is the same as [1, 0]. To instantiate a DeferredDataFrame from data with element order preserved use pd.read_csv(data, usecols=['foo', 'bar'])[['foo', 'bar']] for columns in ['foo', 'bar'] order or pd.read_csv(data, usecols=['foo', 'bar'])[['bar', 'foo']] for ['bar', 'foo'] order.

    If callable, the callable function will be evaluated against the column names, returning names where the callable function evaluates to True. 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 DeferredSeries.
  • prefix (str, optional) – Prefix to add to column numbers when no header, e.g. ‘X’ for X0, X1, …
  • 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'}, optional) – Parser engine to use. The C engine is faster while the python engine is currently more feature-complete.
  • 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 after pd.read_csv. To parse an index or column with a mixture of timezones, specify date_parser to be a partially-applied pandas.to_datetime() with utc=True. See Parsing a CSV with 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 and chunksize.

    Changed in version 1.2: TextFileReader is a context manager.

  • compression ({'infer', 'gzip', 'bz2', 'zip', 'xz', None}, default 'infer') – For on-the-fly decompression of on-disk data. If ‘infer’ and filepath_or_buffer is path-like, then detect compression from the following extensions: ‘.gz’, ‘.bz2’, ‘.zip’, or ‘.xz’ (otherwise no decompression). If using ‘zip’, the ZIP file must contain only one data file to be read in. Set to None for no decompression.
  • 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 not QUOTE_NONE, indicate whether or not to interpret two consecutive quotechar elements INSIDE a field as a single quotechar 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, if comment='#', parsing #empty\na,b,c\n1,2,3 with header=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 . .. versionchanged:: 1.2

    When encoding is None, errors="replace" is passed to open(). Otherwise, errors="strict" is passed to open(). This behavior was previously only the case for engine="python".
  • 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, default True) – Lines with too many fields (e.g. a csv line with too many commas) will by default cause an exception to be raised, and no DeferredDataFrame will be returned. If False, then these “bad lines” will dropped from the DeferredDataFrame that is returned.
  • warn_bad_lines (bool, default True) – If error_bad_lines is False, and warn_bad_lines is True, a warning for each “bad line” will be output.
  • delim_whitespace (bool, default False) – Specifies whether or not whitespace (e.g. ' ' or '    ') will be used as the sep. Equivalent to setting sep='\s+'. If this option is set to True, nothing should be passed in for the delimiter 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 DeferredDataFrame 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., if using a URL that will be parsed by fsspec, e.g., starting “s3://”, “gcs://”. An error will be raised if providing this argument with a non-fsspec URL. See the fsspec and backend storage implementation docs for the set of allowed keys and values.

    New in version 1.2.

Returns:

A comma-separated values (csv) file is returned as two-dimensional data structure with labeled axes.

Return type:

DeferredDataFrame or TextParser

Differences from pandas

If your files are large and records do not contain quoted newlines, you may pass the extra argument splittable=True to enable dynamic splitting for this read on newlines. Using this option for records that do contain quoted newlines may result in partial records and data corruption.

See also

DeferredDataFrame.to_csv()
Write DeferredDataFrame to a comma-separated values (csv) file.
read_csv()
Read a comma-separated values (csv) file into DeferredDataFrame.
read_fwf()
Read a table of fixed-width formatted lines into DeferredDataFrame.

Examples

NOTE: These examples are pulled directly from the pandas documentation for convenience. Usage of the Beam DataFrame API will look different because it is a deferred API. In addition, some arguments shown here may not be supported, see ‘Differences from pandas’ for details.

>>> pd.read_csv('data.csv')  
apache_beam.dataframe.io.to_csv(df, path, *args, **kwargs)[source]

Write object to a comma-separated values (csv) file.

Changed in version 0.24.0: The order of arguments for Series was changed.

Parameters:
  • path_or_buf (str or file handle, default None) –

    File path or object, if None is provided the result is returned as a string. If a non-binary file object is passed, it should be opened with newline=’’, disabling universal newlines. If a binary file object is passed, mode might need to contain a ‘b’.

    Changed in version 0.24.0: Was previously named “path” for DeferredSeries.

    Changed in version 1.2.0: Support for binary file objects was introduced.

  • sep (str, default ',') – String of length 1. Field delimiter for the output file.
  • na_rep (str, default '') – Missing data representation.
  • float_format (str, default None) – Format string for floating point numbers.
  • columns (sequence, optional) – Columns to write.
  • header (bool or list of str, default True) –

    Write out the column names. If a list of strings is given it is assumed to be aliases for the column names.

    Changed in version 0.24.0: Previously defaulted to False for DeferredSeries.

  • index (bool, default True) – Write row names (index).
  • index_label (str or sequence, or False, 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 object uses MultiIndex. If False do not print fields for index names. Use index_label=False for easier importing in R.
  • mode (str) – Python write mode, default ‘w’.
  • encoding (str, optional) – A string representing the encoding to use in the output file, defaults to ‘utf-8’. encoding is not supported if path_or_buf is a non-binary file object.
  • compression (str or dict, default 'infer') –

    If str, represents compression mode. If dict, value at ‘method’ is the compression mode. Compression mode may be any of the following possible values: {‘infer’, ‘gzip’, ‘bz2’, ‘zip’, ‘xz’, None}. If compression mode is ‘infer’ and path_or_buf is path-like, then detect compression mode from the following extensions: ‘.gz’, ‘.bz2’, ‘.zip’ or ‘.xz’. (otherwise no compression). If dict given and mode is one of {‘zip’, ‘gzip’, ‘bz2’}, or inferred as one of the above, other entries passed as additional compression options.

    Changed in version 1.0.0: May now be a dict with key ‘method’ as compression mode and other entries as additional compression options if compression mode is ‘zip’.

    Changed in version 1.1.0: Passing compression options as keys in dict is supported for compression modes ‘gzip’ and ‘bz2’ as well as ‘zip’.

    Changed in version 1.2.0: Compression is supported for binary file objects.

    Changed in version 1.2.0: Previous versions forwarded dict entries for ‘gzip’ to gzip.open instead of gzip.GzipFile which prevented setting mtime.

  • quoting (optional constant from csv module) – Defaults to csv.QUOTE_MINIMAL. If you have set a float_format then floats are converted to strings and thus csv.QUOTE_NONNUMERIC will treat them as non-numeric.
  • quotechar (str, default '"') – String of length 1. Character used to quote fields.
  • line_terminator (str, optional) –

    The newline character or character sequence to use in the output file. Defaults to os.linesep, which depends on the OS in which this method is called (‘n’ for linux, ‘rn’ for Windows, i.e.).

    Changed in version 0.24.0.

  • chunksize (int or None) – Rows to write at a time.
  • date_format (str, default None) – Format string for datetime objects.
  • doublequote (bool, default True) – Control quoting of quotechar inside a field.
  • escapechar (str, default None) – String of length 1. Character used to escape sep and quotechar when appropriate.
  • decimal (str, default '.') – Character recognized as decimal separator. E.g. use ‘,’ for European data.
  • errors (str, default 'strict') –

    Specifies how encoding and decoding errors are to be handled. See the errors argument for open() for a full list of options.

    New in version 1.1.0.

  • storage_options (dict, optional) –

    Extra options that make sense for a particular storage connection, e.g. host, port, username, password, etc., if using a URL that will be parsed by fsspec, e.g., starting “s3://”, “gcs://”. An error will be raised if providing this argument with a non-fsspec URL. See the fsspec and backend storage implementation docs for the set of allowed keys and values.

    New in version 1.2.0.

Returns:

If path_or_buf is None, returns the resulting csv format as a string. Otherwise returns None.

Return type:

None or str

Differences from pandas

This operation has no known divergences from the pandas API.

See also

read_csv()
Load a CSV file into a DeferredDataFrame.
to_excel()
Write DeferredDataFrame to an Excel file.

Examples

NOTE: These examples are pulled directly from the pandas documentation for convenience. Usage of the Beam DataFrame API will look different because it is a deferred API.

>>> df = pd.DataFrame({'name': ['Raphael', 'Donatello'],
...                    'mask': ['red', 'purple'],
...                    'weapon': ['sai', 'bo staff']})
>>> df.to_csv(index=False)
'name,mask,weapon\nRaphael,red,sai\nDonatello,purple,bo staff\n'

Create 'out.zip' containing 'out.csv'

>>> compression_opts = dict(method='zip',
...                         archive_name='out.csv')  
>>> df.to_csv('out.zip', index=False,
...           compression=compression_opts)  
apache_beam.dataframe.io.read_fwf(path, *args, **kwargs)[source]

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) –

    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.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 builtin open function) or StringIO.

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

    New in version 0.24.0.

  • **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:

DeferredDataFrame or TextParser

Differences from pandas

This operation has no known divergences from the pandas API.

See also

DeferredDataFrame.to_csv()
Write DeferredDataFrame to a comma-separated values (csv) file.
read_csv()
Read a comma-separated values (csv) file into DeferredDataFrame.

Examples

NOTE: These examples are pulled directly from the pandas documentation for convenience. Usage of the Beam DataFrame API will look different because it is a deferred API.

>>> pd.read_fwf('data.csv')  
apache_beam.dataframe.io.read_json(path, *args, **kwargs)[source]

Convert a JSON string to pandas object.

Parameters:
  • path_or_buf (a valid JSON 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, and file. For file URLs, a host is expected. A local file could be: file://localhost/path/to/table.json.

    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.

  • orient (str) –

    Indication of expected JSON string format. Compatible JSON strings can be produced by to_json() with a corresponding orient value. The set of possible orients is:

    • 'split' : dict like {index -> [index], columns -> [columns], data -> [values]}
    • 'records' : list like [{column -> value}, ... , {column -> value}]
    • 'index' : dict like {index -> {column -> value}}
    • 'columns' : dict like {column -> {index -> value}}
    • 'values' : just the values array

    The allowed and default values depend on the value of the typ parameter.

    • when typ == 'series',
      • allowed orients are {'split','records','index'}
      • default is 'index'
      • The DeferredSeries index must be unique for orient 'index'.
    • when typ == 'frame',
      • allowed orients are {'split','records','index', 'columns','values', 'table'}
      • default is 'columns'
      • The DeferredDataFrame index must be unique for orients 'index' and 'columns'.
      • The DeferredDataFrame columns must be unique for orients 'index', 'columns', and 'records'.
  • typ ({'frame', 'series'}, default 'frame') – The type of object to recover.
  • dtype (bool or dict, default None) –

    If True, infer dtypes; if a dict of column to dtype, then use those; if False, then don’t infer dtypes at all, applies only to the data.

    For all orient values except 'table', default is True.

    Changed in version 0.25.0: Not applicable for orient='table'.

  • convert_axes (bool, default None) –

    Try to convert the axes to the proper dtypes.

    For all orient values except 'table', default is True.

    Changed in version 0.25.0: Not applicable for orient='table'.

  • convert_dates (bool or list of str, default True) – If True then default datelike columns may be converted (depending on keep_default_dates). If False, no dates will be converted. If a list of column names, then those columns will be converted and default datelike columns may also be converted (depending on keep_default_dates).
  • keep_default_dates (bool, default True) –

    If parsing dates (convert_dates is not False), then try to parse the default datelike columns. A column label is datelike if

    • it ends with '_at',
    • it ends with '_time',
    • it begins with 'timestamp',
    • it is 'modified', or
    • it is 'date'.
  • numpy (bool, default False) –

    Direct decoding to numpy arrays. Supports numeric data only, but non-numeric column and index labels are supported. Note also that the JSON ordering MUST be the same for each term if numpy=True.

    Deprecated since version 1.0.0.

  • precise_float (bool, default False) – Set to enable usage of higher precision (strtod) function when decoding string to double values. Default (False) is to use fast but less precise builtin functionality.
  • date_unit (str, default None) – The timestamp unit to detect if converting dates. The default behaviour is to try and detect the correct precision, but if this is not desired then pass one of ‘s’, ‘ms’, ‘us’ or ‘ns’ to force parsing only seconds, milliseconds, microseconds or nanoseconds respectively.
  • encoding (str, default is 'utf-8') – The encoding to use to decode py3 bytes.
  • lines (bool, default False) – Read the file as a json object per line.
  • chunksize (int, optional) –

    Return JsonReader object for iteration. See the line-delimited json docs for more information on chunksize. This can only be passed if lines=True. If this is None, the file will be read into memory all at once.

    Changed in version 1.2: JsonReader is a context manager.

  • compression ({'infer', 'gzip', 'bz2', 'zip', 'xz', None}, default 'infer') – For on-the-fly decompression of on-disk data. If ‘infer’, then use gzip, bz2, zip or xz if path_or_buf is a string ending in ‘.gz’, ‘.bz2’, ‘.zip’, or ‘xz’, respectively, and no decompression otherwise. If using ‘zip’, the ZIP file must contain only one data file to be read in. Set to None for no decompression.
  • nrows (int, optional) –

    The number of lines from the line-delimited jsonfile that has to be read. This can only be passed if lines=True. If this is None, all the rows will be returned.

    New in version 1.1.

  • storage_options (dict, optional) –

    Extra options that make sense for a particular storage connection, e.g. host, port, username, password, etc., if using a URL that will be parsed by fsspec, e.g., starting “s3://”, “gcs://”. An error will be raised if providing this argument with a non-fsspec URL. See the fsspec and backend storage implementation docs for the set of allowed keys and values.

    New in version 1.2.0.

Returns:

The type returned depends on the value of typ.

Return type:

DeferredSeries or DeferredDataFrame

Differences from pandas

This operation has no known divergences from the pandas API.

See also

DeferredDataFrame.to_json()
Convert a DeferredDataFrame to a JSON string.
DeferredSeries.to_json()
Convert a DeferredSeries to a JSON string.

Notes

Specific to orient='table', if a DeferredDataFrame with a literal Index name of index gets written with to_json(), the subsequent read operation will incorrectly set the Index name to None. This is because index is also used by DeferredDataFrame.to_json() to denote a missing Index name, and the subsequent read_json() operation cannot distinguish between the two. The same limitation is encountered with a MultiIndex and any names beginning with 'level_'.

Examples

NOTE: These examples are pulled directly from the pandas documentation for convenience. Usage of the Beam DataFrame API will look different because it is a deferred API.

>>> df = pd.DataFrame([['a', 'b'], ['c', 'd']],
...                   index=['row 1', 'row 2'],
...                   columns=['col 1', 'col 2'])

Encoding/decoding a Dataframe using ``'split'`` formatted JSON:

>>> df.to_json(orient='split')
'{"columns":["col 1","col 2"],
  "index":["row 1","row 2"],
  "data":[["a","b"],["c","d"]]}'
>>> pd.read_json(_, orient='split')
      col 1 col 2
row 1     a     b
row 2     c     d

Encoding/decoding a Dataframe using ``'index'`` formatted JSON:

>>> df.to_json(orient='index')
'{"row 1":{"col 1":"a","col 2":"b"},"row 2":{"col 1":"c","col 2":"d"}}'
>>> pd.read_json(_, orient='index')
      col 1 col 2
row 1     a     b
row 2     c     d

Encoding/decoding a Dataframe using ``'records'`` formatted JSON.
Note that index labels are not preserved with this encoding.

>>> df.to_json(orient='records')
'[{"col 1":"a","col 2":"b"},{"col 1":"c","col 2":"d"}]'
>>> pd.read_json(_, orient='records')
  col 1 col 2
0     a     b
1     c     d

Encoding with Table Schema

>>> df.to_json(orient='table')
'{"schema": {"fields": [{"name": "index", "type": "string"},
                        {"name": "col 1", "type": "string"},
                        {"name": "col 2", "type": "string"}],
                "primaryKey": "index",
                "pandas_version": "0.20.0"},
    "data": [{"index": "row 1", "col 1": "a", "col 2": "b"},
            {"index": "row 2", "col 1": "c", "col 2": "d"}]}'
apache_beam.dataframe.io.to_json(df, path, orient=None, *args, **kwargs)[source]

Convert the object to a JSON string.

Note NaN’s and None will be converted to null and datetime objects will be converted to UNIX timestamps.

Parameters:
  • path_or_buf (str or file handle, optional) – File path or object. If not specified, the result is returned as a string.
  • orient (str) –

    Indication of expected JSON string format.

    • DeferredSeries:
      • default is ‘index’
      • allowed values are: {‘split’, ‘records’, ‘index’, ‘table’}.
    • DeferredDataFrame:
      • default is ‘columns’
      • allowed values are: {‘split’, ‘records’, ‘index’, ‘columns’, ‘values’, ‘table’}.
    • The format of the JSON string:
      • ’split’ : dict like {‘index’ -> [index], ‘columns’ -> [columns], ‘data’ -> [values]}
      • ’records’ : list like [{column -> value}, … , {column -> value}]
      • ’index’ : dict like {index -> {column -> value}}
      • ’columns’ : dict like {column -> {index -> value}}
      • ’values’ : just the values array
      • ’table’ : dict like {‘schema’: {schema}, ‘data’: {data}}

      Describing the data, where data component is like orient='records'.

  • date_format ({None, 'epoch', 'iso'}) – Type of date conversion. ‘epoch’ = epoch milliseconds, ‘iso’ = ISO8601. The default depends on the orient. For orient='table', the default is ‘iso’. For all other orients, the default is ‘epoch’.
  • double_precision (int, default 10) – The number of decimal places to use when encoding floating point values.
  • force_ascii (bool, default True) – Force encoded string to be ASCII.
  • date_unit (str, default 'ms' (milliseconds)) – The time unit to encode to, governs timestamp and ISO8601 precision. One of ‘s’, ‘ms’, ‘us’, ‘ns’ for second, millisecond, microsecond, and nanosecond respectively.
  • default_handler (callable, default None) – Handler to call if object cannot otherwise be converted to a suitable format for JSON. Should receive a single argument which is the object to convert and return a serialisable object.
  • lines (bool, default False) – If ‘orient’ is ‘records’ write out line delimited json format. Will throw ValueError if incorrect ‘orient’ since others are not list like.
  • compression ({'infer', 'gzip', 'bz2', 'zip', 'xz', None}) –

    A string representing the compression to use in the output file, only used when the first argument is a filename. By default, the compression is inferred from the filename.

    Changed in version 0.24.0: ‘infer’ option added and set to default

  • index (bool, default True) – Whether to include the index values in the JSON string. Not including the index (index=False) is only supported when orient is ‘split’ or ‘table’.
  • indent (int, optional) –

    Length of whitespace used to indent each record.

    New in version 1.0.0.

  • storage_options (dict, optional) –

    Extra options that make sense for a particular storage connection, e.g. host, port, username, password, etc., if using a URL that will be parsed by fsspec, e.g., starting “s3://”, “gcs://”. An error will be raised if providing this argument with a non-fsspec URL. See the fsspec and backend storage implementation docs for the set of allowed keys and values.

    New in version 1.2.0.

Returns:

If path_or_buf is None, returns the resulting json format as a string. Otherwise returns None.

Return type:

None or str

Differences from pandas

This operation has no known divergences from the pandas API.

See also

read_json()
Convert a JSON string to pandas object.

Notes

The behavior of indent=0 varies from the stdlib, which does not indent the output but does insert newlines. Currently, indent=0 and the default indent=None are equivalent in pandas, though this may change in a future release.

orient='table' contains a ‘pandas_version’ field under ‘schema’. This stores the version of pandas used in the latest revision of the schema.

Examples

NOTE: These examples are pulled directly from the pandas documentation for convenience. Usage of the Beam DataFrame API will look different because it is a deferred API.

>>> import json
>>> df = pd.DataFrame(
...     [["a", "b"], ["c", "d"]],
...     index=["row 1", "row 2"],
...     columns=["col 1", "col 2"],
... )

>>> result = df.to_json(orient="split")
>>> parsed = json.loads(result)
>>> json.dumps(parsed, indent=4)  
{
    "columns": [
        "col 1",
        "col 2"
    ],
    "index": [
        "row 1",
        "row 2"
    ],
    "data": [
        [
            "a",
            "b"
        ],
        [
            "c",
            "d"
        ]
    ]
}

Encoding/decoding a Dataframe using ``'records'`` formatted JSON.
Note that index labels are not preserved with this encoding.

>>> result = df.to_json(orient="records")
>>> parsed = json.loads(result)
>>> json.dumps(parsed, indent=4)  
[
    {
        "col 1": "a",
        "col 2": "b"
    },
    {
        "col 1": "c",
        "col 2": "d"
    }
]

Encoding/decoding a Dataframe using ``'index'`` formatted JSON:

>>> result = df.to_json(orient="index")
>>> parsed = json.loads(result)
>>> json.dumps(parsed, indent=4)  
{
    "row 1": {
        "col 1": "a",
        "col 2": "b"
    },
    "row 2": {
        "col 1": "c",
        "col 2": "d"
    }
}

Encoding/decoding a Dataframe using ``'columns'`` formatted JSON:

>>> result = df.to_json(orient="columns")
>>> parsed = json.loads(result)
>>> json.dumps(parsed, indent=4)  
{
    "col 1": {
        "row 1": "a",
        "row 2": "c"
    },
    "col 2": {
        "row 1": "b",
        "row 2": "d"
    }
}

Encoding/decoding a Dataframe using ``'values'`` formatted JSON:

>>> result = df.to_json(orient="values")
>>> parsed = json.loads(result)
>>> json.dumps(parsed, indent=4)  
[
    [
        "a",
        "b"
    ],
    [
        "c",
        "d"
    ]
]

Encoding with Table Schema:

>>> result = df.to_json(orient="table")
>>> parsed = json.loads(result)
>>> json.dumps(parsed, indent=4)  
{
    "schema": {
        "fields": [
            {
                "name": "index",
                "type": "string"
            },
            {
                "name": "col 1",
                "type": "string"
            },
            {
                "name": "col 2",
                "type": "string"
            }
        ],
        "primaryKey": [
            "index"
        ],
        "pandas_version": "0.20.0"
    },
    "data": [
        {
            "index": "row 1",
            "col 1": "a",
            "col 2": "b"
        },
        {
            "index": "row 2",
            "col 1": "c",
            "col 2": "d"
        }
    ]
}
apache_beam.dataframe.io.read_html(path, *args, **kwargs)[source]

Read HTML tables into a list of DataFrame objects.

Parameters:
  • io (str, path object or file-like object) – A URL, a file-like object, or a raw string containing HTML. Note that lxml only accepts the http, ftp and file url protocols. If you have a URL that starts with 'https' you might try removing the 's'.
  • match (str or compiled regular expression, optional) – The set of tables containing text matching this regex or string will be returned. Unless the HTML is extremely simple you will probably need to pass a non-empty string here. Defaults to ‘.+’ (match any non-empty string). The default value will return all tables contained on a page. This value is converted to a regular expression so that there is consistent behavior between Beautiful Soup and lxml.
  • flavor (str, optional) – The parsing engine to use. ‘bs4’ and ‘html5lib’ are synonymous with each other, they are both there for backwards compatibility. The default of None tries to use lxml to parse and if that fails it falls back on bs4 + html5lib.
  • header (int or list-like, optional) – The row (or list of rows for a MultiIndex) to use to make the columns headers.
  • index_col (int or list-like, optional) – The column (or list of columns) to use to create the index.
  • skiprows (int, list-like or slice, optional) – Number of rows to skip after parsing the column integer. 0-based. If a sequence of integers or a slice is given, will skip the rows indexed by that sequence. Note that a single element sequence means ‘skip the nth row’ whereas an integer means ‘skip n rows’.
  • attrs (dict, optional) –

    This is a dictionary of attributes that you can pass to use to identify the table in the HTML. These are not checked for validity before being passed to lxml or Beautiful Soup. However, these attributes must be valid HTML table attributes to work correctly. For example,

    attrs = {'id': 'table'}
    

    is a valid attribute dictionary because the ‘id’ HTML tag attribute is a valid HTML attribute for any HTML tag as per this document.

    attrs = {'asdf': 'table'}
    

    is not a valid attribute dictionary because ‘asdf’ is not a valid HTML attribute even if it is a valid XML attribute. Valid HTML 4.01 table attributes can be found here. A working draft of the HTML 5 spec can be found here. It contains the latest information on table attributes for the modern web.

  • parse_dates (bool, optional) – See read_csv() for more details.
  • thousands (str, optional) – Separator to use to parse thousands. Defaults to ','.
  • encoding (str, optional) – The encoding used to decode the web page. Defaults to None.``None`` preserves the previous encoding behavior, which depends on the underlying parser library (e.g., the parser library will try to use the encoding provided by the document).
  • decimal (str, default '.') – Character to recognize as decimal point (e.g. use ‘,’ for European data).
  • 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 cell (not column) content, and return the transformed content.
  • na_values (iterable, default None) – Custom NA values.
  • keep_default_na (bool, default True) – If na_values are specified and keep_default_na is False the default NaN values are overridden, otherwise they’re appended to.
  • displayed_only (bool, default True) – Whether elements with “display: none” should be parsed.
Returns:

A list of DeferredDataFrames.

Return type:

dfs

Differences from pandas

This operation has no known divergences from the pandas API.

See also

read_csv()
Read a comma-separated values (csv) file into DeferredDataFrame.

Notes

Before using this function you should read the gotchas about the HTML parsing libraries.

Expect to do some cleanup after you call this function. For example, you might need to manually assign column names if the column names are converted to NaN when you pass the header=0 argument. We try to assume as little as possible about the structure of the table and push the idiosyncrasies of the HTML contained in the table to the user.

This function searches for <table> elements and only for <tr> and <th> rows and <td> elements within each <tr> or <th> element in the table. <td> stands for “table data”. This function attempts to properly handle colspan and rowspan attributes. If the function has a <thead> argument, it is used to construct the header, otherwise the function attempts to find the header within the body (by putting rows with only <th> elements into the header).

Similar to read_csv() the header argument is applied after skiprows is applied.

This function will always return a list of DeferredDataFrame or it will fail, e.g., it will not return an empty list.

Examples

NOTE: These examples are pulled directly from the pandas documentation for convenience. Usage of the Beam DataFrame API will look different because it is a deferred API.

See the :ref:`read_html documentation in the IO section of the docs
<io.read_html>` for some examples of reading in HTML tables.
apache_beam.dataframe.io.to_html(df, path, *args, **kwargs)[source]

Render a DataFrame as an HTML table.

Parameters:
  • buf (str, Path or StringIO-like, optional, default None) – Buffer to write to. If None, the output is returned as a string.
  • columns (sequence, optional, default None) – The subset of columns to write. Writes all columns by default.
  • col_space (str or int, list or dict of int or str, optional) –

    The minimum width of each column in CSS length units. An int is assumed to be px units.

    New in version 0.25.0: Ability to use str.

  • header (bool, optional) – Whether to print column labels, default True.
  • 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.

    Changed in version 1.2.0.

  • sparsify (bool, optional, default True) – Set to False for a DeferredDataFrame 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.
  • min_rows (int, optional) – The number of rows to display in the console in a truncated repr (when number of rows is above max_rows).
  • max_cols (int, optional) – Maximum number of columns to display in the console.
  • show_dimensions (bool, default False) – Display DeferredDataFrame dimensions (number of rows by number of columns).
  • decimal (str, default '.') – Character recognized as decimal separator, e.g. ‘,’ in Europe.
  • bold_rows (bool, default True) – Make the row labels bold in the output.
  • classes (str or list or tuple, default None) – CSS class(es) to apply to the resulting html table.
  • escape (bool, default True) – Convert the characters <, >, and & to HTML-safe sequences.
  • notebook ({True, False}, default False) – Whether the generated HTML is for IPython Notebook.
  • border (int) – A border=border attribute is included in the opening <table> tag. Default pd.options.display.html.border.
  • encoding (str, default "utf-8") –

    Set character encoding.

    New in version 1.0.

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

    New in version 0.24.0.

Returns:

If buf is None, returns the result as a string. Otherwise returns None.

Return type:

str or None

Differences from pandas

This operation has no known divergences from the pandas API.

See also

to_string()
Convert DeferredDataFrame to a string.
apache_beam.dataframe.io.read_excel(path, *args, **kwargs)

Read an Excel file into a pandas 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, bytes, 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. Lists of strings/integers are used to request multiple sheets. Specify None to get all sheets.

    Available cases:

    • Defaults to 0: 1st sheet as a DeferredDataFrame
    • 1: 2nd sheet as a DeferredDataFrame
    • "Sheet1": Load sheet with name “Sheet1”
    • [0, 1, "Sheet5"]: Load first, second and sheet named “Sheet5” as a dict of DeferredDataFrame
    • None: All sheets.
  • header (int, list of int, default 0) – Row (0-indexed) to use for the column labels of the parsed DeferredDataFrame. 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, list of int, default None) – Column (0-indexed) to use as the row labels of the DeferredDataFrame. 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.
  • usecols (int, 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.
    • If list of string, then indicates list of column names to be parsed.

      New in version 0.24.0.

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

    New in version 0.24.0.

  • squeeze (bool, default False) – If the parsed data only contains one column then return a DeferredSeries.
  • 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. If converters are specified, they will be applied INSTEAD of dtype conversion.
  • 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”. 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.

    Changed in version 1.2.0: The engine xlrd 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 will be used.
    • Otherwise if path_or_buffer is an xls format, xlrd will be used.
    • Otherwise if openpyxl is installed, then openpyxl will be used.
    • Otherwise if xlrd >= 2.0 is installed, a ValueError will be raised.
    • Otherwise xlrd will be used and a FutureWarning will be raised. This case will raise a ValueError in a future version of pandas.
  • 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. 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.
  • 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 unparseable 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_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.
  • 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).
  • convert_float (bool, default True) – Convert integral floats to int (i.e., 1.0 –> 1). If False, all numeric data will be read in as floats: Excel stores all numbers as floats internally.
  • 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.
  • storage_options (dict, optional) –

    Extra options that make sense for a particular storage connection, e.g. host, port, username, password, etc., if using a URL that will be parsed by fsspec, e.g., starting “s3://”, “gcs://”. An error will be raised if providing this argument with a local path or a file-like buffer. See the fsspec and backend storage implementation docs for the set of allowed keys and values.

    New in version 1.2.0.

Returns:

DeferredDataFrame from the passed in Excel file. See notes in sheet_name argument for more information on when a dict of DeferredDataFrames is returned.

Return type:

DeferredDataFrame or dict of DeferredDataFrames

Differences from pandas

This operation has no known divergences from the pandas API.

See also

DeferredDataFrame.to_excel()
Write DeferredDataFrame to an Excel file.
DeferredDataFrame.to_csv()
Write DeferredDataFrame to a comma-separated values (csv) file.
read_csv()
Read a comma-separated values (csv) file into DeferredDataFrame.
read_fwf()
Read a table of fixed-width formatted lines into DeferredDataFrame.

Examples

NOTE: These examples are pulled directly from the pandas documentation for convenience. Usage of the Beam DataFrame API will look different because it is a deferred API.

The file can be read using the file name as string or an open file object:

>>> pd.read_excel('tmp.xlsx', index_col=0)  
       Name  Value
0   string1      1
1   string2      2
2  #Comment      3

>>> pd.read_excel(open('tmp.xlsx', 'rb'),
...               sheet_name='Sheet3')  
   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)  
     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})  
       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'])  
       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='#')  
      Name  Value
0  string1    1.0
1  string2    2.0
2     None    NaN
apache_beam.dataframe.io.read_feather(path, *args, **kwargs)

Load a feather-format object from the file path.

Parameters:
  • path (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, and file. For file URLs, a host is expected. A local file could be: file://localhost/path/to/table.feather.

    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.

  • columns (sequence, default None) –

    If not provided, all columns are read.

    New in version 0.24.0.

  • use_threads (bool, default True) –

    Whether to parallelize reading using multiple threads.

    New in version 0.24.0.

  • storage_options (dict, optional) –

    Extra options that make sense for a particular storage connection, e.g. host, port, username, password, etc., if using a URL that will be parsed by fsspec, e.g., starting “s3://”, “gcs://”. An error will be raised if providing this argument with a non-fsspec URL. See the fsspec and backend storage implementation docs for the set of allowed keys and values.

    New in version 1.2.0.

Returns:

Return type:

type of object stored in file

Differences from pandas

This operation has no known divergences from the pandas API.

apache_beam.dataframe.io.read_parquet(path, *args, **kwargs)

Load a parquet object from the file path, returning a DataFrame.

Parameters:
  • path (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.parquet. A file URL can also be a path to a directory that contains multiple partitioned parquet files. Both pyarrow and fastparquet support paths to directories as well as file URLs. A directory path could be: file://localhost/path/to/tables or s3://bucket/partition_dir

    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.

  • engine ({'auto', 'pyarrow', 'fastparquet'}, default 'auto') – Parquet library to use. If ‘auto’, then the option io.parquet.engine is used. The default io.parquet.engine behavior is to try ‘pyarrow’, falling back to ‘fastparquet’ if ‘pyarrow’ is unavailable.
  • columns (list, default=None) – If not None, only these columns will be read from the file.
  • use_nullable_dtypes (bool, default False) –

    If True, use dtypes that use pd.NA as missing value indicator for the resulting DeferredDataFrame (only applicable for engine="pyarrow"). As new dtypes are added that support pd.NA in the future, the output with this option will change to use those dtypes. Note: this is an experimental option, and behaviour (e.g. additional support dtypes) may change without notice.

    New in version 1.2.0.

  • **kwargs – Any additional kwargs are passed to the engine.
Returns:

Return type:

DeferredDataFrame

Differences from pandas

This operation has no known divergences from the pandas API.

apache_beam.dataframe.io.read_sas(path, *args, **kwargs)

Read SAS files stored as either XPORT or SAS7BDAT format files.

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, and file. For file URLs, a host is expected. A local file could be: file://localhost/path/to/table.sas.

    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.

  • format (str {'xport', 'sas7bdat'} or None) – If None, file format is inferred from file extension. If ‘xport’ or ‘sas7bdat’, uses the corresponding format.
  • index (identifier of index column, defaults to None) – Identifier of column that should be used as index of the DeferredDataFrame.
  • encoding (str, default is None) – Encoding for text data. If None, text data are stored as raw bytes.
  • chunksize (int) –

    Read file chunksize lines at a time, returns iterator.

    Changed in version 1.2: TextFileReader is a context manager.

  • iterator (bool, defaults to False) –

    If True, returns an iterator for reading the file incrementally.

    Changed in version 1.2: TextFileReader is a context manager.

Returns:

  • DeferredDataFrame if iterator=False and chunksize=None, else SAS7BDATReader
  • or XportReader

Differences from pandas

This operation has no known divergences from the pandas API.

apache_beam.dataframe.io.read_spss(path, *args, **kwargs)

Load an SPSS file from the file path, returning a DataFrame.

New in version 0.25.0.

Parameters:
  • path (str or Path) – File path.
  • usecols (list-like, optional) – Return a subset of the columns. If None, return all columns.
  • convert_categoricals (bool, default is True) – Convert categorical columns into pd.Categorical.
Returns:

Return type:

DeferredDataFrame

Differences from pandas

This operation has no known divergences from the pandas API.

apache_beam.dataframe.io.read_stata(path, *args, **kwargs)

Read Stata file into DataFrame.

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, and file. For file URLs, a host is expected. A local file could be: file://localhost/path/to/table.dta.

    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.

  • convert_dates (bool, default True) – Convert date variables to DeferredDataFrame time values.
  • convert_categoricals (bool, default True) – Read value labels and convert columns to Categorical/Factor variables.
  • index_col (str, optional) – Column to set as index.
  • convert_missing (bool, default False) – Flag indicating whether to convert missing values to their Stata representations. If False, missing values are replaced with nan. If True, columns containing missing values are returned with object data types and missing values are represented by StataMissingValue objects.
  • preserve_dtypes (bool, default True) – Preserve Stata datatypes. If False, numeric data are upcast to pandas default types for foreign data (float64 or int64).
  • columns (list or None) – Columns to retain. Columns will be returned in the given order. None returns all columns.
  • order_categoricals (bool, default True) – Flag indicating whether converted categorical data are ordered.
  • chunksize (int, default None) – Return StataReader object for iterations, returns chunks with given number of lines.
  • iterator (bool, default False) – Return StataReader object.
Returns:

Return type:

DeferredDataFrame or StataReader

Differences from pandas

This operation has no known divergences from the pandas API.

See also

io.stata.StataReader()
Low-level reader for Stata data files.
DeferredDataFrame.to_stata()
Export Stata data files.

Notes

Categorical variables read through an iterator may not have the same categories and dtype. This occurs when a variable stored in a DTA file is associated to an incomplete set of value labels that only label a strict subset of the values.

Examples

NOTE: These examples are pulled directly from the pandas documentation for convenience. Usage of the Beam DataFrame API will look different because it is a deferred API.

Read a Stata dta file:

>>> df = pd.read_stata('filename.dta')

Read a Stata dta file in 10,000 line chunks:

>>> itr = pd.read_stata('filename.dta', chunksize=10000)
>>> for chunk in itr:
...     do_something(chunk)
apache_beam.dataframe.io.to_excel(df, path, *args, **kwargs)

Write object to an Excel sheet.

To write a single object to an Excel .xlsx file it is only necessary to specify a target file name. To write to multiple sheets it is necessary to create an ExcelWriter object with a target file name, and specify a sheet in the file to write to.

Multiple sheets may be written to by specifying unique sheet_name. With all data written to the file it is necessary to save the changes. Note that creating an ExcelWriter object with a file name that already exists will result in the contents of the existing file being erased.

Parameters:
  • excel_writer (path-like, file-like, or ExcelWriter object) – File path or existing ExcelWriter.
  • sheet_name (str, default 'Sheet1') – Name of sheet which will contain DeferredDataFrame.
  • na_rep (str, default '') – Missing data representation.
  • float_format (str, optional) – Format string for floating point numbers. For example float_format="%.2f" will format 0.1234 to 0.12.
  • columns (sequence or list of str, optional) – Columns to write.
  • header (bool or list of str, default True) – Write out the column names. If a list of string is given it is assumed to be aliases for the column names.
  • index (bool, default True) – Write row names (index).
  • index_label (str or sequence, optional) – Column label for index column(s) if desired. If not specified, and header and index are True, then the index names are used. A sequence should be given if the DeferredDataFrame uses MultiIndex.
  • startrow (int, default 0) – Upper left cell row to dump data frame.
  • startcol (int, default 0) – Upper left cell column to dump data frame.
  • engine (str, optional) –

    Write engine to use, ‘openpyxl’ or ‘xlsxwriter’. You can also set this via the options io.excel.xlsx.writer, io.excel.xls.writer, and io.excel.xlsm.writer.

    Deprecated since version 1.2.0: As the xlwt package is no longer maintained, the xlwt engine will be removed in a future version of pandas.

  • merge_cells (bool, default True) – Write MultiIndex and Hierarchical Rows as merged cells.
  • encoding (str, optional) – Encoding of the resulting excel file. Only necessary for xlwt, other writers support unicode natively.
  • inf_rep (str, default 'inf') – Representation for infinity (there is no native representation for infinity in Excel).
  • verbose (bool, default True) – Display more information in the error logs.
  • freeze_panes (tuple of int (length 2), optional) – Specifies the one-based bottommost row and rightmost column that is to be frozen.
  • storage_options (dict, optional) –

    Extra options that make sense for a particular storage connection, e.g. host, port, username, password, etc., if using a URL that will be parsed by fsspec, e.g., starting “s3://”, “gcs://”. An error will be raised if providing this argument with a non-fsspec URL. See the fsspec and backend storage implementation docs for the set of allowed keys and values.

    New in version 1.2.0.

Differences from pandas

This operation has no known divergences from the pandas API.

See also

to_csv()
Write DeferredDataFrame to a comma-separated values (csv) file.
ExcelWriter()
Class for writing DeferredDataFrame objects into excel sheets.
read_excel()
Read an Excel file into a pandas DeferredDataFrame.
read_csv()
Read a comma-separated values (csv) file into DeferredDataFrame.

Notes

For compatibility with to_csv(), to_excel serializes lists and dicts to strings before writing.

Once a workbook has been saved it is not possible write further data without rewriting the whole workbook.

Examples

NOTE: These examples are pulled directly from the pandas documentation for convenience. Usage of the Beam DataFrame API will look different because it is a deferred API.

Create, write to and save a workbook:

>>> df1 = pd.DataFrame([['a', 'b'], ['c', 'd']],
...                    index=['row 1', 'row 2'],
...                    columns=['col 1', 'col 2'])
>>> df1.to_excel("output.xlsx")  

To specify the sheet name:

>>> df1.to_excel("output.xlsx",
...              sheet_name='Sheet_name_1')  

If you wish to write to more than one sheet in the workbook, it is
necessary to specify an ExcelWriter object:

>>> df2 = df1.copy()
>>> with pd.ExcelWriter('output.xlsx') as writer:  
...     df1.to_excel(writer, sheet_name='Sheet_name_1')
...     df2.to_excel(writer, sheet_name='Sheet_name_2')

ExcelWriter can also be used to append to an existing Excel file:

>>> with pd.ExcelWriter('output.xlsx',
...                     mode='a') as writer:  
...     df.to_excel(writer, sheet_name='Sheet_name_3')

To set the library that is used to write the Excel file,
you can pass the `engine` keyword (the default engine is
automatically chosen depending on the file extension):

>>> df1.to_excel('output1.xlsx', engine='xlsxwriter')  
apache_beam.dataframe.io.to_feather(df, path, *args, **kwargs)

Write a DataFrame to the binary Feather format.

Parameters:
  • path (str or file-like object) – If a string, it will be used as Root Directory path.
  • **kwargs

    Additional keywords passed to pyarrow.feather.write_feather(). Starting with pyarrow 0.17, this includes the compression, compression_level, chunksize and version keywords.

    New in version 1.1.0.

Differences from pandas

This operation has no known divergences from the pandas API.

apache_beam.dataframe.io.to_parquet(df, path, *args, **kwargs)

Write a DataFrame to the binary parquet format.

This function writes the dataframe as a parquet file. You can choose different parquet backends, and have the option of compression. See the user guide for more details.

Parameters:
  • path (str or file-like object, default None) –

    If a string, it will be used as Root Directory path when writing a partitioned dataset. By file-like object, we refer to objects with a write() method, such as a file handle (e.g. via builtin open function) or io.BytesIO. The engine fastparquet does not accept file-like objects. If path is None, a bytes object is returned.

    Changed in version 1.2.0.

    Previously this was “fname”

  • engine ({'auto', 'pyarrow', 'fastparquet'}, default 'auto') – Parquet library to use. If ‘auto’, then the option io.parquet.engine is used. The default io.parquet.engine behavior is to try ‘pyarrow’, falling back to ‘fastparquet’ if ‘pyarrow’ is unavailable.
  • compression ({'snappy', 'gzip', 'brotli', None}, default 'snappy') – Name of the compression to use. Use None for no compression.
  • index (bool, default None) –

    If True, include the dataframe’s index(es) in the file output. If False, they will not be written to the file. If None, similar to True the dataframe’s index(es) will be saved. However, instead of being saved as values, the RangeIndex will be stored as a range in the metadata so it doesn’t require much space and is faster. Other indexes will be included as columns in the file output.

    New in version 0.24.0.

  • partition_cols (list, optional, default None) –

    Column names by which to partition the dataset. Columns are partitioned in the order they are given. Must be None if path is not a string.

    New in version 0.24.0.

  • storage_options (dict, optional) –

    Extra options that make sense for a particular storage connection, e.g. host, port, username, password, etc., if using a URL that will be parsed by fsspec, e.g., starting “s3://”, “gcs://”. An error will be raised if providing this argument with a non-fsspec URL. See the fsspec and backend storage implementation docs for the set of allowed keys and values.

    New in version 1.2.0.

  • **kwargs – Additional arguments passed to the parquet library. See pandas io for more details.
Returns:

Return type:

bytes if no path argument is provided else None

Differences from pandas

This operation has no known divergences from the pandas API.

See also

read_parquet()
Read a parquet file.
DeferredDataFrame.to_csv()
Write a csv file.
DeferredDataFrame.to_sql()
Write to a sql table.
DeferredDataFrame.to_hdf()
Write to hdf.

Notes

This function requires either the fastparquet or pyarrow library.

Examples

NOTE: These examples are pulled directly from the pandas documentation for convenience. Usage of the Beam DataFrame API will look different because it is a deferred API.

>>> df = pd.DataFrame(data={'col1': [1, 2], 'col2': [3, 4]})
>>> df.to_parquet('df.parquet.gzip',
...               compression='gzip')  
>>> pd.read_parquet('df.parquet.gzip')  
   col1  col2
0     1     3
1     2     4

If you want to get a buffer to the parquet content you can use a io.BytesIO
object, as long as you don't use partition_cols, which creates multiple files.

>>> import io
>>> f = io.BytesIO()
>>> df.to_parquet(f)
>>> f.seek(0)
0
>>> content = f.read()
apache_beam.dataframe.io.to_stata(df, path, *args, **kwargs)

Export DataFrame object to Stata dta format.

Writes the DataFrame to a Stata dataset file. “dta” files contain a Stata dataset.

Parameters:
  • path (str, buffer or path object) –

    String, path object (pathlib.Path or py._path.local.LocalPath) or object implementing a binary write() function. If using a buffer then the buffer will not be automatically closed after the file data has been written.

    Changed in version 1.0.0.

    Previously this was “fname”

  • convert_dates (dict) – Dictionary mapping columns containing datetime types to stata internal format to use when writing the dates. Options are ‘tc’, ‘td’, ‘tm’, ‘tw’, ‘th’, ‘tq’, ‘ty’. Column can be either an integer or a name. Datetime columns that do not have a conversion type specified will be converted to ‘tc’. Raises NotImplementedError if a datetime column has timezone information.
  • write_index (bool) – Write the index to Stata dataset.
  • byteorder (str) – Can be “>”, “<”, “little”, or “big”. default is sys.byteorder.
  • time_stamp (datetime) – A datetime to use as file creation date. Default is the current time.
  • data_label (str, optional) – A label for the data set. Must be 80 characters or smaller.
  • variable_labels (dict) – Dictionary containing columns as keys and variable labels as values. Each label must be 80 characters or smaller.
  • version ({114, 117, 118, 119, None}, default 114) –

    Version to use in the output dta file. Set to None to let pandas decide between 118 or 119 formats depending on the number of columns in the frame. pandas Version 114 can be read by Stata 10 and later. pandas Version 117 can be read by Stata 13 or later. pandas Version 118 is supported in Stata 14 and later. pandas Version 119 is supported in Stata 15 and later. pandas Version 114 limits string variables to 244 characters or fewer while versions 117 and later allow strings with lengths up to 2,000,000 characters. Versions 118 and 119 support Unicode characters, and pandas version 119 supports more than 32,767 variables.

    pandas Version 119 should usually only be used when the number of variables exceeds the capacity of dta format 118. Exporting smaller datasets in format 119 may have unintended consequences, and, as of November 2020, Stata SE cannot read pandas version 119 files.

    Changed in version 1.0.0: Added support for formats 118 and 119.

  • convert_strl (list, optional) – List of column names to convert to string columns to Stata StrL format. Only available if version is 117. Storing strings in the StrL format can produce smaller dta files if strings have more than 8 characters and values are repeated.
  • compression (str or dict, default 'infer') –

    For on-the-fly compression of the output dta. If string, specifies compression mode. If dict, value at key ‘method’ specifies compression mode. Compression mode must be one of {‘infer’, ‘gzip’, ‘bz2’, ‘zip’, ‘xz’, None}. If compression mode is ‘infer’ and fname is path-like, then detect compression from the following extensions: ‘.gz’, ‘.bz2’, ‘.zip’, or ‘.xz’ (otherwise no compression). If dict and compression mode is one of {‘zip’, ‘gzip’, ‘bz2’}, or inferred as one of the above, other entries passed as additional compression options.

    New in version 1.1.0.

  • storage_options (dict, optional) –

    Extra options that make sense for a particular storage connection, e.g. host, port, username, password, etc., if using a URL that will be parsed by fsspec, e.g., starting “s3://”, “gcs://”. An error will be raised if providing this argument with a non-fsspec URL. See the fsspec and backend storage implementation docs for the set of allowed keys and values.

    New in version 1.2.0.

Raises:
  • NotImplementedError – * If datetimes contain timezone information * Column dtype is not representable in Stata

  • ValueError – * Columns listed in convert_dates are neither datetime64[ns]

    or datetime.datetime

    • Column listed in convert_dates is not in DeferredDataFrame
    • Categorical label contains more than 32,000 characters

Differences from pandas

This operation has no known divergences from the pandas API.

See also

read_stata()
Import Stata data files.
io.stata.StataWriter()
Low-level writer for Stata data files.
io.stata.StataWriter117()
Low-level writer for pandas version 117 files.

Examples

NOTE: These examples are pulled directly from the pandas documentation for convenience. Usage of the Beam DataFrame API will look different because it is a deferred API.

>>> df = pd.DataFrame({'animal': ['falcon', 'parrot', 'falcon',
...                               'parrot'],
...                    'speed': [350, 18, 361, 15]})
>>> df.to_stata('animals.dta')