user13150405
user13150405

Reputation:

How to sort individual column values in Pandas?

I am trying to sort each column value alphabetically, independently of other values.

a_string = "hgfedcba"

sorted_characters = sorted(a_string)

a_string = "".join(sorted_characters)

print(a_string)

Ouput: abcdefgh

I am trying to apply this same concept to an entire column of a dataframe for each value:

for name in df['OTHER_NAME']:
    df['names_sorted'] = ''.join(sorted(name))
    
df['names_sorted']

Output: 0 EEEIKLZ 1 EEEIKLZ 2 EEEIKLZ 3 EEEIKLZ 4 EEEIKLZ

The problem I am running into is that it's returning the same name for each row when each row should be different.

Thanks for the guidance.

Upvotes: 1

Views: 50

Answers (1)

Sprizgola
Sprizgola

Reputation: 441

If you want to apply the function to each row just use DataFrame.apply() with a lambda function:

df['names_sorted'] = df['OTHER_NAME'].apply(lambda x: ''.join(sorted(x)))

Upvotes: 1

Related Questions