polars.SQLContext.execute#

SQLContext.execute(
query: str,
*,
eager: bool | None = None,
) LazyFrame | DataFrame[source]#

解析给定的SQL查询并在注册的框架数据上执行它。

Parameters:
query

一个有效的字符串SQL查询。

eager

急切地应用查询,返回DataFrame而不是LazyFrame。 如果未设置,将使用初始化时的“eager”参数值。 请注意,查询本身始终以惰性模式执行;此 参数仅影响返回帧的类型。

示例

声明框架数据并使用SQLContext注册:

>>> df = pl.DataFrame(
...     data=[
...         ("The Godfather", 1972, 6_000_000, 134_821_952, 9.2),
...         ("The Dark Knight", 2008, 185_000_000, 533_316_061, 9.0),
...         ("Schindler's List", 1993, 22_000_000, 96_067_179, 8.9),
...         ("Pulp Fiction", 1994, 8_000_000, 107_930_000, 8.9),
...         ("The Shawshank Redemption", 1994, 25_000_000, 28_341_469, 9.3),
...     ],
...     schema=["title", "release_year", "budget", "gross", "imdb_score"],
...     orient="row",
... )
>>> ctx = pl.SQLContext(films=df)

对注册的框架数据执行SQL查询:

>>> ctx.execute(
...     '''
...     SELECT title, release_year, imdb_score
...     FROM films
...     WHERE release_year > 1990
...     ORDER BY imdb_score DESC
...     ''',
...     eager=True,
... )
shape: (4, 3)
┌──────────────────────────┬──────────────┬────────────┐
│ title                    ┆ release_year ┆ imdb_score │
│ ---                      ┆ ---          ┆ ---        │
│ str                      ┆ i64          ┆ f64        │
╞══════════════════════════╪══════════════╪════════════╡
│ The Shawshank Redemption ┆ 1994         ┆ 9.3        │
│ The Dark Knight          ┆ 2008         ┆ 9.0        │
│ Schindler's List         ┆ 1993         ┆ 8.9        │
│ Pulp Fiction             ┆ 1994         ┆ 8.9        │
└──────────────────────────┴──────────────┴────────────┘

执行一个GROUP BY查询:

>>> ctx.execute(
...     '''
...     SELECT
...         MAX(release_year / 10) * 10 AS decade,
...         SUM(gross) AS total_gross,
...         COUNT(title) AS n_films,
...     FROM films
...     GROUP BY (release_year / 10) -- decade
...     ORDER BY total_gross DESC
...     ''',
...     eager=True,
... )
shape: (3, 3)
┌────────┬─────────────┬─────────┐
│ decade ┆ total_gross ┆ n_films │
│ ---    ┆ ---         ┆ ---     │
│ i64    ┆ i64         ┆ u32     │
╞════════╪═════════════╪═════════╡
│ 2000   ┆ 533316061   ┆ 1       │
│ 1990   ┆ 232338648   ┆ 3       │
│ 1970   ┆ 134821952   ┆ 1       │
└────────┴─────────────┴─────────┘