1

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)
  • Could you post a reproducible input generating a pandas dataframe? – ivanp Aug 24 '22 at 18:15
  • I am not understanding what you are asking @ivanp – Carlos Lozano Aug 24 '22 at 18:19
  • This probably explains it well: https://stackoverflow.com/help/minimal-reproducible-example – ivanp Aug 24 '22 at 18:24
  • What @ivanp tries to explain is that it would be best to convert the data in your post, directly to a DataFrame, because the way you have written it so far, does not help very much in understanding the problem – Yannis P. Aug 24 '22 at 18:34
  • 1
    See [How to make good pandas examples](https://stackoverflow.com/questions/20109391/how-to-make-good-reproducible-pandas-examples) and [edit] to provide the input and output in a format we can reproduce – G. Anderson Aug 24 '22 at 18:34

2 Answers2

0

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
mozway
  • 194,879
  • 13
  • 39
  • 75
0

Another possible solution:

pd.concat([df[x].sort_values().reset_index(drop=True) for x in df.columns], axis=1)

Output:

     col1     col2     col3
0  1.Test   1.Test   1.Test
1  2.Test   2.Test   2.Test
2  3.Test   3.Test   3.Test
PaulS
  • 21,159
  • 2
  • 9
  • 26