<p>资料</p>
<pre><code>import pandas as pd
import numpy as np
random_data = {'Place Name':['TS~HOT_MD~h_PB~progra_VV~gogl',
'FM~uiosv_PB~emo_SZ~1x1_TG~bhv'], 'Site':['DV360', 'Adikteev']}
dataframe = pd.DataFrame(random_data)
test_data = {'code name': ['PB', 'PB', 'PB'], 'Actual':['programmatic me', 'emoteev', 'programmatic-mechanics'],
'code':['progra', 'emo', 'prog']}
test_dataframe = pd.DataFrame(test_data)
</code></pre>
<p>将<code>test_datframe</code>{<cd2>}和<code>Actual</code>分别映射到字典中作为<code>key</code>和<code>value</code></p>
<pre><code>keys=test_dataframe['code'].values.tolist()
dicto=dict(zip(test_dataframe.code, test_dataframe.Actual))
dicto
</code></pre>
<p>连接由<a href="https://www.dataquest.io/blog/regex-cheatsheet/" rel="nofollow noreferrer">|</a>分隔的键以启用对任一短语的搜索</p>
<pre><code>k = '|'.join(r"{}".format(x) for x in dicto.keys())
k
</code></pre>
<p>从符合k中任何短语的datframe中提取字符串,并将其映射到字典</p>
<pre><code>dataframe['Site'] = dataframe['Place Name'].str.extract('('+ k + ')', expand=False).map(dicto)
dataframe
</code></pre>
<p>输出</p>
<p><a href="https://i.stack.imgur.com/2mesD.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/2mesD.png" alt="enter image description here"/></a></p>