Home > other >  How sort column values by number in string?
How sort column values by number in string?

Time:08-25

Problem: For each column I have in the dataframe, I have the structure number "." value(string). I'm trying to sort each column by the number but it's not working. Output

Row1: Column1: 1.Test, Column2: 1.Test, Column3: 2.Test
Row2: Column1: 3.Test, Column2: 2.Test, Column3: 1.Test
Row3: Column1: 2.Test, Column2: 3.Test, Column3: 3.Test

Objective: Sort each column by the number that accompanies the string so that I can get the correct data for each row and not mixed up.

Row1: Column1: 1.Test, Column2: 1.Test, Column3: 1.Test
Row2: Column1: 2.Test, Column2: 2.Test, Column3: 2.Test
Row3: Column1: 3.Test, Column2: 3.Test, Column3: 3.Test
dfPrincipal.sort_values(by=list(dfPrincipal.columns),axis=0, ascending=False)

CodePudding user response:

If each string starts with a number, then it suffices to call sort on each column:

df.agg('sort', axis=1)

CodePudding user response:

You can use:

sorter = lambda x: x.str.extract(r'(\d )', expand=False).astype(int)

df.apply(lambda s: s.sort_values(key=sorter).reset_index(drop=True))

Output:

        0       1       2
0  1.Test  1.Test  1.Test
1  2.Test  2.Test  2.Test
2  3.Test  3.Test  3.Test
  • Related