Home > Software engineering >  DataFrame: Sort values of a single column
DataFrame: Sort values of a single column

Time:12-09

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

CodePudding user response:

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"]]

CodePudding user response:

Use sort_values() method in Pandas.

Example:

df["B"] = df["B"].sort_values(ascending=True)
  • Related