How to change the order of DataFrame columns?

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

    Moving any column to any position:

    import pandas as pd
    df = pd.DataFrame({"A": [1,2,3], 
                       "B": [2,4,8], 
                       "C": [5,5,5]})
    
    cols = df.columns.tolist()
    column_to_move = "C"
    new_position = 1
    
    cols.insert(new_position, cols.pop(cols.index(column_to_move)))
    df = df[cols]
    

提交回复
热议问题