亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何在字符串中搜索關鍵字、提取該字符串并將其放入新列中?

如何在字符串中搜索關鍵字、提取該字符串并將其放入新列中?

繁花如伊 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 關注
  • 152 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號