简体   繁体   中英

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM