Neo
Neo

Reputation: 492

sort every value of a string column alphabetically

This might be easy to achieve, but I have not found a solution. I have a DataFrame with a string column "c1". I want to sort every value in "c1" alphabetically. The example is in the following:

dic = {'c1':['orange','box','water'],'c2':[41, 42,48]}
df = pd.DataFrame.from_dict(dic)
df

The original DataFrame looks like:

+--------+--------+
|c1      |c2      |
+--------+--------+
|orange  |41      |
+--------+--------+
|box     |42      |
+--------+--------+
|water   |48      |
+--------+--------+

The result I would like to have looks like:

+--------+--------+
|c1      |c2      |
+--------+--------+
|aegnor  |41      |
+--------+--------+
|box     |42      |
+--------+--------+
|aertw   |48      |
+--------+--------+

Thanks. Much appreciated.

Upvotes: 2

Views: 36

Answers (1)

Quang Hoang
Quang Hoang

Reputation: 150825

You can use apply:

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

or list comprehension:

df['c1'] = [''.join(sorted(x)) for x in df['c1']]

Output:

       c1  c2
0  aegnor  41
1     box  42
2   aertw  48

Upvotes: 2

Related Questions