为了账号安全,请及时绑定邮箱和手机立即绑定

如何在字符串中搜索关键字、提取该字符串并将其放入新列中?

如何在字符串中搜索关键字、提取该字符串并将其放入新列中?

繁花如伊 2023-02-07 10:52:27
我正在使用熊猫。这是我的 df:df = {'Product Name': ['Nike Zoom Pegasus', 'All New Nike Zoom Pegasus 4', 'Metcon 3', 'Nike Metcon 5']}我想搜索每个字符串值并仅提取产品类别,然后将提取的字符串值放在另一列(“类别”)中。您可能会注意到,产品名称没有正式的命名约定,因此 .split() 不适合使用。最终结果应如下所示:df = {'Product Name': ['Nike Zoom Pegasus', 'All New Nike Zoom Pegasus 4', 'Metcon 3', 'Nike Metcon 5'], 'Category': ['Pegasus', 'Pegasus', 'Metcon', 'Metcon]}我当前的代码是这样的,但出现错误:def get_category(product):if df['Product Name'].str.contains('Pegasus') or df['Product Name'].str.contains('Metcon'):    return productdf['Category'] = df['Product Name'].apply(lambda x: get_category(x))ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().希望你能帮忙。谢谢!
查看完整描述

4 回答

?
GCT1015

TA贡献1827条经验 获得超4个赞

这个解决方案怎么样,当你有一个新类别时,你所要做的就是将新类别添加到 cats 数组中。


import pandas as pd

import numpy as np


df = pd.DataFrame({'Product Name': ['Nike Zoom Pegasus', 'All New Nike Zoom Pegasus 4', 'Metcon 3', 'Nike Metcon 5']})

cats = ["Pegasus","Metcon"]

df["Category"] = df["Product Name"].apply(lambda x: np.intersect1d(x.split(" "),cats)[0])



output

                  Product Name Category

0            Nike Zoom Pegasus  Pegasus

1  All New Nike Zoom Pegasus 4  Pegasus

2                     Metcon 3   Metcon

3                Nike Metcon 5   Metcon


查看完整回答
反对 回复 2023-02-07
?
BIG阳

TA贡献1859条经验 获得超6个赞

使用pandas.Series.str.extract

>>> df = pd.DataFrame({'Product Name': ['Nike Zoom Pegasus', 'All New Nike Zoom Pegasus 4', 'Metcon 3', 'Nike Metcon 5']})

>>> cats = ["Pegasus","Metcon"]


>>> df['Category'] = df["Product Name"].str.extract("(%s)" % "|".join(cats))

                  Product Name Category

0            Nike Zoom Pegasus  Pegasus

1  All New Nike Zoom Pegasus 4  Pegasus

2                     Metcon 3   Metcon

3                Nike Metcon 5   Metcon


查看完整回答
反对 回复 2023-02-07
?
FFIVE

TA贡献1797条经验 获得超6个赞

怎么样:


import pandas as pd


df = {'Product Name': ['Nike Zoom Pegasus', 'All New Nike Zoom Pegasus 4', 'Metcon 3', 'Nike Metcon 5']}


c = set(['Metcon', 'Pegasus'])

categories = [c.intersection(pn.split(' ')) for pn in df['Product Name']]

df['Categories'] = categories


print(df)

>> {'Product Name': ['Nike Zoom Pegasus', 'All New Nike Zoom Pegasus 4', 'Metcon 3', 'Nike Metcon 5'], 'Categories': [{'Pegasus'}, {'Pegasus'}, {'Metcon'}, {'Metcon'}]}



查看完整回答
反对 回复 2023-02-07
?
守候你守候我

TA贡献1802条经验 获得超10个赞

您的代码存在的问题如下:

  • 您传递的是产品,但在检查时使用的是df["Product Name"],这会返回整个系列。

  • 此外,返回值是产品。但根据预期的答案,要么是Pegasus要么Metcon

我想你想要这样的东西。

def get_category(product):

    if "Pegasus" in product:

        return "Pegasus" 

    elif "Metcon" in product:

        return "Metcon"


查看完整回答
反对 回复 2023-02-07
  • 4 回答
  • 0 关注
  • 88 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信