DataFrame: Sort values of a single column

Question:

I have a dataframe like below

A        B
===========================
AA     1,3,5,2,20,11
BB     9,44,2,33,1,21

Is there a way to sort the values in column "B" as below

A        B
===========================
AA     1,2,3,5,11,20
BB     1,2,9,21,33,44

Thanks

Asked By: SM079

||

Answers:

Use sort_values() method in Pandas.

Example:

df["B"] = df["B"].sort_values(ascending=True)
Answered By: Goh Kok Han

Use lambda function, first convert to integers after split, sorted and last convert back to strings for join:

df["B"] = df["B"].apply(lambda x: ','.join(map(str, sorted(map(int, x.split(','))))))
#alternative
#df["B"] = [','.join(map(str, sorted(map(int, x.split(','))))) for x in df["B"]]
print (df)
    A               B
0  AA   1,2,3,5,11,20
1  BB  1,2,9,21,33,44

Alternative solutions:

f = lambda x: ','.join(str(z) for z in sorted(int(y) for y in x.split(',')))
df["B"] = df["B"].apply(f)

df["B"] = [','.join(str(z) for z in sorted(int(y) for y in x.split(','))) for x in df["B"]]
Answered By: jezrael
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.