如何删除数据帧中的重复字母?

2024-10-01 04:47:52 发布

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

我有以下字符串:

"hello, I'm going to eat to the fullest today hhhhhhhhhhhhhhhhhhhhh"

我收集了很多这样的tweet,并将它们分配到一个数据帧。我如何通过删除“hhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhh?你知道吗

我后来也在使用countVectorizer,所以有很多词汇表都包含了“hhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhh


Tags: theto数据词汇表字符串hellotodaytweet
2条回答

使用正则表达式。你知道吗

例如:

import pandas as pd

df = pd.DataFrame({"Col": ["hello, I'm going to eat to the fullest today hhhhhhhhhhhhhhhhhhhhh", "Hello World"]})
#df["Col"] = df["Col"].str.replace(r"\b(.)\1+\b", "")
df["Col"] = df["Col"].str.replace(r"\s+(.)\1+\b", "").str.strip()
print(df)

输出:

                                             Col
0  hello, I'm going to eat to the fullest today 
1                                    Hello World

你可以试试这个:

df["Col"] = df["Col"].str.replace(u"h{4,}", "")

在我的案例4中,您可以设置要匹配的字符数。你知道吗

                                        Col
0  hello, I'm today hh hhhh hhhhhhhhhhhhhhh
1                               Hello World
                     Col
0  hello, I'm today hh  
1            Hello World

我使用unicode匹配,因为你提到你在推特上。你知道吗

相关问题 更多 >