интеллект:
Я работаю на поиск продукта с лучшим вторым матчем. В каталоге, мы могли бы иметь продукт, соответствующий 100%, но цель состоит в том, чтобы получить лучший второй матч.
Ниже приведен код, но он работает на лучший матч, не самый лучший второй матч.
Я получаю застрял в этой точке. Пожалуйста, дайте мне знать, если вы обнаружите какие-то решения вокруг него.
import pandas as pd
import numpy as np
seller_product =([['mai', 'dubai', '200ml']])
catalog_product=([['mai', 'dubai', '200ml'],
['mai', 'dubai', '300ml']])
# SEARCH ENGINE
def available(product, catalog):
items = [_ for _ in product if _ != "NaN"]
if isinstance(catalog[0], str):
catalog = [catalog]
max_match = (0, [])
for catalog in catalog:
matched_count = 0
for item in items:
if item in catalog:
matched_count += 1
max_match = max(max_match, (matched_count, catalog)) # tuple score + catalog_item
# return "_".join(items), max_match[1], max_match[0] / len(items)
return "_".join(items), max_match[1], max_match[0] / len(items) if len(items) != 0 else 0
def availables(products, catalog):
return [available(product, catalog) for product in products]
output=[]
for res in availables(seller_product, catalog_product):
# res=print(" -> ".join(map(str, res)))
output.append(res)
import pandas as pd
df_output=pd.DataFrame(output)
df_output
выходной ток:
[mai_dubai_200ml] [mai, dubai, 200ml] 1.0
Желаемый результат:
[mai_dubai_200ml] [mai, dubai, 300ml] 0.6667
Спасибо
Лучший Фонг
FBruzzesi:
Не уверен, что этот подход является 100% то, что вы ищете, но это должно быть близко:
# added some sample datapoints
seller_product =([['mai', 'dubai', '200ml'],
['may', 'dubai', '200ml'],
['mai', 'milan', '200ml']
])
catalog_product=([['mai', 'dubai', '200ml'],
['mai', 'dubai', '300ml'],
['may', 'dubai', '300ml']])
items = ['_'.join(p) for p in seller_product]
catalogs = ['_'.join(p) for p in catalog_product]
# Create a dataframe with catalog items as columns and seller items as indexes
df = pd.DataFrame(
np.zeros((len(items), len(catalogs))),
index=items, columns = catalogs)
# Compute row name intersection with column names
def comp_intersection(r, col_names):
item = set(r.name.split('_'))
for c in col_names:
cat = set(c.split('_'))
v = len(item.intersection(cat))/len(cat)
r[c] = v
return r
# Apply the function row-wise
result_df = df.apply(lambda r: comp_intersection(r, list(df)), axis=1)
# Store second largest value for each row
second_largest_value = pd.DataFrame(
np.squeeze(np.sort(result_df.values)[:,-2:-1]),
columns=['2nd-largest'],
index = result_df.index.to_numpy())
# Finally compare the dataframe
final_df = result_df[result_df == second_largest_value.values]
final_df = final_df.reset_index()\
.melt('index').dropna()\
.rename(columns={'index':'product',
'variable':'second_match',
'value':'score'})
for c in ['product', 'second_match']:
final_df[c] = final_df[c].str.split('_').str.join(' ')
final_df[c] = final_df[c].str.replace('NaN', '').str.strip()
final_df
product second_match score
1 may dubai 200ml mai dubai 200ml 0.666667
3 mai dubai 200ml mai dubai 300ml 0.666667
5 mai milan 200ml mai dubai 300ml 0.333333
7 may dubai 200ml may dubai 300ml 0.666667
Заметь:
- Таким образом, вы получаете также детали с теми же «вторым по величине баллов»
- Если у вас есть два или более элементов со счетом совершенным 1, функция не сможет получить второй по величине.