Frage

My DataFrame columns are:

df.columns
>>>Index([u'1', u'10', u'120', u'1800', u'30', u'300', u'3600', u'5', u'60', u'600'], dtype='object')

How I can sort my columns so that I have an ascending sequence like 1, 5, 10, 30, 60, 120, 300, 600, 1800, 3600? I tried this: df = df.reindex_axis(sorted(df.columns), axis=1)

But does not work with numbers.

War es hilfreich?

Lösung 2

You can cast them to ints, and then sort.

In [16]: idx = df.columns
In [17]: df.columns = idx.astype(int)

In [18]: idx.order()
Out[18]: Int64Index([1, 5, 10, 30, 60, 120, 300, 600, 1800, 3600], dtype='int64')

You'll need to set the dataframe's columns to the int version. Then call df = df[idx.order()].

Andere Tipps

Here you go:

df.rename(columns=int).sort(axis=1)

rename expects a function to convert by.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top