polars.scan_csv#

polars.scan_csv(
source: str | Path | IO[str] | IO[bytes] | bytes | list[str] | list[Path] | list[IO[str]] | list[IO[bytes]] | list[bytes],
*,
has_header: bool = True,
separator: str = ',',
comment_prefix: str | None = None,
quote_char: str | None = '"',
skip_rows: int = 0,
skip_lines: int = 0,
schema: SchemaDict | None = None,
schema_overrides: SchemaDict | Sequence[PolarsDataType] | None = None,
null_values: str | Sequence[str] | dict[str, str] | None = None,
missing_utf8_is_empty_string: bool = False,
ignore_errors: bool = False,
cache: bool = True,
with_column_names: Callable[[list[str]], list[str]] | None = None,
infer_schema: bool = True,
infer_schema_length: int | None = 100,
n_rows: int | None = None,
encoding: CsvEncoding = 'utf8',
low_memory: bool = False,
rechunk: bool = False,
skip_rows_after_header: int = 0,
row_index_name: str | None = None,
row_index_offset: int = 0,
try_parse_dates: bool = False,
eol_char: str = '\n',
new_columns: Sequence[str] | None = None,
raise_if_empty: bool = True,
truncate_ragged_lines: bool = False,
decimal_comma: bool = False,
glob: bool = True,
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,
) LazyFrame[source]#

通过通配符模式从CSV文件或多个文件中懒加载读取。

这允许查询优化器将谓词和投影下推到扫描级别,从而可能减少内存开销。

Parameters:
source

文件或目录的路径 当需要为扫描云位置进行身份验证时,请参阅 storage_options 参数。

has_header

指示数据集的第一行是否为标题。如果设置为False,列名将自动生成,格式如下:column_x,其中x是数据集中每一列的枚举,从1开始。

separator

用作文件中分隔符的单字节字符。

comment_prefix

用于指示注释行开始的字符串。在解析过程中,注释行会被跳过。常见的注释前缀示例有 #//

quote_char

用于CSV引用的单字节字符,默认值为"。 设置为None以关闭引号的特殊处理和转义。

skip_rows

skip_rows行之后开始读取。表头将在此偏移量处解析。请注意,我们在跳过行时尊重CSV的转义/注释。如果您只想通过换行符跳过,请使用skip_lines

skip_lines

skip_lines行之后开始读取。头部信息将在此偏移量处解析。请注意,跳过行时不会考虑CSV转义。如果你想跳过有效的CSV行,请使用skip_rows

schema

提供模式。这意味着polars不会进行模式推断。 此参数期望完整的模式,而schema_overrides可以 用于部分覆盖模式。

schema_overrides

在推理期间覆盖数据类型;应该是一个{列名:数据类型,}字典,或者如果提供字符串列表给new_columns,则应该是相同长度的数据类型列表。

null_values

要解释为空值的值。你可以提供一个:

  • str: 所有等于此字符串的值都将为空。

  • List[str]: 所有等于此列表中任何字符串的值都将为空。

  • Dict[str, str]: 一个将列名映射到空值字符串的字典。

missing_utf8_is_empty_string

默认情况下,缺失值被视为 null;如果您希望将缺失的 utf8 值视为空字符串,可以将此参数设置为 True。

ignore_errors

如果某些行产生错误,请尝试继续读取行。 首先尝试 infer_schema=False 将所有列读取为 pl.String 以检查哪些值可能引起问题。

cache

读取后缓存结果。

with_column_names

在列名确定时即时应用一个函数;此函数将接收(并应返回)一个列名列表。

infer_schema

True 时,模式将从数据中使用前 infer_schema_length 行推断出来。 当 False 时,模式不会被推断,如果未在 schemaschema_overrides 中指定,则默认为 pl.String

infer_schema_length

用于模式推断的最大扫描行数。 如果设置为None,可能会扫描完整数据(这很慢)。 设置infer_schema=False将所有列读取为pl.String

n_rows

在读取 n_rows 后停止从 CSV 文件读取。

encoding{‘utf8’, ‘utf8-lossy’}

有损意味着无效的utf8值将被替换为字符。默认为“utf8”。

low_memory

以性能为代价减少内存压力。

rechunk

当所有块/文件都被解析时,重新分配到连续的内存。

skip_rows_after_header

解析标题时跳过此行数。

row_index_name

如果不为None,这将在DataFrame中插入一个具有给定名称的行索引列。

row_index_offset

开始行索引列的偏移量(仅在设置了名称时使用)。

try_parse_dates

尝试自动解析日期。大多数类似ISO8601的格式可以被推断出来,以及其他一些格式。如果解析不成功,该列将保持数据类型为pl.String

eol_char

单字节行结束符(默认:n)。当遇到具有Windows行结束符(rn)的文件时,可以使用默认的n。在处理时,多余的r将被移除。

new_columns

提供一个明确的字符串列名列表以供使用(例如,在扫描无标题的CSV文件时)。如果给定的列表比DataFrame的宽度短,则剩余的列将保留其原始名称。

raise_if_empty

当源中没有数据时,会引发NoDataError。如果此参数设置为False,则返回一个空的LazyFrame(没有列)。

truncate_ragged_lines

截断比模式更长的行。

decimal_comma

使用逗号作为小数分隔符而不是句点来解析浮点数。

glob

通过通配符规则扩展路径。

storage_options

指示如何连接到云提供商的选项。

目前支持的云提供商有AWS、GCP和Azure。 查看支持的密钥请点击这里:

  • aws

  • gcp

  • azure

  • Hugging Face (hf://): 接受在 token 参数下的 API 密钥:{'token': '...'},或者通过设置 HF_TOKEN 环境变量。

如果未提供storage_options,Polars将尝试从环境变量中推断信息。

credential_provider

提供一个可以被调用的函数来提供云存储凭证。该函数预期返回一个包含凭证键的字典以及一个可选的凭证过期时间。

警告

此功能被视为不稳定。它可能会在任何时候更改,而不被视为破坏性更改。

retries

如果访问云实例失败,重试次数。

file_cache_ttl

自上次访问时间以来保留下载的云文件的时间量,以秒为单位。如果未给出,则使用POLARS_FILE_CACHE_TTL环境变量(默认为1小时)。

include_file_paths

将源文件的路径作为一列包含在此名称中。

Returns:
LazyFrame

另请参阅

read_csv

将CSV文件读取到DataFrame中。

示例

>>> import pathlib
>>>
>>> (
...     pl.scan_csv("my_long_file.csv")  # lazy, doesn't do a thing
...     .select(
...         ["a", "c"]
...     )  # select only 2 columns (other columns will not be read)
...     .filter(
...         pl.col("a") > 10
...     )  # the filter is pushed down the scan, so less data is read into memory
...     .head(100)  # constrain number of returned results to 100
... )  

我们可以使用 with_column_names 在扫描前修改表头:

>>> df = pl.DataFrame(
...     {"BrEeZaH": [1, 2, 3, 4], "LaNgUaGe": ["is", "hard", "to", "read"]}
... )
>>> path: pathlib.Path = dirpath / "mydf.csv"
>>> df.write_csv(path)
>>> pl.scan_csv(
...     path, with_column_names=lambda cols: [col.lower() for col in cols]
... ).collect()
shape: (4, 2)
┌─────────┬──────────┐
│ breezah ┆ language │
│ ---     ┆ ---      │
│ i64     ┆ str      │
╞═════════╪══════════╡
│ 1       ┆ is       │
│ 2       ┆ hard     │
│ 3       ┆ to       │
│ 4       ┆ read     │
└─────────┴──────────┘

你也可以通过向new_columns参数传递一个新的列名列表来简单地替换列名(或者如果文件没有列名,则提供它们):

>>> df.write_csv(path)
>>> pl.scan_csv(
...     path,
...     new_columns=["idx", "txt"],
...     schema_overrides=[pl.UInt16, pl.String],
... ).collect()
shape: (4, 2)
┌─────┬──────┐
│ idx ┆ txt  │
│ --- ┆ ---  │
│ u16 ┆ str  │
╞═════╪══════╡
│ 1   ┆ is   │
│ 2   ┆ hard │
│ 3   ┆ to   │
│ 4   ┆ read │
└─────┴──────┘