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

时间:2018-07-20 20:27:18

标签: python string pandas sorting dataframe

我在数据框中有一个包含如下字符串值的列:

address = 'http://interceptor-service:5002/'

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

所需的输出:

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

但是此代码不起作用。

1 个答案:

答案 0 :(得分:5)

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