gpt4 book ai didi

python - 删除数据框中每行列中字符串中的重复单词

转载 作者:行者123 更新时间:2023-12-01 08:13:31 25 4
gpt4 key购买 nike

我正在尝试删除每行数据框中字符串中的重复单词。

假设我的数据框如下所示:

In:
Yes Yes Absolutely
No No Nope
Win Win Lose



for row in df.iterrows():
row["Sentence"] = (list(set(row["Sentence"])))

Desired Out:
Yes Absolutely
No Nope
Win Lose

如何清理每一行以删除重复的字符串。我已经尝试过上面的代码。

如果任何文档或来源的链接能够引导我走向正确的方向,我将不胜感激。谢谢。

最佳答案

您可以使用(假设列名称为 0):

from collections import OrderedDict
df[0].str.split().apply(lambda x: ','.join(OrderedDict.fromkeys(x).keys()))

0 Yes,Absolutely
1 No,Nope
2 Win,Lose

注意,您可以使用设置为:

df[0].str.split().apply(lambda x: ','.join(list(set(x))))

但是 set 并不能保证顺序。

关于python - 删除数据框中每行列中字符串中的重复单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55089343/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com