Python:从数据帧中删除表情符号

2024-05-06 19:07:57 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个数据框,其中包含许多不同的表情符号,我想删除它们。我看了类似问题的答案,但它们对我不起作用

index| messages
----------------
1    |Hello! 👋 
2    |Good Morning 😃  
3    |How are you ?
4    | Good 👍
5    | Ländern

现在,我想从数据帧中删除所有这些表情符号,看起来像这样

    index| messages
    ----------------
    1    |Hello!
    2    |Good Morning   
    3    |How are you ?
    4    | Good 
    5    |Ländern

我在这里尝试了这个解决方案,但不幸的是,它也删除了所有非英语字母,如“ä” How can I remove emojis from a dataframe?


Tags: 数据答案youhelloindex字母解决方案can
2条回答

我想下面是对你问题的回答。我添加了一些其他字符以进行验证

import pandas as pd
df = pd.DataFrame({'messages':['Hello! 👋', 'Good-Morning 😃', 'How are you ?', ' Goodé 👍', 'Ländern' ]})

df['messages'].astype(str).apply(lambda x: x.encode('latin-1', 'ignore').decode('latin-1'))

此解决方案将保留所有ASCII和拉丁-1字符,即this list中U+0000和U+00FF之间的字符。对于扩展拉丁语加希腊语,请使用< 1024

df = pd.DataFrame({'messages': ['Länder 🇩🇪❤️', 'Hello! 👋']})

filter_char = lambda c: ord(c) < 256
df['messages'] = df['messages'].apply(lambda s: ''.join(filter(filter_char, s)))

结果:

  messages
0  Länder 
1  Hello!

注意:例如,这不适用于日文文本。另一个问题是心脏的“表情符号”实际上是一个Dingbat,所以我不能简单地过滤Unicode的Basic Multilingual Plane,哦,好吧

相关问题 更多 >