AskOverflow.Dev

AskOverflow.Dev Logo AskOverflow.Dev Logo

AskOverflow.Dev Navigation

  • 主页
  • 系统&网络
  • Ubuntu
  • Unix
  • DBA
  • Computer
  • Coding
  • LangChain

Mobile menu

Close
  • 主页
  • 系统&网络
    • 最新
    • 热门
    • 标签
  • Ubuntu
    • 最新
    • 热门
    • 标签
  • Unix
    • 最新
    • 标签
  • DBA
    • 最新
    • 标签
  • Computer
    • 最新
    • 标签
  • Coding
    • 最新
    • 标签
主页 / coding / 问题 / 79161450
Accepted
apostofes
apostofes
Asked: 2024-11-06 13:47:43 +0800 CST2024-11-06 13:47:43 +0800 CST 2024-11-06 13:47:43 +0800 CST

在 polars 中 join_where 与 starts_with

  • 772

我有两个数据框,

df = pl.DataFrame({'url': ['https//abc.com', 'https//abcd.com', 'https//abcd.com/aaa', 'https//abc.com/abcd']})

conditions_df = pl.DataFrame({'url': ['https//abc.com', 'https//abcd.com', 'https//abcd.com/aaa', 'https//abc.com/aaa'], 'category': [['a'], ['b'], ['c'], ['d']]})

现在我想要一个 df,用于根据第二个 df 中以 url 开头的第一个匹配项为第一个 df 分配类别,即输出应该是,

网址 类别
https//abc.com ['一个']
https//abcd.com ['b']
https//abcd.com/aaa ['b'] - 这个以 https//abcd.com 开头,这是第一个匹配
https//abc.com/abcd ['a'] - 这个以 https//abc.com 开头,这是第一个匹配

目前有效的代码是这样的,

def add_category_column(df: pl.DataFrame, conditions_df) -> pl.DataFrame:
    
    # Initialize the category column with empty lists
    df = df.with_columns(pl.Series("category", [[] for _ in range(len(df))], dtype=pl.List(pl.String)))
    
    # Apply the conditions to populate the category column
    for row in conditions_df.iter_rows():
        url_start, category = row
        df = df.with_columns(
            pl.when(
                (pl.col("url").str.starts_with(url_start)) & (pl.col("category").list.len() == 0)
            )
            .then(pl.lit(category))
            .otherwise(pl.col("category"))
            .alias("category")
        )
    
    return df

但是有没有办法在不使用 for 循环的情况下实现相同的效果,我们可以在这里使用 join_where 吗,但在我的尝试中 join_where 对 starts_with 不起作用

python-polars
  • 3 3 个回答
  • 69 Views

3 个回答

  • Voted
  1. Henry Harbeck
    2024-11-06T16:11:16+08:002024-11-06T16:11:16+08:00

    不幸的是,目前看起来并非如此。我刚刚在 Polars 问题跟踪器上提出了这个问题并请求它。

    这是@roman 答案的一个细微变化,它在连接之前准备一个行索引。

    (
        df.join(conditions_df.with_row_index(), how="cross")
        .filter(pl.col("url").str.starts_with(pl.col("url_right")))
        # pick only the first match based on lowest row number
        # needs to happen after the starts with filter
        .filter(pl.col("index") == pl.col("index").min().over("url"))
        .select("url", "category")
    )
    

    或者,如果您有更大的数据或性能问题,则通过 DuckDB 的解决方案将进行连接starts_with(Polars SQL 似乎还不支持它)

    sql = """
    select df.url, c.category
    from df
    inner join (select *, row_number() over() as index from conditions_df) as c
    on starts_with(df.url, c.url)
    -- pick only the first match based on lowest row number
    -- this happens after the join is already done
    qualify index = min(index) over(partition by df.url)
    """
    duckdb.query(sql).pl()
    
    • 2
  2. Best Answer
    roman
    2024-11-06T15:55:48+08:002024-11-06T15:55:48+08:00

    我希望pl.DataFrame.join_where()能工作,但显然它还不允许pl.Expr.str.starts_with()条件——我得到了only 1 binary comparison allowed as join condition错误。

    因此你可以pl.DataFrame.join()改用pl.DataFrame.filter():

    (
        df
        .join(conditions_df, how="cross")
        .filter(pl.col("url").str.starts_with(pl.col("url_right")))
        .sort("url")
        .group_by("url", maintain_order=True)
        .agg(pl.col.category.first())
    )
    
    shape: (4, 2)
    ┌─────────────────────┬───────────┐
    │ url                 ┆ category  │
    │ ---                 ┆ ---       │
    │ str                 ┆ list[str] │
    ╞═════════════════════╪═══════════╡
    │ https//abc.com      ┆ ["a"]     │
    │ https//abc.com/abcd ┆ ["a"]     │
    │ https//abcd.com     ┆ ["b"]     │
    │ https//abcd.com/aaa ┆ ["b"]     │
    └─────────────────────┴───────────┘
    

    您还可以将DuckDB 与 Polars 集成并使用lateral join:

    import duckdb
    
    duckdb.sql("""
        select
            d.url,
            c.category
        from df as d,
            lateral (
                select c.category
                from conditions_df as c
                where
                    starts_with(d.url, c.url)
                limit 1
            ) as c
    """)
    
    ┌─────────────────────┬───────────┐
    │         url         │ category  │
    │       varchar       │ varchar[] │
    ├─────────────────────┼───────────┤
    │ https//abc.com      │ [a]       │
    │ https//abc.com/abcd │ [a]       │
    │ https//abcd.com/aaa │ [b]       │
    │ https//abcd.com     │ [b]       │
    └─────────────────────┴───────────┘
    

    但是,您必须小心,因为在标准 SQL 规范中行集合是无序的,因此如果不在order by侧面添加明确的子句,我不会在生产中这样做。

    • 1
  3. jqurious
    2024-11-06T23:56:52+08:002024-11-06T23:56:52+08:00

    可以concat先进行水平操作(而不是初始操作)来找到匹配项join。

    它需要更多的手动步骤 - 但在处理较大的输入时给了我最快的结果,所以可能会感兴趣。

    (df.with_row_index()
       .join(
           pl.concat(
               [
                   df.with_row_index(), 
                   conditions_df.rename({"url": "condition_url"}).drop("category")
               ],
               how = "horizontal"
           )
           .with_columns(
               pl.col.url.str.extract_many(pl.col.condition_url, overlapping=True)
                 .alias("condition_url")
           )
           .explode("condition_url")
           .filter(pl.col.url.str.starts_with(pl.col.condition_url))
           .group_by("index")
           .agg(pl.col.condition_url.first())
           .join(
               conditions_df.rename({"url": "condition_url"}),
               on = "condition_url"
           ),
           on = "index",
           how = "left"
      )
    )
    
    shape: (5, 4)
    ┌───────┬─────────────────────┬─────────────────┬───────────┐
    │ index ┆ url                 ┆ condition_url   ┆ category  │
    │ ---   ┆ ---                 ┆ ---             ┆ ---       │
    │ u32   ┆ str                 ┆ str             ┆ list[str] │
    ╞═══════╪═════════════════════╪═════════════════╪═══════════╡
    │ 0     ┆ https//abc.com      ┆ https//abc.com  ┆ ["a"]     │
    │ 1     ┆ https//abcd.com     ┆ https//abcd.com ┆ ["b"]     │
    │ 2     ┆ https//abcd.com/aaa ┆ https//abcd.com ┆ ["b"]     │
    │ 3     ┆ https//abc.com/abcd ┆ https//abc.com  ┆ ["a"]     │
    │ 4     ┆ nomatch             ┆ null            ┆ null      │
    └───────┴─────────────────────┴─────────────────┴───────────┘
    

    解释

    我们水平排列.concat()框架并用来.str.extract_many()获取所有子字符串匹配的列表,然后将其explode分成几行。

    possible_matches = (
        pl.concat(
            [
                df.with_row_index(), 
                conditions_df.rename({"url": "condition_url"}).drop("category")
            ],
            how = "horizontal"
        )
        .with_columns(
            pl.col.url.str.extract_many(pl.col.condition_url, overlapping=True)
              .alias("condition_url")
        )
        .explode("condition_url")
    )
    
    shape: (6, 3)
    ┌───────┬─────────────────────┬─────────────────────┐
    │ index ┆ url                 ┆ condition_url       │
    │ ---   ┆ ---                 ┆ ---                 │
    │ u32   ┆ str                 ┆ str                 │
    ╞═══════╪═════════════════════╪═════════════════════╡
    │ 0     ┆ https//abc.com      ┆ https//abc.com      │
    │ 1     ┆ https//abcd.com     ┆ https//abcd.com     │
    │ 2     ┆ https//abcd.com/aaa ┆ https//abcd.com     │
    │ 2     ┆ https//abcd.com/aaa ┆ https//abcd.com/aaa │
    │ 3     ┆ https//abc.com/abcd ┆ https//abc.com      │
    │ 4     ┆ nomatch             ┆ null                │
    └───────┴─────────────────────┴─────────────────────┘
    

    然后我们应用starts_with过滤器和first约束。

    matches = (
        possible_matches
         .filter(pl.col.url.str.starts_with(pl.col.condition_url))
         .group_by("index")
         .agg(pl.col.condition_url.first())
    )
    
    shape: (4, 2)
    ┌───────┬─────────────────┐
    │ index ┆ condition_url   │
    │ ---   ┆ ---             │
    │ u32   ┆ str             │
    ╞═══════╪═════════════════╡
    │ 0     ┆ https//abc.com  │
    │ 1     ┆ https//abcd.com │
    │ 2     ┆ https//abcd.com │
    │ 3     ┆ https//abc.com  │
    └───────┴─────────────────┘
    

    A.join()用于获取对应的类别。

    matches.join(
        conditions_df.rename({"url": "condition_url"}), 
        on = "condition_url"
    )
    
    shape: (4, 3)
    ┌───────┬─────────────────┬───────────┐
    │ index ┆ condition_url   ┆ category  │
    │ ---   ┆ ---             ┆ ---       │
    │ u32   ┆ str             ┆ list[str] │
    ╞═══════╪═════════════════╪═══════════╡
    │ 0     ┆ https//abc.com  ┆ ["a"]     │
    │ 3     ┆ https//abc.com  ┆ ["a"]     │
    │ 1     ┆ https//abcd.com ┆ ["b"]     │
    │ 2     ┆ https//abcd.com ┆ ["b"]     │
    └───────┴─────────────────┴───────────┘
    

    最后.join()根据匹配的行将其添加回原始框架index。

    • 0

相关问题

  • Polars - 获取包含每行最大值的列名称

  • Polars 模式与列表类型不同

  • 当过滤器不匹配时,通过返回值来进行极性分组

  • 极地扫描镶木地板;有没有办法获取扫描的文件数量?

  • 部分基于其他列名称创建新列

Sidebar

Stats

  • 问题 205573
  • 回答 270741
  • 最佳答案 135370
  • 用户 68524
  • 热门
  • 回答
  • Marko Smith

    Vue 3:创建时出错“预期标识符但发现‘导入’”[重复]

    • 1 个回答
  • Marko Smith

    为什么这个简单而小的 Java 代码在所有 Graal JVM 上的运行速度都快 30 倍,但在任何 Oracle JVM 上却不行?

    • 1 个回答
  • Marko Smith

    具有指定基础类型但没有枚举器的“枚举类”的用途是什么?

    • 1 个回答
  • Marko Smith

    如何修复未手动导入的模块的 MODULE_NOT_FOUND 错误?

    • 6 个回答
  • Marko Smith

    `(表达式,左值) = 右值` 在 C 或 C++ 中是有效的赋值吗?为什么有些编译器会接受/拒绝它?

    • 3 个回答
  • Marko Smith

    何时应使用 std::inplace_vector 而不是 std::vector?

    • 3 个回答
  • Marko Smith

    在 C++ 中,一个不执行任何操作的空程序需要 204KB 的堆,但在 C 中则不需要

    • 1 个回答
  • Marko Smith

    PowerBI 目前与 BigQuery 不兼容:Simba 驱动程序与 Windows 更新有关

    • 2 个回答
  • Marko Smith

    AdMob:MobileAds.initialize() - 对于某些设备,“java.lang.Integer 无法转换为 java.lang.String”

    • 1 个回答
  • Marko Smith

    我正在尝试仅使用海龟随机和数学模块来制作吃豆人游戏

    • 1 个回答
  • Martin Hope
    Aleksandr Dubinsky 为什么 InetAddress 上的 switch 模式匹配会失败,并出现“未涵盖所有可能的输入值”? 2024-12-23 06:56:21 +0800 CST
  • Martin Hope
    Phillip Borge 为什么这个简单而小的 Java 代码在所有 Graal JVM 上的运行速度都快 30 倍,但在任何 Oracle JVM 上却不行? 2024-12-12 20:46:46 +0800 CST
  • Martin Hope
    Oodini 具有指定基础类型但没有枚举器的“枚举类”的用途是什么? 2024-12-12 06:27:11 +0800 CST
  • Martin Hope
    sleeptightAnsiC `(表达式,左值) = 右值` 在 C 或 C++ 中是有效的赋值吗?为什么有些编译器会接受/拒绝它? 2024-11-09 07:18:53 +0800 CST
  • Martin Hope
    The Mad Gamer 何时应使用 std::inplace_vector 而不是 std::vector? 2024-10-29 23:01:00 +0800 CST
  • Martin Hope
    Chad Feller 在 5.2 版中,bash 条件语句中的 [[ .. ]] 中的分号现在是可选的吗? 2024-10-21 05:50:33 +0800 CST
  • Martin Hope
    Wrench 为什么双破折号 (--) 会导致此 MariaDB 子句评估为 true? 2024-05-05 13:37:20 +0800 CST
  • Martin Hope
    Waket Zheng 为什么 `dict(id=1, **{'id': 2})` 有时会引发 `KeyError: 'id'` 而不是 TypeError? 2024-05-04 14:19:19 +0800 CST
  • Martin Hope
    user924 AdMob:MobileAds.initialize() - 对于某些设备,“java.lang.Integer 无法转换为 java.lang.String” 2024-03-20 03:12:31 +0800 CST
  • Martin Hope
    MarkB 为什么 GCC 生成有条件执行 SIMD 实现的代码? 2024-02-17 06:17:14 +0800 CST

热门标签

python javascript c++ c# java typescript sql reactjs html

Explore

  • 主页
  • 问题
    • 最新
    • 热门
  • 标签
  • 帮助

Footer

AskOverflow.Dev

关于我们

  • 关于我们
  • 联系我们

Legal Stuff

  • Privacy Policy

Language

  • Pt
  • Server
  • Unix

© 2023 AskOverflow.DEV All Rights Reserve