【发布时间】: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 在循环内创建一个字典,其中键是“多词”中的单元格,值是使用拆分创建的列表
-
在“一个单词”列中使用循环
2.1 在循环内创建另一个循环在 1.1 中的字典的键、值
2.2.在这些 to 循环中检查 1.1 中的列表是否包含一个单词中的单词
2.3 如果是 - 将第三列中的相应单元格与条件下的字典键连接起来,则连接数为 5 或更少。
我实际上是在遍历数据框列单元格,并从中创建字典和列表,我读到的内容非常非常糟糕。
我是 Python 的新手,但我很确定我的方式是邪恶的。
必须有更好、更快、更清洁的方法。也许与矢量化有关?
谢谢!
【问题讨论】: