首页 > 解决方案 > 在数据框python的每一行中按字母顺序对单词进行排序

问题描述

我在数据框中有一列包含字符串值,如下所示:

sortdf=pd.DataFrame(data= {'col1':["hello are you","what happenend","hello you there","issue is in our program","whatt is your name"]})

我想按字母顺序对元素中的每个单词进行排序。

期望的输出:

    col1
0    are hello you
1   happenend what 
2   hello there you 
3    is in issue  our program
4   is name whatt your

我尝试使用以下代码执行此操作:

sortdf['col1']. sort()

但是这段代码不起作用。

标签: pythonstringpandassortingdataframe

解决方案


pd.Series.apply与匿名lambda函数一起使用:

sortdf['col1'] = sortdf['col1'].apply(lambda x: ' '.join(sorted(x.split())))

pd.Series.sort是不合适的,因为 (a) 这对系列元素而不是系列元素中的单词进行排序,并且 (b) 该方法已被弃用,取而代之的是sort_values.

这个想法是将一个字符串拆分为一个单词列表,按字母顺序排序,然后重新加入一个字符串。

结果:

                      col1
0            are hello you
1           happenend what
2          hello there you
3  in is issue our program
4       is name whatt your

或者,列表推导可能更有效:

sortdf['col1'] = [' '.join(sorted(x)) for x in sortdf['col1'].str.split()]

推荐阅读