Pandas if the full string is contained in another pandas frame

I would like to classify parts using data frames.

Simplifying the problem to try to show the problem:

data = {'col1': ['engine','blue engine cover','spark plug',
        'rear panel','black rear panel', 'blue engine']}
desc_df = pd.DataFrame(data=data)

catg = {'bodywork': ['engine cover','side panel','rear panel'],'underhood':['engine','spark plug','oil filter'],
   'Glass':['Windscreen','window','demister']}

catg_df = pd.DataFrame(data=catg)

catg_df


   Glass         bodywork       underhood
0 Windscreen     engine cover   engine 
1 window         side panel     spark plug 
2 demister       rear panel     oil filter 

desc_df

     col1
0   engine 
1 blue engine cover 
2 spark plug 
3 rear panel 
4 black rear panel 
5 blue engine 

I would like to end up with:

  col1                Category
0 engine              underhood 
1 blue engine cover   underhood 
2 spark plug          underhood 
3 rear panel          bodywork 
4 black rear panel    bodywork 
5 blue engine         underhood 

The closest I came up with is:

d=catg_df.apply('|'.join).to_dict()

desc_df['Category'] = desc_df['col1'].apply(lambda x : ''.join([z if pd.Series(x).str.contains(y).values else '' for z,y in d.items()]))

But in the end, I found in the line "engine" and "engine cover": desc_df

col1                   Category
0 engine              underhood 
1 blue engine cover   bodyworkunderhood 
2 spark plug          underhood 
3 rear panel          bodywork 
4 black rear panel    bodywork 
5 blue engine         underhood 

Is there any method that I could use, perhaps if he first finds the “engine cover” and then categorizes this category and does not move to the “engine”.

+4
source share
2 answers

You can solve this problem by iterating the dictionary:

from collections import OrderedDict

d = OrderedDict([(k, '|'.join(catg_df[k].tolist())) for k in catg_df.columns[::-1]])

for k, v in d.items():
    desc_df.loc[desc_df['col1'].str.contains(v), 'Category'] = k

Result

print(desc_df)

                col1   Category
0             engine  underhood
1  blue engine cover   bodywork
2         spark plug  underhood
3         rear panel   bodywork
4   black rear panel   bodywork
5        blue engine  underhood

Explanation

  • str.contains "".
  • collections.OrderedDict .
  • d.
+1

difflib lambda:

:

from difflib import get_close_matches
mapper = {val:k for k, v in catg_df.to_dict('list').items() for val in v}
print(mapper)

, mapper :

{'Windscreen': 'Glass',
 'demister': 'Glass',
 'engine': 'underhood',
 'engine cover': 'bodywork',
 'oil filter': 'underhood',
 'rear panel': 'bodywork',
 'side panel': 'bodywork',
 'spark plug': 'underhood',
 'window': 'Glass'}

, lambda difflib, :

# avoid calling mapper.keys() in lambda 
keys = mapper.keys()
desc_df['Category'] = desc_df['col1'].apply(lambda row: mapper[get_close_matches(row, keys)[0]])

:

                col1   Category
0             engine  underhood
1  blue engine cover   bodywork
2         spark plug  underhood
3         rear panel   bodywork
4   black rear panel   bodywork
5        blue engine  underhood
+2

Source: https://habr.com/ru/post/1696363/


All Articles