擅长:python、mysql、java
<p>您可以通过迭代字典来解决此问题:</p>
<pre><code>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
</code></pre>
<p><strong>结果</strong></p>
<pre><code>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
</code></pre>
<p><strong>解释</strong></p>
<ul>
<li>对于字典中的每一项,检查<code>str.contains</code>条件与regex值,并将键分配给“Category”列。你知道吗</li>
<li>使用<code>collections.OrderedDict</code>为列赋予优先级。你知道吗</li>
<li>在这种情况下,可以在<code>d</code>的构造中反转列的迭代顺序。你知道吗</li>
</ul>