2017-11-15 5 views
-3

以下に、私が持っているデータのある列と、重複していないデータのある列を示します。Python Dataframe:Pythonの列内の同じセル内の重複する単語を削除します。

enter image description here

私は正直にもPythonコードでこれをやって起動する方法がわかりません。私はRでこれについてのいくつかの記事を読んだが、Pythonでは読んでいない。あなただけ連続で重複を取り除くために探しているなら

答えて

0

、これで十分です:

df['Desired'] = df.Current.str.replace(r'\b(\w+)(\s+\1)+\b', r'\1') 
df 

      Current   Desired 
0  Racoon Dog  Racoon Dog 
1   Cat Cat    Cat 
2 Dog Dog Dog Dog    Dog 
3 Rat Fox Chicken Rat Fox Chicken 

詳細

\b  # word boundary 
(\w+)  # 1st capture group of a single word 
( 
\s+  # 1 or more spaces 
\1  # reference to first group 
)+  # one or more repeats 
\b 

正規表現をhereから。


非連続的な重複を削除するには、私はOrderedDictデータ構造を含むソリューションをお勧めしたい:

from collections import OrderedDict 
df['Desired'] = df.Current.str.split()\ 
     .apply(lambda x: OrderedDict.fromkeys(x).keys()).str.join(' ') 

df 

      Current   Desired 
0  Racoon Dog  Racoon Dog 
1   Cat Cat    Cat 
2 Dog Dog Dog Dog    Dog 
3 Rat Fox Chicken Rat Fox Chicken 
+0

アメージング!ありがとうございました – PineNuts0

関連する問題