Reputation: 967
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
Upvotes: 2
Views: 49
Reputation: 863166
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
Upvotes: 2
Reputation: 75100
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)
Upvotes: 3