2

Based on this question Can't Re-Order Columns Data, how to do it for the dataframe row? because I have a problem, not in the column order but the row order.

my data looks like this:

 B1 B2 B1 1 1 B10 1 1 B11 1 1 B12 1 1 B2 1 1 B20 1 1 B21 1 1 B22 1 1 B3 1 1 B30 1 1 B31 1 1 

my expected result:

 B1 B2 B1 1 1 B2 1 1 B3 1 1 B10 1 1 B11 1 1 B12 1 1 B20 1 1 B21 1 1 B22 1 1 B30 1 1 B31 1 1 
1
  • 1
    Can you create some small DataFrame with expcted output? Commented Jun 19, 2019 at 6:13

2 Answers 2

3

you can use natsort

import natsort as ns df.reindex(ns.natsorted(df.index)) 

 B1 B2 B1 1 1 B2 1 1 B3 1 1 B10 1 1 B11 1 1 B12 1 1 B20 1 1 B21 1 1 B22 1 1 B30 1 1 B31 1 1 

Or:

i=df.index.to_series().str.extract('(\d+)',expand=False).astype(float).sort_values().index df.reindex(i) 
Sign up to request clarification or add additional context in comments.

Comments

2

You can use parameter key in sorted function and pass output to DataFrame.reindex:

df = df.reindex(sorted(df.index, key=lambda x: float(x[1:]))) print (df) B1 B2 B1 1 1 B2 1 1 B3 1 1 B10 1 1 B11 1 1 B12 1 1 B20 1 1 B21 1 1 B22 1 1 B30 1 1 B31 1 1 

Alternative is Series.str.extract numeric, convert to floats and get positions of sorted values by Index.argsort, last change order by DataFrame.iloc:

df = df.iloc[df.index.str.extract('(\d+)', expand=False).astype(float).argsort()] print (df) B1 B2 B1 1 1 B2 1 1 B3 1 1 B10 1 1 B11 1 1 B12 1 1 B20 1 1 B21 1 1 B22 1 1 B30 1 1 B31 1 1 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.