Module: Polars::IO

Included in:
Polars
Defined in:
lib/polars/io/csv.rb,
lib/polars/io/ipc.rb,
lib/polars/io/avro.rb,
lib/polars/io/json.rb,
lib/polars/io/cloud.rb,
lib/polars/io/delta.rb,
lib/polars/io/utils.rb,
lib/polars/io/ndjson.rb,
lib/polars/io/iceberg.rb,
lib/polars/io/parquet.rb,
lib/polars/io/database.rb,
lib/polars/io/scan_options.rb,
lib/polars/io/sink_options.rb

Instance Method Summary collapse

Instance Method Details

#read_avro(source, columns: nil, n_rows: nil) ⇒ DataFrame

Read into a DataFrame from Apache Avro format.

Parameters:

  • source (Object)

    Path to a file or a file-like object.

  • columns (Object) (defaults to: nil)

    Columns to select. Accepts a list of column indices (starting at zero) or a list of column names.

  • n_rows (Integer) (defaults to: nil)

    Stop reading from Apache Avro file after reading n_rows.

Returns:



14
15
16
17
18
19
20
21
22
# File 'lib/polars/io/avro.rb', line 14

def read_avro(source, columns: nil, n_rows: nil)
  if Utils.pathlike?(source)
    source = Utils.normalize_filepath(source)
  end
  projection, column_names = Utils.handle_projection_columns(columns)

  rbdf = RbDataFrame.read_avro(source, column_names, projection, n_rows)
  Utils.wrap_df(rbdf)
end

#read_csv(source, has_header: true, columns: nil, new_columns: nil, separator: ",", comment_prefix: nil, quote_char: '"', skip_rows: 0, skip_lines: 0, schema: nil, schema_overrides: nil, null_values: nil, missing_utf8_is_empty_string: false, ignore_errors: false, try_parse_dates: false, n_threads: nil, infer_schema: true, infer_schema_length: N_INFER_DEFAULT, batch_size: 8192, n_rows: nil, encoding: "utf8", low_memory: false, rechunk: false, storage_options: nil, skip_rows_after_header: 0, row_index_name: nil, row_index_offset: 0, eol_char: "\n", raise_if_empty: true, truncate_ragged_lines: false, decimal_comma: false, glob: true) ⇒ DataFrame

Note:

This operation defaults to a rechunk operation at the end, meaning that all data will be stored continuously in memory. Set rechunk: false if you are benchmarking the csv-reader. A rechunk is an expensive operation.

Read a CSV file into a DataFrame.

Parameters:

  • source (Object)

    Path to a file or a file-like object.

  • has_header (Boolean) (defaults to: true)

    Indicate if the first row of dataset is a header or not. If set to false, column names will be autogenerated in the following format: column_x, with x being an enumeration over every column in the dataset starting at 1.

  • columns (Object) (defaults to: nil)

    Columns to select. Accepts a list of column indices (starting at zero) or a list of column names.

  • new_columns (Object) (defaults to: nil)

    Rename columns right after parsing the CSV file. If the given list is shorter than the width of the DataFrame the remaining columns will have their original name.

  • separator (String) (defaults to: ",")

    Single byte character to use as separator in the file.

  • comment_prefix (String) (defaults to: nil)

    A string used to indicate the start of a comment line. Comment lines are skipped during parsing. Common examples of comment prefixes are # and //.

  • quote_char (String) (defaults to: '"')

    Single byte character used for csv quoting. Set to nil to turn off special handling and escaping of quotes.

  • skip_rows (Integer) (defaults to: 0)

    Start reading after skip_rows lines.

  • skip_lines (Integer) (defaults to: 0)

    Start reading after skip_lines lines. The header will be parsed at this offset. Note that CSV escaping will not be respected when skipping lines. If you want to skip valid CSV rows, use skip_rows.

  • schema (Object) (defaults to: nil)

    Provide the schema. This means that polars doesn't do schema inference. This argument expects the complete schema, whereas schema_overrides can be used to partially overwrite a schema. Note that the order of the columns in the provided schema must match the order of the columns in the CSV being read.

  • schema_overrides (Object) (defaults to: nil)

    Overwrite dtypes for specific or all columns during schema inference.

  • null_values (Object) (defaults to: nil)

    Values to interpret as null values. You can provide a:

    • String: All values equal to this string will be null.
    • Array: All values equal to any string in this array will be null.
    • Hash: A hash that maps column name to a null value string.
  • missing_utf8_is_empty_string (Boolean) (defaults to: false)

    By default a missing value is considered to be null; if you would prefer missing utf8 values to be treated as the empty string you can set this param true.

  • ignore_errors (Boolean) (defaults to: false)

    Try to keep reading lines if some lines yield errors. First try infer_schema_length: 0 to read all columns as :str to check which values might cause an issue.

  • try_parse_dates (Boolean) (defaults to: false)

    Try to automatically parse dates. If this does not succeed, the column remains of data type :str.

  • n_threads (Integer) (defaults to: nil)

    Number of threads to use in csv parsing. Defaults to the number of physical cpu's of your system.

  • infer_schema (Boolean) (defaults to: true)

    When true, the schema is inferred from the data using the first infer_schema_length rows. When false, the schema is not inferred and will be Polars::String if not specified in schema or schema_overrides.

  • infer_schema_length (Integer) (defaults to: N_INFER_DEFAULT)

    The maximum number of rows to scan for schema inference. If set to nil, the full data may be scanned (this is slow). Set infer_schema: false to read all columns as Polars::String.

  • batch_size (Integer) (defaults to: 8192)

    Number of lines to read into the buffer at once. Modify this to change performance.

  • n_rows (Integer) (defaults to: nil)

    Stop reading from CSV file after reading n_rows. During multi-threaded parsing, an upper bound of n_rows rows cannot be guaranteed.

  • encoding ("utf8", "utf8-lossy") (defaults to: "utf8")

    Lossy means that invalid utf8 values are replaced with characters. When using other encodings than utf8 or utf8-lossy, the input is first decoded im memory with Ruby.

  • low_memory (Boolean) (defaults to: false)

    Reduce memory usage at expense of performance.

  • rechunk (Boolean) (defaults to: false)

    Make sure that all columns are contiguous in memory by aggregating the chunks into a single array.

  • storage_options (Hash) (defaults to: nil)

    Extra options that make sense for a particular storage connection.

  • skip_rows_after_header (Integer) (defaults to: 0)

    Skip this number of rows when the header is parsed.

  • row_index_name (String) (defaults to: nil)

    If not nil, this will insert a row count column with the given name into the DataFrame.

  • row_index_offset (Integer) (defaults to: 0)

    Offset to start the row_count column (only used if the name is set).

  • eol_char (String) (defaults to: "\n")

    Single byte end of line character.

  • raise_if_empty (Boolean) (defaults to: true)

    When there is no data in the source, NoDataError is raised. If this parameter is set to false, an empty DataFrame (with no columns) is returned instead.

  • truncate_ragged_lines (Boolean) (defaults to: false)

    Truncate lines that are longer than the schema.

  • decimal_comma (Boolean) (defaults to: false)

    Parse floats using a comma as the decimal separator instead of a period.

  • glob (Boolean) (defaults to: true)

    Expand path given via globbing rules.

Returns:



114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
# File 'lib/polars/io/csv.rb', line 114

def read_csv(
  source,
  has_header: true,
  columns: nil,
  new_columns: nil,
  separator: ",",
  comment_prefix: nil,
  quote_char: '"',
  skip_rows: 0,
  skip_lines: 0,
  schema: nil,
  schema_overrides: nil,
  null_values: nil,
  missing_utf8_is_empty_string: false,
  ignore_errors: false,
  try_parse_dates: false,
  n_threads: nil,
  infer_schema: true,
  infer_schema_length: N_INFER_DEFAULT,
  batch_size: 8192,
  n_rows: nil,
  encoding: "utf8",
  low_memory: false,
  rechunk: false,
  storage_options: nil,
  skip_rows_after_header: 0,
  row_index_name: nil,
  row_index_offset: 0,
  eol_char: "\n",
  raise_if_empty: true,
  truncate_ragged_lines: false,
  decimal_comma: false,
  glob: true
)
  Utils._check_arg_is_1byte("separator", separator, false)
  Utils._check_arg_is_1byte("quote_char", quote_char, true)
  Utils._check_arg_is_1byte("eol_char", eol_char, false)

  projection, columns = Utils.handle_projection_columns(columns)

  storage_options ||= {}

  if columns && !has_header
    columns.each do |column|
      if !column.start_with?("column_")
        raise ArgumentError, "Specified column names do not start with \"column_\", but autogenerated header names were requested."
      end
    end
  end

  if !infer_schema
    infer_schema_length = 0
  end

  df = nil
  _prepare_file_arg(source) do |data|
    df = _read_csv_impl(
      data,
      has_header: has_header,
      columns: columns || projection,
      separator: separator,
      comment_prefix: comment_prefix,
      quote_char: quote_char,
      skip_rows: skip_rows,
      skip_lines: skip_lines,
      schema_overrides: schema_overrides,
      schema: schema,
      null_values: null_values,
      missing_utf8_is_empty_string: missing_utf8_is_empty_string,
      ignore_errors: ignore_errors,
      try_parse_dates: try_parse_dates,
      n_threads: n_threads,
      infer_schema_length: infer_schema_length,
      batch_size: batch_size,
      n_rows: n_rows,
      encoding: encoding == "utf8-lossy" ? encoding : "utf8",
      low_memory: low_memory,
      rechunk: rechunk,
      skip_rows_after_header: skip_rows_after_header,
      row_index_name: row_index_name,
      row_index_offset: row_index_offset,
      eol_char: eol_char,
      raise_if_empty: raise_if_empty,
      truncate_ragged_lines: truncate_ragged_lines,
      decimal_comma: decimal_comma,
      glob: glob
    )
  end

  if new_columns
    Utils._update_columns(df, new_columns)
  else
    df
  end
end

#read_csv_batched(source, has_header: true, columns: nil, new_columns: nil, separator: ",", comment_prefix: nil, quote_char: '"', skip_rows: 0, skip_lines: 0, schema_overrides: nil, null_values: nil, missing_utf8_is_empty_string: false, ignore_errors: false, try_parse_dates: false, n_threads: nil, infer_schema_length: N_INFER_DEFAULT, batch_size: 50_000, n_rows: nil, encoding: "utf8", low_memory: false, rechunk: false, skip_rows_after_header: 0, row_index_name: nil, row_index_offset: 0, eol_char: "\n", raise_if_empty: true, truncate_ragged_lines: false, decimal_comma: false) ⇒ BatchedCsvReader

Deprecated.

Use scan_csv().collect_batches instead.

Read a CSV file in batches.

Upon creation of the BatchedCsvReader, polars will gather statistics and determine the file chunks. After that work will only be done if next_batches is called.

Examples:

reader = Polars.read_csv_batched(
  "./tpch/tables_scale_100/lineitem.tbl", separator: "|", try_parse_dates: true
)
reader.next_batches(5)

Parameters:

  • source (Object)

    Path to a file or a file-like object.

  • has_header (Boolean) (defaults to: true)

    Indicate if the first row of dataset is a header or not. If set to false, column names will be autogenerated in the following format: column_x, with x being an enumeration over every column in the dataset starting at 1.

  • columns (Object) (defaults to: nil)

    Columns to select. Accepts a list of column indices (starting at zero) or a list of column names.

  • new_columns (Object) (defaults to: nil)

    Rename columns right after parsing the CSV file. If the given list is shorter than the width of the DataFrame the remaining columns will have their original name.

  • separator (String) (defaults to: ",")

    Single byte character to use as separator in the file.

  • comment_prefix (String) (defaults to: nil)

    A string used to indicate the start of a comment line. Comment lines are skipped during parsing. Common examples of comment prefixes are # and //.

  • quote_char (String) (defaults to: '"')

    Single byte character used for csv quoting, default = ". Set to nil to turn off special handling and escaping of quotes.

  • skip_rows (Integer) (defaults to: 0)

    Start reading after skip_rows lines.

  • skip_lines (Integer) (defaults to: 0)

    Start reading after skip_lines lines. The header will be parsed at this offset. Note that CSV escaping will not be respected when skipping lines. If you want to skip valid CSV rows, use skip_rows.

  • schema_overrides (Object) (defaults to: nil)

    Overwrite dtypes during inference.

  • null_values (Object) (defaults to: nil)

    Values to interpret as null values. You can provide a:

    • String: All values equal to this string will be null.
    • Array: All values equal to any string in this array will be null.
    • Hash: A hash that maps column name to a null value string.
  • missing_utf8_is_empty_string (Boolean) (defaults to: false)

    By default a missing value is considered to be null; if you would prefer missing utf8 values to be treated as the empty string you can set this param true.

  • ignore_errors (Boolean) (defaults to: false)

    Try to keep reading lines if some lines yield errors. First try infer_schema_length: 0 to read all columns as :str to check which values might cause an issue.

  • try_parse_dates (Boolean) (defaults to: false)

    Try to automatically parse dates. If this does not succeed, the column remains of data type :str.

  • n_threads (Integer) (defaults to: nil)

    Number of threads to use in csv parsing. Defaults to the number of physical cpu's of your system.

  • infer_schema_length (Integer) (defaults to: N_INFER_DEFAULT)

    Maximum number of lines to read to infer schema. If set to 0, all columns will be read as :str. If set to nil, a full table scan will be done (slow).

  • batch_size (Integer) (defaults to: 50_000)

    Number of lines to read into the buffer at once. Modify this to change performance.

  • n_rows (Integer) (defaults to: nil)

    Stop reading from CSV file after reading n_rows. During multi-threaded parsing, an upper bound of n_rows rows cannot be guaranteed.

  • encoding ("utf8", "utf8-lossy") (defaults to: "utf8")

    Lossy means that invalid utf8 values are replaced with characters. When using other encodings than utf8 or utf8-lossy, the input is first decoded im memory with Ruby. Defaults to utf8.

  • low_memory (Boolean) (defaults to: false)

    Reduce memory usage at expense of performance.

  • rechunk (Boolean) (defaults to: false)

    Make sure that all columns are contiguous in memory by aggregating the chunks into a single array.

  • skip_rows_after_header (Integer) (defaults to: 0)

    Skip this number of rows when the header is parsed.

  • row_index_name (String) (defaults to: nil)

    If not nil, this will insert a row count column with the given name into the DataFrame.

  • row_index_offset (Integer) (defaults to: 0)

    Offset to start the row_count column (only used if the name is set).

  • eol_char (String) (defaults to: "\n")

    Single byte end of line character.

  • raise_if_empty (Boolean) (defaults to: true)

    When there is no data in the source,NoDataError is raised. If this parameter is set to false, nil will be returned from next_batches(n) instead.

  • truncate_ragged_lines (Boolean) (defaults to: false)

    Truncate lines that are longer than the schema.

  • decimal_comma (Boolean) (defaults to: false)

    Parse floats using a comma as the decimal separator instead of a period.

Returns:

  • (BatchedCsvReader)


456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
# File 'lib/polars/io/csv.rb', line 456

def read_csv_batched(
  source,
  has_header: true,
  columns: nil,
  new_columns: nil,
  separator: ",",
  comment_prefix: nil,
  quote_char: '"',
  skip_rows: 0,
  skip_lines: 0,
  schema_overrides: nil,
  null_values: nil,
  missing_utf8_is_empty_string: false,
  ignore_errors: false,
  try_parse_dates: false,
  n_threads: nil,
  infer_schema_length: N_INFER_DEFAULT,
  batch_size: 50_000,
  n_rows: nil,
  encoding: "utf8",
  low_memory: false,
  rechunk: false,
  skip_rows_after_header: 0,
  row_index_name: nil,
  row_index_offset: 0,
  eol_char: "\n",
  raise_if_empty: true,
  truncate_ragged_lines: false,
  decimal_comma: false
)
  projection, columns = Utils.handle_projection_columns(columns)

  if columns && !has_header
    columns.each do |column|
      if !column.start_with?("column_")
        raise ArgumentError, "Specified column names do not start with \"column_\", but autogenerated header names were requested."
      end
    end
  end

  BatchedCsvReader.new(
    source,
    has_header: has_header,
    columns: columns || projection,
    separator: separator,
    comment_prefix: comment_prefix,
    quote_char: quote_char,
    skip_rows: skip_rows,
    skip_lines: skip_lines,
    schema_overrides: schema_overrides,
    null_values: null_values,
    missing_utf8_is_empty_string: missing_utf8_is_empty_string,
    ignore_errors: ignore_errors,
    try_parse_dates: try_parse_dates,
    n_threads: n_threads,
    infer_schema_length: infer_schema_length,
    batch_size: batch_size,
    n_rows: n_rows,
    encoding: encoding == "utf8-lossy" ? encoding : "utf8",
    low_memory: low_memory,
    rechunk: rechunk,
    skip_rows_after_header: skip_rows_after_header,
    row_index_name: row_index_name,
    row_index_offset: row_index_offset,
    eol_char: eol_char,
    new_columns: new_columns,
    raise_if_empty: raise_if_empty,
    truncate_ragged_lines: truncate_ragged_lines,
    decimal_comma: decimal_comma
  )
end

#read_database(query, schema_overrides: nil) ⇒ DataFrame

Read a SQL query into a DataFrame.

Parameters:

  • query (Object)

    ActiveRecord::Relation or ActiveRecord::Result.

  • schema_overrides (Hash) (defaults to: nil)

    A hash mapping column names to dtypes, used to override the schema inferred from the query.

Returns:



12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
# File 'lib/polars/io/database.rb', line 12

def read_database(query, schema_overrides: nil)
  if !defined?(ActiveRecord)
    raise Error, "Active Record not available"
  end

  result =
    if query.is_a?(ActiveRecord::Result)
      query
    elsif query.is_a?(ActiveRecord::Relation)
      query.connection_pool.with_connection { |c| c.select_all(query.to_sql) }
    elsif query.is_a?(::String)
      ActiveRecord::Base.connection_pool.with_connection { |c| c.select_all(query) }
    else
      raise ArgumentError, "Expected ActiveRecord::Relation, ActiveRecord::Result, or String"
    end

  data = {}
  schema_overrides = (schema_overrides || {}).transform_keys(&:to_s)

  result.columns.each_with_index do |k, i|
    column_type = result.column_types[i]

    data[k] =
      if column_type
        result.rows.map { |r| column_type.deserialize(r[i]) }
      else
        result.rows.map { |r| r[i] }
      end

    polars_type =
      case column_type&.type
      when :binary
        Binary
      when :boolean
        Boolean
      when :date
        Date
      when :datetime, :timestamp
        Datetime
      when :decimal
        Decimal
      when :float
        # TODO uncomment in future release
        # if column_type.limit && column_type.limit <= 24
        #   Float32
        # else
        #   Float64
        # end
        Float64
      when :integer
        # TODO uncomment in future release
        # case column_type.limit
        # when 1
        #   Int8
        # when 2
        #   Int16
        # when 4
        #   Int32
        # else
        #   Int64
        # end
        Int64
      when :string, :text
        String
      when :time
        Time
      # TODO fix issue with null
      # when :json, :jsonb
      #   Struct
      end

    schema_overrides[k] ||= polars_type if polars_type
  end

  DataFrame.new(data, schema_overrides: schema_overrides)
end

#read_delta(source, version: nil, columns: nil, rechunk: nil, storage_options: nil, delta_table_options: nil) ⇒ DataFrame

Reads into a DataFrame from a Delta lake table.

Parameters:

  • source (Object)

    DeltaTable or a Path or URI to the root of the Delta lake table.

  • version (Object) (defaults to: nil)

    Numerical version or timestamp version of the Delta lake table.

  • columns (Array) (defaults to: nil)

    Columns to select. Accepts a list of column names.

  • rechunk (Boolean) (defaults to: nil)

    Make sure that all columns are contiguous in memory by aggregating the chunks into a single array.

  • storage_options (Hash) (defaults to: nil)

    Extra options for the storage backends supported by deltalake-rb.

  • delta_table_options (Hash) (defaults to: nil)

    Additional keyword arguments while reading a Delta lake Table.

Returns:



20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
# File 'lib/polars/io/delta.rb', line 20

def read_delta(
  source,
  version: nil,
  columns: nil,
  rechunk: nil,
  storage_options: nil,
  delta_table_options: nil
)
  df =
    scan_delta(
      source,
      version: version,
      storage_options: storage_options,
      delta_table_options: delta_table_options,
      rechunk: rechunk
    )

  if !columns.nil?
    df = df.select(columns)
  end
  df.collect
end

#read_ipc(source, columns: nil, n_rows: nil, memory_map: true, storage_options: nil, row_index_name: nil, row_index_offset: 0, rechunk: true) ⇒ DataFrame

Read into a DataFrame from Arrow IPC (Feather v2) file.

Parameters:

  • source (Object)

    Path to a file or a file-like object.

  • columns (Object) (defaults to: nil)

    Columns to select. Accepts a list of column indices (starting at zero) or a list of column names.

  • n_rows (Integer) (defaults to: nil)

    Stop reading from IPC file after reading n_rows.

  • memory_map (Boolean) (defaults to: true)

    Try to memory map the file. This can greatly improve performance on repeated queries as the OS may cache pages. Only uncompressed IPC files can be memory mapped.

  • storage_options (Hash) (defaults to: nil)

    Extra options that make sense for a particular storage connection.

  • row_index_name (String) (defaults to: nil)

    If not nil, this will insert a row count column with give name into the DataFrame.

  • row_index_offset (Integer) (defaults to: 0)

    Offset to start the row_count column (only use if the name is set).

  • rechunk (Boolean) (defaults to: true)

    Make sure that all data is contiguous.

Returns:



27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
# File 'lib/polars/io/ipc.rb', line 27

def read_ipc(
  source,
  columns: nil,
  n_rows: nil,
  memory_map: true,
  storage_options: nil,
  row_index_name: nil,
  row_index_offset: 0,
  rechunk: true
)
  storage_options ||= {}
  _prepare_file_arg(source, **storage_options) do |data|
    _read_ipc_impl(
      data,
      columns: columns,
      n_rows: n_rows,
      row_index_name: row_index_name,
      row_index_offset: row_index_offset,
      rechunk: rechunk,
      memory_map: memory_map
    )
  end
end

#read_ipc_schema(source) ⇒ Hash

Get a schema of the IPC file without reading data.

Parameters:

  • source (Object)

    Path to a file or a file-like object.

Returns:

  • (Hash)


164
165
166
167
168
169
170
# File 'lib/polars/io/ipc.rb', line 164

def read_ipc_schema(source)
  if Utils.pathlike?(source)
    source = Utils.normalize_filepath(source)
  end

  Plr.ipc_schema(source)
end

#read_ipc_stream(source, columns: nil, n_rows: nil, storage_options: nil, row_index_name: nil, row_index_offset: 0, rechunk: true) ⇒ DataFrame

Read into a DataFrame from Arrow IPC record batch stream.

See "Streaming format" on https://arrow.apache.org/docs/python/ipc.html.

Parameters:

  • source (Object)

    Path to a file or a file-like object.

  • columns (Array) (defaults to: nil)

    Columns to select. Accepts a list of column indices (starting at zero) or a list of column names.

  • n_rows (Integer) (defaults to: nil)

    Stop reading from IPC stream after reading n_rows.

  • storage_options (Hash) (defaults to: nil)

    Extra options that make sense for a particular storage connection.

  • row_index_name (String) (defaults to: nil)

    Insert a row index column with the given name into the DataFrame as the first column. If set to nil (default), no row index column is created.

  • row_index_offset (Integer) (defaults to: 0)

    Start the row index at this offset. Cannot be negative. Only used if row_index_name is set.

  • rechunk (Boolean) (defaults to: true)

    Make sure that all data is contiguous.

Returns:



108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
# File 'lib/polars/io/ipc.rb', line 108

def read_ipc_stream(
  source,
  columns: nil,
  n_rows: nil,
  storage_options: nil,
  row_index_name: nil,
  row_index_offset: 0,
  rechunk: true
)
  storage_options ||= {}
  _prepare_file_arg(source, **storage_options) do |data|
    _read_ipc_stream_impl(
      data,
      columns: columns,
      n_rows: n_rows,
      row_index_name: row_index_name,
      row_index_offset: row_index_offset,
      rechunk: rechunk
    )
  end
end

#read_json(source, schema: nil, schema_overrides: nil, infer_schema_length: N_INFER_DEFAULT) ⇒ DataFrame

Read into a DataFrame from a JSON file.

Parameters:

  • source (Object)

    Path to a file or a file-like object.

  • schema (Object) (defaults to: nil)

    The DataFrame schema may be declared in several ways:

    • As a hash of \{name:type} pairs; if type is nil, it will be auto-inferred.
    • As an array of column names; in this case types are automatically inferred.
    • As an array of [name,type] pairs; this is equivalent to the hash form.

    If you supply an array of column names that does not match the names in the underlying data, the names given here will overwrite them. The number of names given in the schema should match the underlying data dimensions.

  • schema_overrides (Hash) (defaults to: nil)

    Support type specification or override of one or more columns; note that any dtypes inferred from the schema param will be overridden.

  • infer_schema_length (Integer) (defaults to: N_INFER_DEFAULT)

    The maximum number of rows to scan for schema inference. If set to nil, the full data may be scanned (this is slow).

Returns:



25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
# File 'lib/polars/io/json.rb', line 25

def read_json(
  source,
  schema: nil,
  schema_overrides: nil,
  infer_schema_length: N_INFER_DEFAULT
)
  if Utils.pathlike?(source)
    source = Utils.normalize_filepath(source)
  end

  rbdf =
    RbDataFrame.read_json(
      source,
      infer_schema_length,
      schema,
      schema_overrides
    )
  Utils.wrap_df(rbdf)
end

#read_ndjson(source, schema: nil, schema_overrides: nil, infer_schema_length: N_INFER_DEFAULT, batch_size: 1024, n_rows: nil, low_memory: false, rechunk: false, row_index_name: nil, row_index_offset: 0, ignore_errors: false, storage_options: nil, credential_provider: "auto", retries: nil, file_cache_ttl: nil, include_file_paths: nil) ⇒ DataFrame

Read into a DataFrame from a newline delimited JSON file.

Parameters:

  • source (String)

    Path to a file.

  • schema (Object) (defaults to: nil)

    The DataFrame schema may be declared in several ways:

    • As a dict of \{name:type} pairs; if type is nil, it will be auto-inferred.
    • As a list of column names; in this case types are automatically inferred.
    • As a list of (name,type) pairs; this is equivalent to the hash form.

    If you supply a list of column names that does not match the names in the underlying data, the names given here will overwrite them. The number of names given in the schema should match the underlying data dimensions.

  • schema_overrides (Hash) (defaults to: nil)

    Support type specification or override of one or more columns; note that any dtypes inferred from the schema param will be overridden.

  • infer_schema_length (Integer) (defaults to: N_INFER_DEFAULT)

    Infer the schema length from the first infer_schema_length rows.

  • batch_size (Integer) (defaults to: 1024)

    Number of rows to read in each batch.

  • n_rows (Integer) (defaults to: nil)

    Stop reading from JSON file after reading n_rows.

  • low_memory (Boolean) (defaults to: false)

    Reduce memory pressure at the expense of performance.

  • rechunk (Boolean) (defaults to: false)

    Reallocate to contiguous memory when all chunks/ files are parsed.

  • row_index_name (String) (defaults to: nil)

    If not nil, this will insert a row count column with give name into the DataFrame.

  • row_index_offset (Integer) (defaults to: 0)

    Offset to start the row_count column (only use if the name is set).

  • ignore_errors (Boolean) (defaults to: false)

    Return Null if parsing fails because of schema mismatches.

  • storage_options (Hash) (defaults to: nil)

    Options that indicate how to connect to a cloud provider.

    The cloud providers currently supported are AWS, GCP, and Azure. See supported keys here:

    • aws
    • gcp
    • azure
    • Hugging Face (hf://): Accepts an API key under the token parameter: \ {'token': '...'}, or by setting the HF_TOKEN environment variable.

    If storage_options is not provided, Polars will try to infer the information from environment variables.

  • credential_provider (Object) (defaults to: "auto")

    Provide a function that can be called to provide cloud storage credentials. The function is expected to return a hash of credential keys along with an optional credential expiry time.

  • retries (Integer) (defaults to: nil)

    Number of retries if accessing a cloud instance fails.

  • file_cache_ttl (Integer) (defaults to: nil)

    Amount of time to keep downloaded cloud files since their last access time, in seconds. Uses the POLARS_FILE_CACHE_TTL environment variable (which defaults to 1 hour) if not given.

  • include_file_paths (String) (defaults to: nil)

    Include the path of the source file(s) as a column with this name.

Returns:



65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
# File 'lib/polars/io/ndjson.rb', line 65

def read_ndjson(
  source,
  schema: nil,
  schema_overrides: nil,
  infer_schema_length: N_INFER_DEFAULT,
  batch_size: 1024,
  n_rows: nil,
  low_memory: false,
  rechunk: false,
  row_index_name: nil,
  row_index_offset: 0,
  ignore_errors: false,
  storage_options: nil,
  credential_provider: "auto",
  retries: nil,
  file_cache_ttl: nil,
  include_file_paths: nil
)
  credential_provider_builder = _init_credential_provider_builder(
    credential_provider, source, storage_options, "read_ndjson"
  )

  scan_ndjson(
    source,
    schema: schema,
    schema_overrides: schema_overrides,
    infer_schema_length: infer_schema_length,
    batch_size: batch_size,
    n_rows: n_rows,
    low_memory: low_memory,
    rechunk: rechunk,
    row_index_name: row_index_name,
    row_index_offset: row_index_offset,
    ignore_errors: ignore_errors,
    include_file_paths: include_file_paths,
    retries: retries,
    storage_options: storage_options,
    credential_provider: credential_provider_builder,
    file_cache_ttl: file_cache_ttl,
  ).collect
end

#read_parquet(source, columns: nil, n_rows: nil, row_index_name: nil, row_index_offset: 0, parallel: "auto", use_statistics: true, hive_partitioning: nil, glob: true, schema: nil, hive_schema: nil, try_parse_hive_dates: true, rechunk: false, low_memory: false, storage_options: nil, credential_provider: "auto", retries: nil, include_file_paths: nil, missing_columns: "raise", allow_missing_columns: nil) ⇒ DataFrame

Read into a DataFrame from a parquet file.

Parameters:

  • source (Object)

    Path to a file or a file-like object.

  • columns (Object) (defaults to: nil)

    Columns to select. Accepts a list of column indices (starting at zero) or a list of column names.

  • n_rows (Integer) (defaults to: nil)

    Stop reading from parquet file after reading n_rows.

  • row_index_name (String) (defaults to: nil)

    If not nil, this will insert a row count column with give name into the DataFrame.

  • row_index_offset (Integer) (defaults to: 0)

    Offset to start the row_count column (only use if the name is set).

  • parallel ("auto", "columns", "row_groups", "none") (defaults to: "auto")

    This determines the direction of parallelism. 'auto' will try to determine the optimal direction.

  • use_statistics (Boolean) (defaults to: true)

    Use statistics in the parquet to determine if pages can be skipped from reading.

  • hive_partitioning (Boolean) (defaults to: nil)

    Infer statistics and schema from hive partitioned URL and use them to prune reads.

  • glob (Boolean) (defaults to: true)

    Expand path given via globbing rules.

  • schema (Object) (defaults to: nil)

    Specify the datatypes of the columns. The datatypes must match the datatypes in the file(s). If there are extra columns that are not in the file(s), consider also enabling allow_missing_columns.

  • hive_schema (Object) (defaults to: nil)

    The column names and data types of the columns by which the data is partitioned. If set to nil (default), the schema of the Hive partitions is inferred.

  • try_parse_hive_dates (Boolean) (defaults to: true)

    Whether to try parsing hive values as date/datetime types.

  • rechunk (Boolean) (defaults to: false)

    In case of reading multiple files via a glob pattern rechunk the final DataFrame into contiguous memory chunks.

  • low_memory (Boolean) (defaults to: false)

    Reduce memory pressure at the expense of performance.

  • storage_options (Hash) (defaults to: nil)

    Extra options that make sense for a particular storage connection.

  • credential_provider (Object) (defaults to: "auto")

    Provide a function that can be called to provide cloud storage credentials. The function is expected to return a hash of credential keys along with an optional credential expiry time.

  • retries (Integer) (defaults to: nil)

    Number of retries if accessing a cloud instance fails.

  • include_file_paths (String) (defaults to: nil)

    Include the path of the source file(s) as a column with this name.

  • missing_columns ('insert', 'raise') (defaults to: "raise")

    Configuration for behavior when columns defined in the schema are missing from the data:

    • insert: Inserts the missing columns using NULLs as the row values.
    • raise: Raises an error.
  • allow_missing_columns (Boolean) (defaults to: nil)

    When reading a list of parquet files, if a column existing in the first file cannot be found in subsequent files, the default behavior is to raise an error. However, if allow_missing_columns is set to true, a full-NULL column is returned instead of erroring for the files that do not contain the column.

Returns:



66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
# File 'lib/polars/io/parquet.rb', line 66

def read_parquet(
  source,
  columns: nil,
  n_rows: nil,
  row_index_name: nil,
  row_index_offset: 0,
  parallel: "auto",
  use_statistics: true,
  hive_partitioning: nil,
  glob: true,
  schema: nil,
  hive_schema: nil,
  try_parse_hive_dates: true,
  rechunk: false,
  low_memory: false,
  storage_options: nil,
  credential_provider: "auto",
  retries: nil,
  include_file_paths: nil,
  missing_columns: "raise",
  allow_missing_columns: nil
)
  lf =
    scan_parquet(
      source,
      n_rows: n_rows,
      row_index_name: row_index_name,
      row_index_offset: row_index_offset,
      parallel: parallel,
      use_statistics: use_statistics,
      hive_partitioning: hive_partitioning,
      schema: schema,
      hive_schema: hive_schema,
      try_parse_hive_dates: try_parse_hive_dates,
      rechunk: rechunk,
      low_memory: low_memory,
      cache: false,
      storage_options: storage_options,
      credential_provider: credential_provider,
      retries: retries,
      glob: glob,
      include_file_paths: include_file_paths,
      missing_columns: missing_columns,
      allow_missing_columns: allow_missing_columns
    )

  if !columns.nil?
    if Utils.is_int_sequence(columns)
      lf = lf.select(F.nth(columns))
    else
      lf = lf.select(columns)
    end
  end

  lf.collect
end

#read_parquet_metadata(source, storage_options: nil, credential_provider: "auto", retries: nil) ⇒ Hash

Note:

This functionality is considered experimental. It may be removed or changed at any point without it being considered a breaking change.

Get file-level custom metadata of a Parquet file without reading data.

Parameters:

  • source (Object)

    Path to a file or a file-like object.

  • storage_options (Hash) (defaults to: nil)

    Extra options that make sense for a particular storage connection.

  • credential_provider (Object) (defaults to: "auto")

    Provide a function that can be called to provide cloud storage credentials. The function is expected to return a hash of credential keys along with an optional credential expiry time.

  • retries (Integer) (defaults to: nil)

    Number of retries if accessing a cloud instance fails.

Returns:

  • (Hash)


155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
# File 'lib/polars/io/parquet.rb', line 155

def (
  source,
  storage_options: nil,
  credential_provider: "auto",
  retries: nil
)
  if Utils.pathlike?(source)
    source = Utils.normalize_filepath(source, check_not_directory: false)
  end

  if !retries.nil?
    msg = "the `retries` parameter was deprecated in 0.25.0; specify 'max_retries' in `storage_options` instead."
    Utils.issue_deprecation_warning(msg)
    storage_options = storage_options || {}
    storage_options["max_retries"] = retries
  end

  credential_provider_builder = _init_credential_provider_builder(
    credential_provider, source, storage_options, "scan_parquet"
  )

  Plr.(
    source,
    storage_options,
    credential_provider_builder
  )
end

#read_parquet_schema(source) ⇒ Schema

Get a schema of the Parquet file without reading data.

Parameters:

  • source (Object)

    Path to a file or a file-like object.

Returns:



129
130
131
132
133
134
135
# File 'lib/polars/io/parquet.rb', line 129

def read_parquet_schema(source)
  if Utils.pathlike?(source)
    source = Utils.normalize_filepath(source)
  end

  scan_parquet(source).collect_schema
end

#scan_csv(source, has_header: true, separator: ",", comment_prefix: nil, quote_char: '"', skip_rows: 0, skip_lines: 0, schema: nil, schema_overrides: nil, null_values: nil, missing_utf8_is_empty_string: false, ignore_errors: false, cache: true, with_column_names: nil, infer_schema: true, infer_schema_length: N_INFER_DEFAULT, n_rows: nil, encoding: "utf8", low_memory: false, rechunk: false, skip_rows_after_header: 0, row_index_name: nil, row_index_offset: 0, try_parse_dates: false, eol_char: "\n", new_columns: nil, raise_if_empty: true, truncate_ragged_lines: false, decimal_comma: false, glob: true, storage_options: nil, credential_provider: "auto", retries: nil, file_cache_ttl: nil, include_file_paths: nil) ⇒ LazyFrame

Lazily read from a CSV file or multiple files via glob patterns.

This allows the query optimizer to push down predicates and projections to the scan level, thereby potentially reducing memory overhead.

Parameters:

  • source (Object)

    Path to a file.

  • has_header (Boolean) (defaults to: true)

    Indicate if the first row of dataset is a header or not. If set to false, column names will be autogenerated in the following format: column_x, with x being an enumeration over every column in the dataset starting at 1.

  • separator (String) (defaults to: ",")

    Single byte character to use as separator in the file.

  • comment_prefix (String) (defaults to: nil)

    A string used to indicate the start of a comment line. Comment lines are skipped during parsing. Common examples of comment prefixes are # and //.

  • quote_char (String) (defaults to: '"')

    Single byte character used for csv quoting. Set to nil to turn off special handling and escaping of quotes.

  • skip_rows (Integer) (defaults to: 0)

    Start reading after skip_rows lines. The header will be parsed at this offset.

  • skip_lines (Integer) (defaults to: 0)

    Start reading after skip_lines lines. The header will be parsed at this offset. Note that CSV escaping will not be respected when skipping lines. If you want to skip valid CSV rows, use skip_rows.

  • schema (Object) (defaults to: nil)

    Provide the schema. This means that polars doesn't do schema inference. This argument expects the complete schema, whereas schema_overrides can be used to partially overwrite a schema. Note that the order of the columns in the provided schema must match the order of the columns in the CSV being read.

  • schema_overrides (Object) (defaults to: nil)

    Overwrite dtypes for specific or all columns during schema inference.

  • null_values (Object) (defaults to: nil)

    Values to interpret as null values. You can provide a:

    • String: All values equal to this string will be null.
    • Array: All values equal to any string in this array will be null.
    • Hash: A hash that maps column name to a null value string.
  • missing_utf8_is_empty_string (Boolean) (defaults to: false)

    By default a missing value is considered to be null; if you would prefer missing utf8 values to be treated as the empty string you can set this param true.

  • ignore_errors (Boolean) (defaults to: false)

    Try to keep reading lines if some lines yield errors. First try infer_schema_length: 0 to read all columns as :str to check which values might cause an issue.

  • cache (Boolean) (defaults to: true)

    Cache the result after reading.

  • with_column_names (Object) (defaults to: nil)

    Apply a function over the column names. This can be used to update a schema just in time, thus before scanning.

  • infer_schema (Boolean) (defaults to: true)

    When true, the schema is inferred from the data using the first infer_schema_length rows. When false, the schema is not inferred and will be Polars::String if not specified in schema or schema_overrides.

  • infer_schema_length (Integer) (defaults to: N_INFER_DEFAULT)

    Maximum number of lines to read to infer schema. If set to 0, all columns will be read as :str. If set to nil, a full table scan will be done (slow).

  • n_rows (Integer) (defaults to: nil)

    Stop reading from CSV file after reading n_rows.

  • encoding ("utf8", "utf8-lossy") (defaults to: "utf8")

    Lossy means that invalid utf8 values are replaced with characters.

  • low_memory (Boolean) (defaults to: false)

    Reduce memory usage in expense of performance.

  • rechunk (Boolean) (defaults to: false)

    Reallocate to contiguous memory when all chunks/ files are parsed.

  • skip_rows_after_header (Integer) (defaults to: 0)

    Skip this number of rows when the header is parsed.

  • row_index_name (String) (defaults to: nil)

    If not nil, this will insert a row count column with the given name into the DataFrame.

  • row_index_offset (Integer) (defaults to: 0)

    Offset to start the row_count column (only used if the name is set).

  • try_parse_dates (Boolean) (defaults to: false)

    Try to automatically parse dates. If this does not succeed, the column remains of data type :str.

  • eol_char (String) (defaults to: "\n")

    Single byte end of line character.

  • new_columns (Array) (defaults to: nil)

    Provide an explicit list of string column names to use (for example, when scanning a headerless CSV file). If the given list is shorter than the width of the DataFrame the remaining columns will have their original name.

  • raise_if_empty (Boolean) (defaults to: true)

    When there is no data in the source, NoDataError is raised. If this parameter is set to false, an empty LazyFrame (with no columns) is returned instead.

  • truncate_ragged_lines (Boolean) (defaults to: false)

    Truncate lines that are longer than the schema.

  • decimal_comma (Boolean) (defaults to: false)

    Parse floats using a comma as the decimal separator instead of a period.

  • glob (Boolean) (defaults to: true)

    Expand path given via globbing rules.

  • storage_options (Hash) (defaults to: nil)

    Options that indicate how to connect to a cloud provider.

    The cloud providers currently supported are AWS, GCP, and Azure. See supported keys here:

    • aws
    • gcp
    • azure
    • Hugging Face (hf://): Accepts an API key under the token parameter: \ {'token': '...'}, or by setting the HF_TOKEN environment variable.

    If storage_options is not provided, Polars will try to infer the information from environment variables.

  • credential_provider (Object) (defaults to: "auto")

    Provide a function that can be called to provide cloud storage credentials. The function is expected to return a hash of credential keys along with an optional credential expiry time.

  • retries (Integer) (defaults to: nil)

    Number of retries if accessing a cloud instance fails.

  • file_cache_ttl (Integer) (defaults to: nil)

    Amount of time to keep downloaded cloud files since their last access time, in seconds. Uses the POLARS_FILE_CACHE_TTL environment variable (which defaults to 1 hour) if not given.

  • include_file_paths (String) (defaults to: nil)

    Include the path of the source file(s) as a column with this name.

Returns:



653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
# File 'lib/polars/io/csv.rb', line 653

def scan_csv(
  source,
  has_header: true,
  separator: ",",
  comment_prefix: nil,
  quote_char: '"',
  skip_rows: 0,
  skip_lines: 0,
  schema: nil,
  schema_overrides: nil,
  null_values: nil,
  missing_utf8_is_empty_string: false,
  ignore_errors: false,
  cache: true,
  with_column_names: nil,
  infer_schema: true,
  infer_schema_length: N_INFER_DEFAULT,
  n_rows: nil,
  encoding: "utf8",
  low_memory: false,
  rechunk: false,
  skip_rows_after_header: 0,
  row_index_name: nil,
  row_index_offset: 0,
  try_parse_dates: false,
  eol_char: "\n",
  new_columns: nil,
  raise_if_empty: true,
  truncate_ragged_lines: false,
  decimal_comma: false,
  glob: true,
  storage_options: nil,
  credential_provider: "auto",
  retries: nil,
  file_cache_ttl: nil,
  include_file_paths: nil
)
  if new_columns&.any? && schema_overrides.is_a?(::Array)
    msg = "expected 'schema_overrides' hash, found #{schema_overrides.inspect}"
    raise TypeError, msg
  elsif new_columns&.any?
    if with_column_names
      msg = "cannot set both `with_column_names` and `new_columns`; mutually exclusive"
      raise ArgumentError, msg
    end
    if schema_overrides && schema_overrides.is_a?(::Array)
      schema_overrides = new_columns.zip(schema_overrides).to_h
    end

    # wrap new column names as a callable
    with_column_names = lambda do |cols|
      if cols.length > new_columns.length
        new_columns + cols[new_columns.length..]
      else
        new_columns
      end
    end
  end

  Utils._check_arg_is_1byte("separator", separator, false)
  Utils._check_arg_is_1byte("quote_char", quote_char, true)

  if Utils.pathlike?(source)
    source = Utils.normalize_filepath(source)
  end

  if !infer_schema
    infer_schema_length = 0
  end

  if !retries.nil?
    msg = "the `retries` parameter was deprecated in 0.25.0; specify 'max_retries' in `storage_options` instead."
    Utils.issue_deprecation_warning(msg)
    storage_options = storage_options || {}
    storage_options["max_retries"] = retries
  end

  if !file_cache_ttl.nil?
    msg = "the `file_cache_ttl` parameter was deprecated in 0.25.0; specify 'file_cache_ttl' in `storage_options` instead."
    Utils.issue_deprecation_warning(msg)
    storage_options = storage_options || {}
    storage_options["file_cache_ttl"] = file_cache_ttl
  end

  credential_provider_builder = _init_credential_provider_builder(
    credential_provider, source, storage_options, "scan_csv"
  )

  _scan_csv_impl(
    source,
    has_header: has_header,
    separator: separator,
    comment_prefix: comment_prefix,
    quote_char: quote_char,
    skip_rows: skip_rows,
    skip_lines: skip_lines,
    schema_overrides: schema_overrides,
    schema: schema,
    null_values: null_values,
    ignore_errors: ignore_errors,
    cache: cache,
    with_column_names: with_column_names,
    infer_schema_length: infer_schema_length,
    n_rows: n_rows,
    low_memory: low_memory,
    rechunk: rechunk,
    skip_rows_after_header: skip_rows_after_header,
    encoding: encoding,
    row_index_name: row_index_name,
    row_index_offset: row_index_offset,
    try_parse_dates: try_parse_dates,
    eol_char: eol_char,
    raise_if_empty: raise_if_empty,
    truncate_ragged_lines: truncate_ragged_lines,
    decimal_comma: decimal_comma,
    glob: glob,
    storage_options: storage_options,
    credential_provider: credential_provider_builder,
    include_file_paths: include_file_paths
  )
end

#scan_delta(source, version: nil, storage_options: nil, delta_table_options: nil, rechunk: nil) ⇒ LazyFrame

Lazily read from a Delta lake table.

Parameters:

  • source (Object)

    DeltaTable or a Path or URI to the root of the Delta lake table.

  • version (Object) (defaults to: nil)

    Numerical version or timestamp version of the Delta lake table.

  • storage_options (Hash) (defaults to: nil)

    Extra options for the storage backends supported by deltalake-rb.

  • delta_table_options (Hash) (defaults to: nil)

    Additional keyword arguments while reading a Delta lake Table.

  • rechunk (Boolean) (defaults to: nil)

    Make sure that all columns are contiguous in memory by aggregating the chunks into a single array.

Returns:



58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
# File 'lib/polars/io/delta.rb', line 58

def scan_delta(
  source,
  version: nil,
  storage_options: nil,
  delta_table_options: nil,
  rechunk: nil
)
  dl_tbl =
    _get_delta_lake_table(
      source,
      version: version,
      storage_options: storage_options,
      delta_table_options: delta_table_options
    )

  dl_tbl.to_polars(eager: false, rechunk: rechunk || false)
end

#scan_iceberg(source, snapshot_id: nil, storage_options: nil) ⇒ LazyFrame

Lazily read from an Apache Iceberg table.

Parameters:

  • source (Object)

    A Iceberg Ruby table, or a direct path to the metadata.

  • snapshot_id (Integer) (defaults to: nil)

    The snapshot ID to scan from.

  • storage_options (Hash) (defaults to: nil)

    Extra options for the storage backends.

Returns:



13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
# File 'lib/polars/io/iceberg.rb', line 13

def scan_iceberg(
  source,
  snapshot_id: nil,
  storage_options: nil
)
  require "iceberg"

  unless source.is_a?(Iceberg::Table)
    raise Todo
  end

  dataset =
    IcebergDataset.new(
      source,
      snapshot_id:,
      storage_options:
    )

  dataset.to_lazyframe
end

#scan_ipc(source, n_rows: nil, cache: true, rechunk: false, row_index_name: nil, row_index_offset: 0, glob: true, storage_options: nil, credential_provider: "auto", retries: nil, file_cache_ttl: nil, hive_partitioning: nil, hive_schema: nil, try_parse_hive_dates: true, include_file_paths: nil, _record_batch_statistics: false) ⇒ LazyFrame

Lazily read from an Arrow IPC (Feather v2) file or multiple files via glob patterns.

This allows the query optimizer to push down predicates and projections to the scan level, thereby potentially reducing memory overhead.

Parameters:

  • source (String)

    Path to a IPC file.

  • n_rows (Integer) (defaults to: nil)

    Stop reading from IPC file after reading n_rows.

  • cache (Boolean) (defaults to: true)

    Cache the result after reading.

  • rechunk (Boolean) (defaults to: false)

    Reallocate to contiguous memory when all chunks/ files are parsed.

  • row_index_name (String) (defaults to: nil)

    If not nil, this will insert a row count column with give name into the DataFrame.

  • row_index_offset (Integer) (defaults to: 0)

    Offset to start the row_count column (only use if the name is set).

  • glob (Boolean) (defaults to: true)

    Expand path given via globbing rules.

  • storage_options (Hash) (defaults to: nil)

    Extra options that make sense for a particular storage connection.

  • credential_provider (Object) (defaults to: "auto")

    Provide a function that can be called to provide cloud storage credentials. The function is expected to return a hash of credential keys along with an optional credential expiry time.

  • retries (Integer) (defaults to: nil)

    Number of retries if accessing a cloud instance fails.

  • file_cache_ttl (Integer) (defaults to: nil)

    Amount of time to keep downloaded cloud files since their last access time, in seconds. Uses the POLARS_FILE_CACHE_TTL environment variable (which defaults to 1 hour) if not given.

  • hive_partitioning (Boolean) (defaults to: nil)

    Infer statistics and schema from Hive partitioned URL and use them to prune reads. This is unset by default (i.e. nil), meaning it is automatically enabled when a single directory is passed, and otherwise disabled.

  • hive_schema (Hash) (defaults to: nil)

    The column names and data types of the columns by which the data is partitioned. If set to nil (default), the schema of the Hive partitions is inferred.

  • try_parse_hive_dates (Boolean) (defaults to: true)

    Whether to try parsing hive values as date/datetime types.

  • include_file_paths (String) (defaults to: nil)

    Include the path of the source file(s) as a column with this name.

Returns:



218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
# File 'lib/polars/io/ipc.rb', line 218

def scan_ipc(
  source,
  n_rows: nil,
  cache: true,
  rechunk: false,
  row_index_name: nil,
  row_index_offset: 0,
  glob: true,
  storage_options: nil,
  credential_provider: "auto",
  retries: nil,
  file_cache_ttl: nil,
  hive_partitioning: nil,
  hive_schema: nil,
  try_parse_hive_dates: true,
  include_file_paths: nil,
  _record_batch_statistics: false
)
  sources = get_sources(source)

  if !retries.nil?
    msg = "the `retries` parameter was deprecated in 0.25.0; specify 'max_retries' in `storage_options` instead."
    Utils.issue_deprecation_warning(msg)
    storage_options = storage_options || {}
    storage_options["max_retries"] = retries
  end

  if !file_cache_ttl.nil?
    msg = "the `file_cache_ttl` parameter was deprecated in 0.25.0; specify 'file_cache_ttl' in `storage_options` instead."
    Utils.issue_deprecation_warning(msg)
    storage_options = storage_options || {}
    storage_options["file_cache_ttl"] = file_cache_ttl
  end

  credential_provider_builder = _init_credential_provider_builder(
    credential_provider, sources, storage_options, "scan_parquet"
  )

  rblf =
    RbLazyFrame.new_from_ipc(
      sources,
      _record_batch_statistics,
      ScanOptions.new(
        row_index: !row_index_name.nil? ? [row_index_name, row_index_offset] : nil,
        pre_slice: !n_rows.nil? ? [0, n_rows] : nil,
        include_file_paths: include_file_paths,
        glob: glob,
        hive_partitioning: hive_partitioning,
        hive_schema: hive_schema,
        try_parse_hive_dates: try_parse_hive_dates,
        rechunk: rechunk,
        cache: cache,
        storage_options: !storage_options.nil? ? storage_options.to_a : nil,
        credential_provider: credential_provider_builder
      )
    )
  Utils.wrap_ldf(rblf)
end

#scan_ndjson(source, schema: nil, schema_overrides: nil, infer_schema_length: N_INFER_DEFAULT, batch_size: 1024, n_rows: nil, low_memory: false, rechunk: false, row_index_name: nil, row_index_offset: 0, ignore_errors: false, storage_options: nil, credential_provider: "auto", retries: nil, file_cache_ttl: nil, include_file_paths: nil) ⇒ LazyFrame

Lazily read from a newline delimited JSON file.

This allows the query optimizer to push down predicates and projections to the scan level, thereby potentially reducing memory overhead.

Parameters:

  • source (String)

    Path to a file.

  • schema (Object) (defaults to: nil)

    The DataFrame schema may be declared in several ways:

    • As a dict of \{name:type} pairs; if type is nil, it will be auto-inferred.
    • As a list of column names; in this case types are automatically inferred.
    • As a list of (name,type) pairs; this is equivalent to the hash form.

    If you supply a list of column names that does not match the names in the underlying data, the names given here will overwrite them. The number of names given in the schema should match the underlying data dimensions.

  • schema_overrides (Hash) (defaults to: nil)

    Support type specification or override of one or more columns; note that any dtypes inferred from the schema param will be overridden.

  • infer_schema_length (Integer) (defaults to: N_INFER_DEFAULT)

    Infer the schema length from the first infer_schema_length rows.

  • batch_size (Integer) (defaults to: 1024)

    Number of rows to read in each batch.

  • n_rows (Integer) (defaults to: nil)

    Stop reading from JSON file after reading n_rows.

  • low_memory (Boolean) (defaults to: false)

    Reduce memory pressure at the expense of performance.

  • rechunk (Boolean) (defaults to: false)

    Reallocate to contiguous memory when all chunks/ files are parsed.

  • row_index_name (String) (defaults to: nil)

    If not nil, this will insert a row count column with give name into the DataFrame.

  • row_index_offset (Integer) (defaults to: 0)

    Offset to start the row_count column (only use if the name is set).

  • ignore_errors (Boolean) (defaults to: false)

    Return Null if parsing fails because of schema mismatches.

  • storage_options (Hash) (defaults to: nil)

    Options that indicate how to connect to a cloud provider.

    The cloud providers currently supported are AWS, GCP, and Azure. See supported keys here:

    • aws
    • gcp
    • azure
    • Hugging Face (hf://): Accepts an API key under the token parameter: \ {'token': '...'}, or by setting the HF_TOKEN environment variable.

    If storage_options is not provided, Polars will try to infer the information from environment variables.

  • credential_provider (Object) (defaults to: "auto")

    Provide a function that can be called to provide cloud storage credentials. The function is expected to return a hash of credential keys along with an optional credential expiry time.

  • retries (Integer) (defaults to: nil)

    Number of retries if accessing a cloud instance fails.

  • file_cache_ttl (Integer) (defaults to: nil)

    Amount of time to keep downloaded cloud files since their last access time, in seconds. Uses the POLARS_FILE_CACHE_TTL environment variable (which defaults to 1 hour) if not given.

  • include_file_paths (String) (defaults to: nil)

    Include the path of the source file(s) as a column with this name.

Returns:



172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
# File 'lib/polars/io/ndjson.rb', line 172

def scan_ndjson(
  source,
  schema: nil,
  schema_overrides: nil,
  infer_schema_length: N_INFER_DEFAULT,
  batch_size: 1024,
  n_rows: nil,
  low_memory: false,
  rechunk: false,
  row_index_name: nil,
  row_index_offset: 0,
  ignore_errors: false,
  storage_options: nil,
  credential_provider: "auto",
  retries: nil,
  file_cache_ttl: nil,
  include_file_paths: nil
)
  sources = []
  if Utils.pathlike?(source)
    source = Utils.normalize_filepath(source)
  elsif source.is_a?(::Array)
    if Utils.is_path_or_str_sequence(source)
      sources = source.map { |s| Utils.normalize_filepath(s) }
    else
      sources = source
    end

    source = nil
  end

  if infer_schema_length == 0
    msg = "'infer_schema_length' should be positive"
    raise ArgumentError, msg
  end

  if !retries.nil?
    msg = "the `retries` parameter was deprecated in 0.25.0; specify 'max_retries' in `storage_options` instead."
    Utils.issue_deprecation_warning(msg)
    storage_options = storage_options || {}
    storage_options["max_retries"] = retries
  end

  if !file_cache_ttl.nil?
    msg = "the `file_cache_ttl` parameter was deprecated in 0.25.0; specify 'file_cache_ttl' in `storage_options` instead."
    Utils.issue_deprecation_warning(msg)
    storage_options = storage_options || {}
    storage_options["file_cache_ttl"] = file_cache_ttl
  end

  credential_provider_builder = _init_credential_provider_builder(
    credential_provider, source, storage_options, "scan_ndjson"
  )

  rblf =
    RbLazyFrame.new_from_ndjson(
      source,
      sources,
      infer_schema_length,
      schema,
      schema_overrides,
      batch_size,
      n_rows,
      low_memory,
      rechunk,
      Utils.parse_row_index_args(row_index_name, row_index_offset),
      ignore_errors,
      include_file_paths,
      storage_options,
      credential_provider_builder
    )
  Utils.wrap_ldf(rblf)
end

#scan_parquet(source, n_rows: nil, row_index_name: nil, row_index_offset: 0, parallel: "auto", use_statistics: true, hive_partitioning: nil, glob: true, hidden_file_prefix: nil, schema: nil, hive_schema: nil, try_parse_hive_dates: true, rechunk: false, low_memory: false, cache: true, storage_options: nil, credential_provider: "auto", retries: nil, include_file_paths: nil, missing_columns: "raise", allow_missing_columns: nil, extra_columns: "raise", cast_options: nil, _column_mapping: nil, _default_values: nil, _deletion_files: nil, _table_statistics: nil, _row_count: nil) ⇒ LazyFrame

Lazily read from a parquet file or multiple files via glob patterns.

This allows the query optimizer to push down predicates and projections to the scan level, thereby potentially reducing memory overhead.

Parameters:

  • source (Object)

    Path to a file or a file-like object.

  • n_rows (Integer) (defaults to: nil)

    Stop reading from parquet file after reading n_rows.

  • row_index_name (String) (defaults to: nil)

    If not nil, this will insert a row count column with give name into the DataFrame.

  • row_index_offset (Integer) (defaults to: 0)

    Offset to start the row_count column (only use if the name is set).

  • parallel ("auto", "columns", "row_groups", "none") (defaults to: "auto")

    This determines the direction of parallelism. 'auto' will try to determine the optimal direction.

  • use_statistics (Boolean) (defaults to: true)

    Use statistics in the parquet to determine if pages can be skipped from reading.

  • hive_partitioning (Boolean) (defaults to: nil)

    Infer statistics and schema from hive partitioned URL and use them to prune reads.

  • glob (Boolean) (defaults to: true)

    Expand path given via globbing rules.

  • hidden_file_prefix (Boolean) (defaults to: nil)

    Skip reading files whose names begin with the specified prefixes.

  • schema (Object) (defaults to: nil)

    Specify the datatypes of the columns. The datatypes must match the datatypes in the file(s). If there are extra columns that are not in the file(s), consider also enabling allow_missing_columns.

  • hive_schema (Object) (defaults to: nil)

    The column names and data types of the columns by which the data is partitioned. If set to nil (default), the schema of the Hive partitions is inferred.

  • try_parse_hive_dates (Boolean) (defaults to: true)

    Whether to try parsing hive values as date/datetime types.

  • rechunk (Boolean) (defaults to: false)

    In case of reading multiple files via a glob pattern rechunk the final DataFrame into contiguous memory chunks.

  • low_memory (Boolean) (defaults to: false)

    Reduce memory pressure at the expense of performance.

  • cache (Boolean) (defaults to: true)

    Cache the result after reading.

  • storage_options (Hash) (defaults to: nil)

    Extra options that make sense for a particular storage connection.

  • credential_provider (Object) (defaults to: "auto")

    Provide a function that can be called to provide cloud storage credentials. The function is expected to return a hash of credential keys along with an optional credential expiry time.

  • retries (Integer) (defaults to: nil)

    Number of retries if accessing a cloud instance fails.

  • include_file_paths (String) (defaults to: nil)

    Include the path of the source file(s) as a column with this name.

  • missing_columns ('insert', 'raise') (defaults to: "raise")

    Configuration for behavior when columns defined in the schema are missing from the data:

    • insert: Inserts the missing columns using NULLs as the row values.
    • raise: Raises an error.
  • allow_missing_columns (Boolean) (defaults to: nil)

    When reading a list of parquet files, if a column existing in the first file cannot be found in subsequent files, the default behavior is to raise an error. However, if allow_missing_columns is set to true, a full-NULL column is returned instead of erroring for the files that do not contain the column.

  • extra_columns ('ignore', 'raise') (defaults to: "raise")

    Configuration for behavior when extra columns outside of the defined schema are encountered in the data:

    • ignore: Silently ignores.
    • raise: Raises an error.
  • cast_options (Object) (defaults to: nil)

    Configuration for column type-casting during scans. Useful for datasets containing files that have differing schemas.

Returns:



258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
# File 'lib/polars/io/parquet.rb', line 258

def scan_parquet(
  source,
  n_rows: nil,
  row_index_name: nil,
  row_index_offset: 0,
  parallel: "auto",
  use_statistics: true,
  hive_partitioning: nil,
  glob: true,
  hidden_file_prefix: nil,
  schema: nil,
  hive_schema: nil,
  try_parse_hive_dates: true,
  rechunk: false,
  low_memory: false,
  cache: true,
  storage_options: nil,
  credential_provider: "auto",
  retries: nil,
  include_file_paths: nil,
  missing_columns: "raise",
  allow_missing_columns: nil,
  extra_columns: "raise",
  cast_options: nil,
  _column_mapping: nil,
  _default_values: nil,
  _deletion_files: nil,
  _table_statistics: nil,
  _row_count: nil
)
  if !schema.nil?
    msg = "the `schema` parameter of `scan_parquet` is considered unstable."
    Utils.issue_unstable_warning(msg)
  end

  if !hive_schema.nil?
    msg = "the `hive_schema` parameter of `scan_parquet` is considered unstable."
    Utils.issue_unstable_warning(msg)
  end

  if !cast_options.nil?
    msg = "The `cast_options` parameter of `scan_parquet` is considered unstable."
    Utils.issue_unstable_warning(msg)
  end

  if !hidden_file_prefix.nil?
    msg = "The `hidden_file_prefix` parameter of `scan_parquet` is considered unstable."
    Utils.issue_unstable_warning(msg)
  end

  if !allow_missing_columns.nil?
    Utils.issue_deprecation_warning(
      "the parameter `allow_missing_columns` for `scan_parquet` is deprecated. " +
      "Use the parameter `missing_columns` instead and pass one of " +
      "`('insert', 'raise')`."
    )

    missing_columns = allow_missing_columns ? "insert" : "raise"
  end

  if !retries.nil?
    msg = "the `retries` parameter was deprecated in 0.25.0; specify 'max_retries' in `storage_options` instead."
    Utils.issue_deprecation_warning(msg)
    storage_options = storage_options || {}
    storage_options["max_retries"] = retries
  end

  sources = get_sources(source)

  credential_provider_builder =
    _init_credential_provider_builder(
      credential_provider,
      sources,
      storage_options,
      "scan_parquet"
    )

  rblf =
    RbLazyFrame.new_from_parquet(
      sources,
      schema,
      ScanOptions.new(
        row_index: !row_index_name.nil? ? [row_index_name, row_index_offset] : nil,
        pre_slice: !n_rows.nil? ? [0, n_rows] : nil,
        cast_options: cast_options,
        extra_columns: extra_columns,
        missing_columns: missing_columns,
        include_file_paths: include_file_paths,
        glob: glob,
        hidden_file_prefix: hidden_file_prefix.is_a?(::String) ? [hidden_file_prefix] : hidden_file_prefix,
        hive_partitioning: hive_partitioning,
        hive_schema: hive_schema,
        try_parse_hive_dates: try_parse_hive_dates,
        rechunk: rechunk,
        cache: cache,
        storage_options: storage_options ? storage_options.map { |k, v| [k.to_s, v.to_s] } : nil,
        credential_provider: credential_provider_builder,
        column_mapping: _column_mapping,
        default_values: _default_values,
        deletion_files: _deletion_files,
        table_statistics: _table_statistics,
        row_count: _row_count
      ),
      parallel,
      low_memory,
      use_statistics
    )
  Utils.wrap_ldf(rblf)
end