【问题标题】:Replace special characters with "N/A" in Python在 Python 中用“N/A”替换特殊字符
【发布时间】:2020-08-30 10:29:10
【问题描述】:

我想将所有仅包含 df['Comments'][2] 等表情符号的行更改为 N/A。

df['Comments'][:6]
0                                                          nice
1                                                       Insane3
2                                                          ????????❤️
3                                                @bertelsen1986
4                       20 or 30 mm rise on the Renthal Fatbar?
5                                     Luckily I have one to ????????????

以下代码没有返回我期望的输出:

df['Comments'].replace(';', ':', '!', '*', np.NaN)

预期输出:

df['Comments'][:6]
0                                                          nice
1                                                       Insane3
2                                                          nan
3                                                @bertelsen1986
4                       20 or 30 mm rise on the Renthal Fatbar?
5                                     Luckily I have one to ????????????

【问题讨论】:

  • 你不想替换最后一行的????????????
  • 如果可以保留它们,我想保留它们。但是如果代码太复杂,去掉也可以。

标签: python python-3.x regex pandas special-characters


【解决方案1】:

函数(remove_emoji)参考https://stackoverflow.com/a/61839832/6075699

试试
先安装emoji lib - pip install emoji

import re
import emoji

df.Comments.apply(lambda x: x if (re.sub(r'(:[!_\-\w]+:)', '', emoji.demojize(x)) != "") else np.nan)
0                         nice
1                      Insane3
2                          NaN
3               @bertelsen1986
4    Luckily I have one to ???
Name: a, dtype: object

【讨论】:

    【解决方案2】:

    您可以通过迭代每行中的 unicode 字符(使用 emojiunicodedata 包)来检测包含 表情符号的行:

    df = {}
    df['Comments'] = ["Test", "Hello ?", "???"]
    
    import unicodedata
    import numpy as np
    from emoji import UNICODE_EMOJI
    for i in range(len(df['Comments'])):
        pure_emoji = True
        for unicode_char in unicodedata.normalize('NFC', df['Comments'][i]):
            if unicode_char not in UNICODE_EMOJI:
                pure_emoji = False
                break
        if pure_emoji:
            df['Comments'][i] = np.NaN
    print(df['Comments'])
    

    【讨论】:

    • 很抱歉,但这对我的代码没有任何影响。感谢您的努力!
    • 你是对的,它没有正确写回结果。我修改了示例以正确地将所有内容写回df 数组,并验证它是否有效。确保现在再试一次,并考虑将我的答案标记为我首先发布的解决方案。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-07-13
    • 1970-01-01
    • 1970-01-01
    • 2014-07-22
    • 2022-01-22
    • 2014-11-03
    • 2012-04-26
    相关资源
    最近更新 更多