[ SKILL_DOCUMENTATION ]
# Polars 数据转换
关于 Polars 中连接 (Join)、拼接和重塑操作的综合指南。
## 连接 (Joins)
连接操作基于公共列组合多个 DataFrame。
### 基础连接类型
**内连接 (Inner Join - 交集):**
python
# 仅保留两个 DataFrame 中匹配的行
result = df1.join(df2, on="id", how="inner")
**左连接 (Left Join - 左侧所有 + 右侧匹配):**
python
# 保留左侧所有行,添加右侧匹配行
result = df1.join(df2, on="id", how="left")
**外连接 (Outer Join - 并集):**
python
# 保留两个 DataFrame 中的所有行
result = df1.join(df2, on="id", how="outer")
**交叉连接 (Cross Join - 笛卡尔积):**
python
# 左侧每一行与右侧每一行组合
result = df1.join(df2, how="cross")
**半连接 (Semi Join - 过滤左侧):**
python
# 仅保留在右侧有匹配项的左侧行
result = df1.join(df2, on="id", how="semi")
**反连接 (Anti Join - 非匹配左侧):**
python
# 仅保留在右侧没有匹配项的左侧行
result = df1.join(df2, on="id", how="anti")
### 连接语法变体
**单列连接:**
python
df1.join(df2, on="id")
**多列连接:**
python
df1.join(df2, on=["id", "date"])
**不同列名连接:**
python
df1.join(df2, left_on="user_id", right_on="id")
**多列不同名连接:**
python
df1.join(
df2,
left_on=["user_id", "date"],
right_on=["id", "timestamp"]
)
### 后缀处理
当两个 DataFrame 具有相同名称的列(非连接键)时:
python
# 添加后缀以区分列
result = df1.join(df2, on="id", suffix="_right")
# 结果为:value, value_right (如果两者都有 "value" 列)
### 连接示例
**示例 1: 客户订单**
python
customers = pl.DataFrame({
"customer_id": [1, 2, 3, 4],
"name": ["Alice", "Bob", "Charlie", "David"]
})
orders = pl.DataFrame({
"order_id": [101, 102, 103],
"customer_id": [1, 2, 1],
"amount": [100, 200, 150]
})
# 内连接 - 仅有订单的客户
result = customers.join(orders, on="customer_id", how="inner")
# 左连接 - 所有客户,即使没有订单
result = customers.join(orders, on="customer_id", how="left")
**示例 2: 时间序列数据**
python
prices = pl.DataFrame({
"date": ["2023-01-01", "2023-01-02", "2023-01-03"],
"stock": ["AAPL", "AAPL", "AAPL"],
"price": [150, 152, 151]
})
volumes = pl.DataFrame({
"date": ["2023-01-01", "2023-01-02"],
"stock"