0

I have a dataframe which looks like this in pandas, and want to reorder the columns in the dataframe from lowest to highest Hz - not manually). Please could you advise?

       100Hz  10Hz  25Hz  30Hz  33Hz  50Hz
0        7.0   5.3   5.4   5.4   5.7   6.3
1        8.2   5.0   6.4   6.4   6.8   7.5
2        9.4   5.7   7.2   7.2   8.1   8.5
3       12.8   7.9   9.8   9.8  10.6  11.6
4       11.6   9.5   8.8   8.8   9.7  10.5
...      ...   ...   ...   ...   ...   ...
20154   11.3   8.6   9.9   9.9  10.2  10.5
20155    4.4   3.7   3.5   3.5   3.8   3.7
20156    6.0   5.3   4.9   4.9   5.1   5.5
20157    0.4   0.2   0.3   0.3   0.3   0.3
moys
  • 7,747
  • 2
  • 11
  • 42
SD12
  • 1
  • kindly fix ur post. it is not properly formatted – sammywemmy Feb 28 '20 at 13:21
  • 1
    Use `df = df.reindex(columns=natsorted(df.columns))` – jezrael Feb 28 '20 at 13:23
  • for `natsorted` to work, don't we have to install a separate package? – moys Feb 28 '20 at 13:44
  • natsorted is not work for me. This code works for me. `col_list = df.columns.to_list()` `col_list.sort(key=lambda col: int(''.join(filter(str.isdigit, col))))` `df[col_list]` – moys Feb 28 '20 at 13:47
  • @jezrael For natsorted to work, don't we have to install a separate package? I am asking this question again because it is not working for me. I get the error `NameError: name 'natsorted' is not defined` – moys Mar 03 '20 at 08:45
  • @moys - yes, iti necessary install – jezrael Mar 03 '20 at 08:45
  • @jezrael Then can you please remove the duplicate? I can put-in the answer that i have put or may be provide the link to another answer that can sort without installing a new package. – moys Mar 03 '20 at 08:48
  • @moys - I think there is no reason, why? If OP need it, I reopen. – jezrael Mar 03 '20 at 08:50
  • @moys - I think better is add answer to dupe, without natsort. – jezrael Mar 03 '20 at 08:51
  • @jezrael 2 reasons I feel this is not duplicate 1)This is a new method compared to the dupe 2)Dupe question is sorting index, this is sorting columns. Adding this there can be confusing. Adding the answer here will give a very clear comparison between in-put & output (many people see input & out & not read the text) Hence I will not add it there. – moys Mar 03 '20 at 08:58
  • @moys - hmm, I think difference `axis=1` vs `axis=0` (or removed) is too small difference, for `1)` be free add answer to dupe. – jezrael Mar 03 '20 at 09:00

0 Answers0