首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >构建一个使用匹配值更新列的循环?

构建一个使用匹配值更新列的循环?
EN

Stack Overflow用户
提问于 2021-03-02 22:24:43
回答 2查看 37关注 0票数 1

我想在数据框中搜索某些关键字,然后为找到关键字的行条目建立索引,以便以后进行操作。

假设我得到了一个数据帧和一些类似以下结构的关键字:

代码语言:javascript
复制
import pandas as pd

data = {"metals": ["copper", "zinc", "aluminium", "iron", "platinum", "gold", "silver", "copper and zinc"]}
df = pd.DataFrame(data)

keywords = ["copper", "zinc"]

最终,我希望实现以下目标:

代码语言:javascript
复制
# What I would like to obtain
[in] data
[out]
| ID | metals            | label          |
| -- | ----------------- | -------------- |
|0   |copper             | copper         |
|1   |zinc               | zinc           |
|2   |aluminium          | 0              |
|3   |iron               | 0              |
|4   |platinum           | 0              |
|5   |gold               | 0              |
|6   |silver             | 0              |
|7   |copper and zinc    | [copper, zinc] |

我想出了随后的循环,但是它只返回:

代码语言:javascript
复制
df['label'] = 0

for word in keywords:
    df['label'][df['metals'].str.contains(word)] = word
    
# What I actually obtain
[in] data
[out]
| ID | metals            | label          |
| -- | ----------------- | -------------- |
|0   |copper             | copper         |
|1   |zinc               | zinc           |
|2   |aluminium          | 0              |
|3   |iron               | 0              |
|4   |platinum           | 0              |
|5   |gold               | 0              |
|6   |silver             | 0              |
|7   |copper and zinc    | zinc           |

如何构建一个循环,用每一行中所有匹配的单词来更新'label‘列?我将非常感谢您的反馈。

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2021-03-02 22:41:25

您可以简单地使用str.findall查找匹配模式的所有匹配项:

代码语言:javascript
复制
pat = fr"\b({'|'.join(keywords)})\b"
df['label'] = df['metals'].str.findall(pat)

>>> df
            metals           label
0           copper        [copper]
1             zinc          [zinc]
2        aluminium              []
3             iron              []
4         platinum              []
5             gold              []
6           silver              []
7  copper and zinc  [copper, zinc]

如果您特别希望以问题中所示的所需格式输出,则还可以使用np.select

代码语言:javascript
复制
s = df['metals'].str.findall(fr"\b({'|'.join(keywords)})\b")
l = s.str.len()
df['label'] = np.select([l.ge(2), l.eq(1)], [s, s.str[0]], 0)


>>> df
            metals           label
0           copper          copper
1             zinc            zinc
2        aluminium               0
3             iron               0
4         platinum               0
5             gold               0
6           silver               0
7  copper and zinc  [copper, zinc]
票数 1
EN

Stack Overflow用户

发布于 2021-03-02 22:28:03

使用str.extractall

代码语言:javascript
复制
pattern = '|'.join(keywords)
df['label'] = (df['metals'].str.extractall(rf'\b({pattern})\b')[0]
                  .groupby(level=0).agg(list)
              )

输出:

代码语言:javascript
复制
            metals           label
0           copper        [copper]
1             zinc          [zinc]
2        aluminium             NaN
3             iron             NaN
4         platinum             NaN
5             gold             NaN
6           silver             NaN
7  copper and zinc  [copper, zinc]
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/66441252

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档