这可能是一个非常基本的问题,但我一直无法找到答案,所以这里...
问题:
有没有一种方法可以按字母顺序对值进行排序,同时删除任何重复的实例?
这是我所拥有的:
data = ['Car | Book | Apple','','Book | Car | Apple | Apple']
df = pd.DataFrame(data,columns=['Labels']
print(df)
Labels
0 Car | Book | Apple
1
2 Book | Car | Apple | Apple
期望的输出:
Labels
0 Apple | Book | Car
1
2 Apple | Book | Car
谢谢!
最佳答案
在 str.split
str.join
df=df.replace({' ':''},regex=True)
df.Labels.str.split('|').apply(set).str.join('|')
Out[339]:
0 Apple|Book|Car
1
2 Apple|Book|Car
Name: Labels, dtype: object
根据注释添加sorted
df.Labels.str.split('|').apply(lambda x : sorted(set(x),reverse=False)).str.join(' | ')
关于python - 如何对 Pandas DF 列中的值进行排序并删除重复项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49326927/