【问题标题】:How to optimally find if "dataframe cell value" contains "cell value from another dataframe" and fill cell with it?如何以最佳方式查找“数据框单元格值”是否包含“来自另一个数据框的单元格值”并用它填充单元格?
【发布时间】:2022-11-03 16:59:19
【问题描述】:

我有 2 个不相等列的数据框:

One-word Many-Words
Bird Bird with no blood
Stone Stone that killed the bird
Blood Bird without brains
<none> stone and blood

我正在尝试用所有包含一个单词的多词来填充新的第三列。 (5个或更少) 所以它会像:

One-word Many-Words Many-Words with One-word
Bird Bird with no blood Bird with no blood, Bird with no blood, Stone that killed the bird, Bird without brains
Stone Stone that killed the bird Stone that killed the bird, stone and blood
Blood Bird without brains Bird without brains, Bird with no blood, stone and blood
<none> stone and blood

我实际上找到了一种方法,但是它很慢。

  1. 在“多行”列中使用循环。

    1.1 在循环内创建一个字典,其中键是“多词”中的单元格,值是使用拆分创建的列表

  2. 在“一个单词”列中使用循环

    2.1 在循环内创建另一个循环在 1.1 中的字典的键、值

    2.2.在这些 to 循环中检查 1.1 中的列表是否包含一个单词中的单词

    2.3 如果是 - 将第三列中的相应单元格与条件下的字典键连接起来,则连接数为 5 或更少。

    我实际上是在遍历数据框列单元格,并从中创建字典和列表,我读到的内容非常非常糟糕。

    我是 Python 的新手,但我很确定我的方式是邪恶的。

    必须有更好、更快、更清洁的方法。也许与矢量化有关?

    谢谢!

【问题讨论】:

    标签: python pandas dataframe


    【解决方案1】:

    您可以使用iterrows 循环您的df 行并构建包含One-wordMany-Words 列表:

    df["Many-Words with One-word"] = pd.Series([
      df[df["Many-Words"].str.lower().str.contains(row["One-word"].lower())]["Many-Words"].to_list()
        for _, row in df.iterrows()
    ])
    

    注意:使用lower 使匹配不区分大小写。

    输出:

      One-word                  Many-Words                           Many-Words with One-word
    0     Bird          Bird with no blood  [Bird with no blood, Stone that killed the bir...
    1    Stone  Stone that killed the bird      [Stone that killed the bird, stone and blood]
    2    Blood         Bird without brains              [Bird with no blood, stone and blood]
    3   <none>             stone and blood                                                 []
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-03-12
      • 2018-01-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-11-21
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多