4

I have a column in a pandas dataframe called feature. I want to order the values of "feature" in an alphabetical order. For example, in the below table, how can I get all the values under age in the order age, color, gender?

ID  Feature
1001    color,age,gender
1002    age,gender,color
1003    age,color,gender
1004    color,age,gender
1005    age,color,gender
1006    color,age,gender
1007    age,color,gender

1 Answer 1

3

Here is one way, but, honestly, i don't like it:

In [24]: df.Feature = df.Feature.str.split(',', expand=True).apply(lambda x: pd.Series(np.sort(x)).str.cat(sep=','), axis=1)

In [25]: df
Out[25]:
     ID           Feature
0  1001  age,color,gender
1  1002  age,color,gender
2  1003  age,color,gender
3  1004  age,color,gender
4  1005  age,color,gender
5  1006  age,color,gender
6  1007  age,color,gender
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.