How to change the order of DataFrame columns?

前端 未结 30 1567
南旧
南旧 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:24

    You need to create a new list of your columns in the desired order, then use df = df[cols] to rearrange the columns in this new order.

    cols = ['mean']  + [col for col in df if col != 'mean']
    df = df[cols]
    

    You can also use a more general approach. In this example, the last column (indicated by -1) is inserted as the first column.

    cols = [df.columns[-1]] + [col for col in df if col != df.columns[-1]]
    df = df[cols]
    

    You can also use this approach for reordering columns in a desired order if they are present in the DataFrame.

    inserted_cols = ['a', 'b', 'c']
    cols = ([col for col in inserted_cols if col in df] 
            + [col for col in df if col not in inserted_cols])
    df = df[cols]
    

提交回复
热议问题