How to change the order of DataFrame columns?

前端 未结 30 2301
南旧
南旧 2020-11-22 01:24

I have the following DataFrame (df):

import numpy as np
import pandas as pd

df = pd.DataFrame(np.random.rand(10, 5))
30条回答
  •  傲寒
    傲寒 (楼主)
    2020-11-22 02:14

    I liked Shoresh's answer to use set functionality to remove columns when you don't know the location, however this didn't work for my purpose as I need to keep the original column order (which has arbitrary column labels).

    I got this to work though by using IndexedSet from the boltons package.

    I also needed to re-add multiple column labels, so for a more general case I used the following code:

    from boltons.setutils import IndexedSet
    cols = list(IndexedSet(df.columns.tolist()) - set(['mean', 'std']))
    cols[0:0] =['mean', 'std']
    df = df[cols]
    

    Hope this is useful to anyone searching this thread for a general solution.

提交回复
热议问题