在数据帧python的每一行中按字母顺序对单词进行排序

在数据帧python的每一行中按字母顺序对单词进行排序,python,string,pandas,sorting,dataframe,Python,String,Pandas,Sorting,Dataframe,我在dataframe中有一列,其中包含如下所示的字符串值: 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 hel

我在dataframe中有一列,其中包含如下所示的字符串值:

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()
但此代码不起作用。

使用匿名
lambda
函数:

sortdf['col1'] = sortdf['col1'].apply(lambda x: ' '.join(sorted(x.split())))
pd.Series.sort
不合适,因为(a)该方法对序列元素而不是序列元素中的单词进行排序,并且(b)该方法已被弃用,取而代之的是
sort\u值

其思想是将一个字符串拆分为一个单词列表,按字母顺序排序,然后重新合并为一个字符串

结果:

                      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()]

也许比申请更快<代码>列表(map(lambda x:“”.join(sorted(x)),sortdf.col1.str.split().tolist())@Wen,可能是的。我添加的列表理解应该比
map
+
lambda
更快。