user15051990
user15051990

Reputation: 1895

Sort words alphabetically in each row of a dataframe python

I have a column in dataframe which contains string values as given below:

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

I want to sort each word in a element alphabetically.

Desired output:

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

I tried doing this using below code:

sortdf['col1']. sort()

But this code doen not work.

Upvotes: 3

Views: 4050

Answers (1)

jpp
jpp

Reputation: 164673

Using pd.Series.apply with an anonymous lambda function:

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

pd.Series.sort is inappropriate because (a) this sorts series elements rather than words within series elements, and (b) the method has been deprecated in favour of sort_values.

The idea is to split a string into a list of words, sort alphabetically, then rejoin into a string.

Result:

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

Alternatively, a list comprehension may be more efficient:

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

Upvotes: 5

Related Questions