跳到主要内容

全局函数

以下全局函数与命名空间已直接注入 Python 脚本作用域,无需 import 即可使用。

query

query(sql: str, *args) -> DataFrame

对已绑定/挂载的数据源执行 SQL 查询,将结果行返回为一个 DataFrame。走的是与普通 SQL 查询相同的查询引擎通路,支持多数据源与跨源查询。

def main():
df = query("SELECT id, name, amount FROM orders WHERE amount > ?", 100)
return df
  • 位置参数 *args 依次替换 SQL 中的 ? 占位符,用于参数化查询。

  • 时间列注意:SQL 返回的 timestamp / date 列会以字符串形式回来,需用 .str.to_datetime().str.to_date() 转换:

    df = df.with_columns(pl.col("created_at").str.to_datetime())

fetch

fetch(url: str, method="GET", body=None, headers=None, timeout=30) -> Response

发起 HTTP 请求,返回 Response 对象。JS fetch 风格封装。

def main():
res = fetch(
"https://api.example.com/items",
method="POST",
body={"page": 1},
headers={"Authorization": "Bearer ..."},
)
if not res.ok:
return [{"error": res.status}]
return res.json()

参数

参数说明
url请求地址
methodHTTP 方法,默认 "GET"
body请求体;为 dict / list 时自动 JSON 序列化,并在未显式指定时默认 content-type: application/json
headers请求头 dict
timeout超时秒数,默认 30

错误处理

  • 传输层错误(DNS/连接失败等)会抛出可捕获的异常。
  • HTTP 4xx/5xx 状态码不会抛异常,需通过 res.ok / res.status 判断。

Response 对象

成员说明
res.ok布尔,状态码是否为 2xx
res.statusHTTP 状态码(int)
res.status_text状态描述文本
res.headers.get(name, default=None)按名称读响应头(大小写不敏感)
res.text()响应体原始字符串
res.json()将响应体解析为 JSON
备注

fetch() 仅用于访问外部 HTTP 服务

args

args: dict

调用方传入的脚本参数,始终是一个 dict

def main():
threshold = args["threshold"]
return query("SELECT * FROM sales").filter(pl.col("revenue") > threshold)

print

print(*values)

内置 print() 被重定向到脚本日志,输出不会进入结果集,便于调试。

def main():
df = query("SELECT * FROM orders")
print("行数:", df.height)
return df

pl 命名空间

pl 提供表达式构造器、数据类型常量以及 DataFrame / Series 类型。

成员说明
pl.col(name)按列名引用一个列,返回 Expr
pl.lit(value)由标量构造字面量表达式,返回 Expr
pl.when(*predicates)条件表达式入口,返回 When,链式 .then().when().otherwise()
pl.cov(a, b, ddof=1)两个 Series 的样本协方差(即时求值)
pl.corr(a, b, method="pearson", ...)两个 Series 的相关系数,method 支持 "pearson" / "spearman"
pl.DataFrameDataFrame 类型
pl.SeriesSeries 类型
pl.Int / pl.Float / pl.Boolean / pl.String / pl.Datetime / pl.Date数据类型常量(见 总览
def main():
df = query("SELECT category, amount FROM sales")
return df.with_columns((pl.col("amount") * pl.lit(1.1)).alias("amount_with_tax"))

条件表达式

pl.when() 支持链式条件分支,类似 SQL 的 CASE WHEN

df.with_columns(
pl.when(pl.col("amount") > 100)
.then(pl.lit("high"))
.when(pl.col("amount") > 50)
.then(pl.lit("mid"))
.otherwise(pl.lit("low"))
.alias("level")
)

不调 .otherwise() 时,未匹配的值为 null。

协方差与相关系数

s1 = df.get_column("a")
s2 = df.get_column("b")
cov_ab = pl.cov(s1, s2) # 样本协方差
r = pl.corr(s1, s2) # Pearson 相关系数(默认)
r_spearman = pl.corr(s1, s2, method="spearman")
备注

DataFrameSeries 既可作为全局名直接使用,也可通过 pl.DataFrame / pl.Series 访问,二者等价。