<p>如果您的最终目标是获得所需的结果,那么您可以简单地解析数据</p>
<h2>您的示例数据:</h2>
<pre><code>print(data)
Tim Tim@google.com
Rob Rob@gmail.com
Jen Jen@gmail.com
Wes NaN
</code></pre>
<p>我们可以简单地使用<code>str</code>方法和<code>split</code>函数,如下所示,我们将获得所需的名称</p>
<pre><code>df.str.split('.').str[-2]
Tim google
Rob gmail
Jen gmail
Wes NaN
</code></pre>
<h2>或</h2>
<p>您可以使用@Allen的解决方案,将<code>match()</code>替换为<code>findall()</code>,因为它符合要求,因为您有系列数据<code>data = pd.Series(data)</code>,请参见下面的区别</p>
<p><strong>findall()</strong>查找序列/索引中所有出现的模式或正则表达式。相当于对所有元素应用re.findall()</p>
<p><strong>match()</strong>确定每个字符串是否与正则表达式匹配。调用re.match()并返回布尔值</p>
<pre><code>pattern = r'([A-Z0-9._%+-]+)@([A-Z0-9.-]+)\.([A-Z]{2,4})'
matches = data.str.findall(pattern, flags=re.IGNORECASE)
matches.str.get(0).str.get(1)
Tim google
Rob gmail
Jen gmail
Wes NaN
dtype: object
</code></pre>
<p>为了解决这个错误,<code>AttributeError: Can only use .str accessor with string values!</code>您应该使用<code>astype(str).str</code>,因为<code>data</code>有它所抱怨的浮点值<code>.</code></p>
<p>所以,你可以尝试下面的方法,但不返回你想要的</p>
<pre><code>matches.astype(str).str.get(1)
Tim r
Rob r
Jen r
Wes a
</code></pre>