<h2>简单结构包含在所有数据上</h2>
<p>我做了一个示例数据帧,因为你没有提供</p>
<pre><code> col1 col2 col3
0 foo cucumber HogsWatch
1 bar selery hogswatch
2 baz Porcupine Watch Hogs
</code></pre>
<p>您可以使用apply获取一个函数来处理整个数据帧</p>
^{pr2}$
<h3>合并回</h3>
<p>这意味着您可以用布尔列生成一个新的数据帧,如果需要,可以将其连接到原始数据帧中</p>
<pre><code>bool_df = df.apply(lambda x: x.str.contains('A', flags=re.IGNORECASE))
df = df.merge(bool_df, left_index=True, right_index=True, suffixes=['', '_bool'])
col1 col2 col3 col1_bool col2_bool col3_bool
0 foo cucumber HogsWatch False False True
1 bar selery hogswatch True False True
2 baz Porcupine Watch Hogs True False True
</code></pre>
<h2>多重条件</h2>
<p>当然,您可以在<code>str.contains</code>中生成更复杂的正则表达式,例如</p>
<pre><code>df.apply(lambda x: x.str.contains('A|O', flags=re.IGNORECASE))
col1 col2 col3
0 True False True
1 True False True
2 True True True
</code></pre>
<h2>独立条件</h2>
<p>我注意到每个专栏都有不同的条件,这也可以用这种方法来实现,但它有点复杂,尽管仍然很快。在</p>
<p>首先,我们创建所有实际匹配字符串的数据帧</p>
<pre><code>conditions = {"col1": ["ar", "f"], "col2": ["er", "c"], "col3": ["Hog", " "]}
for col_name, strings in conditions:
regex = "(" + ")|(".join(strings) + ")"
df_cond = df[col_name].str.extract(regex, flags=re.IGNORECASE).notnull()
df[col_name + '_matches'] = df_cond.T.max().T
</code></pre>
<p>生产</p>
<pre><code> col1 col2 col3 col1_matches col2_matches col3_matches
0 foo cucumber HogsWatch True True True
1 bar selery hogswatch True True True
2 baz Porcupine Watch Hogs True False True
</code></pre>