简体   繁体   中英

Replace special characters with "N/A" in Python

I would like to change all rows with only emojis such as df['Comments'][2] to 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 🔥💪🏻

The following code doesn't return the output I expect:

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

Expected Output:

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 🔥💪🏻

You can detect lines containing only emojis by iterating over the unicode characters in each line (using the emoji and unicodedata packages):

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'])

Function (remove_emoji) reference https://stackoverflow.com/a/61839832/6075699

Try
Install first 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM