【问题标题】:Removing rows contains non-english words in Pandas dataframe删除行包含 Pandas 数据框中的非英语单词
【发布时间】:2020-11-25 20:58:09
【问题描述】:

我有一个由 4 行组成的 pandas 数据框,英文行包含新闻标题,一些行包含像这样的非英文单词

**She’s the Hollywood Power Behind Those ...**

我想删除所有像这样的行,所以所有在 Pandas 数据框中至少包含非英文字符的行。

【问题讨论】:

  • 非英文字符、非(基本)ASCII 字符还是非拉丁字符? “字符”是指字母/数字?请提供 DataFrame 的示例以及预期结果。谢谢。
  • 可能在此处提交有用的 string.ascii_lettersstring.digits 属性。
  • 这能回答你的问题吗? How to check if string is 100% ascii in python 3

标签: python python-3.x pandas dataframe


【解决方案1】:

如果使用 Python >= 3.7:

df[df['col'].map(lambda x: x.isascii())]

col 是您的目标列。


数据:

df = pd.DataFrame({
    'colA': ['**She’s the Hollywood Power Behind Those ...**', 
             'Hello, world!', 'Cainã', 'another value', 'test123*', 'âbc']
})

print(df.to_markdown())
|    | colA                                                  |
|---:|:------------------------------------------------------|
|  0 | **She’s the Hollywood Power Behind Those ...** |
|  1 | Hello, world!                                         |
|  2 | Cainã                                                 |
|  3 | another value                                         |
|  4 | test123*                                              |
|  5 | âbc                                                   |

识别和过滤非英文字符的字符串(参见ASCII printable characters):

df[df.colA.map(lambda x: x.isascii())]

输出:

            colA
1  Hello, world!
3  another value
4       test123*

最初的方法是使用这样的用户定义函数:

def is_ascii(s):
    try:
        s.encode(encoding='utf-8').decode('ascii')
    except UnicodeDecodeError:
        return False
    else:
        return True

【讨论】:

  • 谢谢@S3DEV。更新了!
【解决方案2】:

您可以使用regex 来执行此操作。

安装文档是here。 (只是一个简单的 pip install regex)

import re

并使用[^a-zA-Z] 对其进行过滤。

分解: ^:不是 a-z:小写字母 A-Z:大写字母

【讨论】:

  • 我建议检查以确保这些模式(以及一般的正则表达式)排除带有“ä”等的非(基本)拉丁字符。 (过去的经验告诉我,他们不会……)。特别是如果 OP 想要坚持使用基本 ASCII 表。 (目前不清楚)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-08-03
  • 1970-01-01
  • 2022-06-16
  • 1970-01-01
  • 1970-01-01
  • 2014-11-21
相关资源
最近更新 更多