Reputation: 637
I have the following dataframe:
+------+-----+-----+-----+-----+
| Name | 1 | 4 | 3 | 2 |
+------+-----+-----+-----+-----+
| ... | ... | ... | ... | ... |
+------+-----+-----+-----+-----+
And I need my dataframe to be re-arranged like this:
+------+-----+-----+-----+-----+
| Name | 1 | 2 | 3 | 4 |
+------+-----+-----+-----+-----+
| ... | ... | ... | ... | ... |
+------+-----+-----+-----+-----+
with text first, then numbers in increasing order.
I have tried doing:
df[sorted(df.columns)]
But it doesn't work as the columns are of string
type.
Upvotes: 1
Views: 158
Reputation: 862511
Use DataFrame.sort_index
with convert columns to integers with to_numeric
with errors='coerce'
, so missing values for non numbers are created. Then is used parameter na_position='first'
for starts by this columns and then are values sorted by numerics:
df = pd.DataFrame(columns=['Name','1','10','7', '6'])
df=df.sort_index(axis=1,key=lambda x: pd.to_numeric(x,errors='coerce'),na_position='first')
print (df)
Empty DataFrame
Columns: [Name, 1, 6, 7, 10]
Index: []
If values are only numbers is used Index.astype
:
df = pd.DataFrame(columns=['1','10','7', '6'])
df = df.sort_index(axis=1, key=lambda x: x.astype(int))
print (df)
Empty DataFrame
Columns: [1, 6, 7, 10]
Index: []
Or:
df = df[sorted(df.columns,key=lambda x:int(x))]
print (df)
Empty DataFrame
Columns: [1, 6, 7, 10]
Index: []
Upvotes: 4