检查单元格是否包含字母的最快方法是什么?

What is the fastest way to check whether a cell contains letters?

我有一个包含 260 万行的数据集,其中有一列名为 msgText,其中包含书面消息。

现在,我想过滤掉所有不包含任何字母的邮件。为此,我找到了以下代码:

dataset = dataset[dataset['msgText'].astype(str).str.contains('[A-Za-z]')]

然而,16 小时后代码仍然是 运行。

此外,基于Does Python have a string 'contains' substring method?,我考虑创建一个长度为 26 的列表,其中包含字母表中的所有字母,然后检查每个单元格是否包含该字母。但这似乎也没有效率。

因此,我想知道是否有更快的方法来查找单元格是否包含字母。


编辑:上面的代码运行良好。显然,我的(慢速)代码是:dataset['msgText'] = dataset[dataset['msgText'].astype(str).str.contains('[A-Za-z]')]

import pandas

dataset['columnName'].apply(lambda x: x.find('\w') > 0)

你可以使用numpy的isalpha()方法。 (Numpy 据说比 pandas 快)

df = pd.DataFrame({'msgText': ['a', 'b', 'g', '1']})
column = df['msgText']
column[column.str.replace(' ','').str.isalpha()]

会 return:

0    a
1    b
2    g
Name: msgText, dtype: object

具有 260 万行的测试用例:

导入日期时间

df = pd.DataFrame({'msgText': ['a', 'b', 'g', '1']*2600000})
column = df['msgText']
start = datetime.datetime.now()
new_col = column[column.str.replace(' ','').str.isalpha()]
end = datetime.datetime.now()
print(f'Time taken: {end - start}; Shape: {new_col.shape}')

OUTPUT:
Time taken: 0:00:06.144576; Shape: (7800000,)