我有一個帶有產品標題的資料框,其中包含關鍵字,可以識別產品型別:
df_product_titles 資料框
product_title
blue phn small
silver totebag
crossshldr bag
crossshldr tote
我有另一個包含兩列的資料框,其中第一列包含關鍵字和相關的產品型別:
df_product_types 資料框
search_keyword product_type
phn phone
tote tote bag
shldr shoulder bag
我想從 product_titles 資料框中的 product_types 資料框中搜索每個關鍵字并回傳相關的產品型別。一些產品標題有多個關鍵字,因此具有多種產品型別,在這種情況下,將所有產品型別回傳到一個用逗號分隔的單個字串中會很有用。
df_output
product_title product_type
blue phn small phone
silver totebag tote bag
cross-shldr bag shoulder bag
crossshldr tote shoulder bag, tote bag
我將不勝感激任何幫助。謝謝!
uj5u.com熱心網友回復:
我可以用這個解決方案
df1 = pd.DataFrame({"product_title": ["blue phn small","silver totebag",
"crossshldr bag", "crossshldr tote"]})
df2 = pd.DataFrame({"search_keyword":["phn", "tote", "shldr"],
"product_type": ["phone","tote bag", "shoulder bag"]})
df1["product_type"] = df1["product_title"].apply(lambda x: ", ".join([df2.loc[index, "product_type"]
for index, val in df2.search_keyword.iteritems()
if val in x]))
輸出
product_title product_type
0 blue phn small phone
1 silver totebag tote bag
2 crossshldr bag shoulder bag
3 crossshldr tote tote bag, shoulder bag
uj5u.com熱心網友回復:
替代解決方案:
import numpy as np
import pandas as pd
df_product_titles = pd.DataFrame({'product_title' : ['blue phn small', 'silver totebag', 'crossshldr bag', 'crossshldr tote']})
df_product_types = pd.DataFrame({'earch_keyword': ['phn', 'tote', 'shldr'], 'product_type': ['phone', 'tote bag', 'shoulder bag']})
product_type = np.empty((df_product_titles.shape[0],),object)
product_type.fill([])
product_type[...] = [[] for _ in range(df_product_titles.shape[0])]
df_product_titles['product_type'] = product_type
for i in df_product_types.index:
for j in df_product_titles.index:
if df_product_types.loc[i, 'earch_keyword'] in df_product_titles.loc[j, 'product_title']:
df_product_titles.loc[j, 'product_type'].append(df_product_types.loc[i, 'product_type'])
for j in df_product_titles.index:
df_product_titles.loc[j,'product_type'] = ', '.join(df_product_titles.loc[j,'product_type'])
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/505736.html
上一篇:如何改變x_i向量的值?
