polars.read_ndjson#
- polars.read_ndjson(
- source: str | Path | list[str] | list[Path] | IOBase | bytes,
- *,
- schema: SchemaDefinition | None = None,
- schema_overrides: SchemaDefinition | None = None,
- infer_schema_length: int | None = 100,
- batch_size: int | None = 1024,
- n_rows: int | None = None,
- low_memory: bool = False,
- rechunk: bool = False,
- row_index_name: str | None = None,
- row_index_offset: int = 0,
- ignore_errors: bool = False,
- storage_options: dict[str, Any] | None = None,
- credential_provider: CredentialProviderFunction | Literal['auto'] | None = 'auto',
- retries: int = 2,
- file_cache_ttl: int | None = None,
- include_file_paths: str | None = None,
从以换行符分隔的JSON文件中读取到DataFrame。
- Parameters:
- source
文件路径或类文件对象(“类文件对象”指的是具有
read()方法的对象,例如内置的open函数文件句柄,或BytesIO实例)。对于类文件对象,读取后流位置可能不会相应更新。- schemaSequence of str, (str,DataType) pairs, or a {str:DataType,} dict
DataFrame的模式可以通过几种方式声明:
作为一个{名称:类型}对的字典;如果类型为None,它将自动推断。
作为列名的列表;在这种情况下,类型会自动推断。
作为(名称,类型)对的列表;这等同于字典形式。
如果您提供的列名列表与基础数据中的名称不匹配,此处提供的名称将覆盖它们。模式中提供的名称数量应与基础数据的维度相匹配。
- schema_overridesdict, default None
支持类型指定或覆盖一个或多个列;请注意,从schema参数推断出的任何dtypes将被覆盖。
- infer_schema_length
用于模式推断的最大扫描行数。 如果设置为
None,可能会扫描完整的数据(这很慢)。- batch_size
每批读取的行数。
- n_rows
在读取
n_rows后停止从 JSON 文件读取。- low_memory
以性能为代价减少内存压力。
- rechunk
当所有块/文件都被解析时,重新分配到连续的内存。
- row_index_name
如果不是None,这将在DataFrame中插入一个具有给定名称的行索引列
- row_index_offset
开始行索引列的偏移量(仅在设置了名称时使用)
- ignore_errors
如果由于模式不匹配导致解析失败,则返回
Null。- storage_options
指示如何连接到云提供商的选项。
目前支持的云提供商有AWS、GCP和Azure。 查看支持的密钥请点击这里:
如果未提供
storage_options,Polars将尝试从环境变量中推断信息。- credential_provider
提供一个可以被调用的函数来提供云存储凭证。该函数预期返回一个包含凭证键的字典以及一个可选的凭证过期时间。
警告
此功能被视为不稳定。它可能会在任何时候更改,而不被视为破坏性更改。
- retries
如果访问云实例失败,重试次数。
- file_cache_ttl
自上次访问时间以来保留下载的云文件的时间量,以秒为单位。如果未给出,则使用
POLARS_FILE_CACHE_TTL环境变量(默认为1小时)。- include_file_paths
将源文件的路径作为一列包含在此名称中。
示例
>>> from io import StringIO >>> json_str = '{"foo":1,"bar":6}\n{"foo":2,"bar":7}\n{"foo":3,"bar":8}\n' >>> pl.read_ndjson(StringIO(json_str)) shape: (3, 2) ┌─────┬─────┐ │ foo ┆ bar │ │ --- ┆ --- │ │ i64 ┆ i64 │ ╞═════╪═════╡ │ 1 ┆ 6 │ │ 2 ┆ 7 │ │ 3 ┆ 8 │ └─────┴─────┘