How to change the order of DataFrame columns?

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

    You can use a set which is an unordered collection of unique elements to do keep the "order of the other columns untouched":

    other_columns = list(set(df.columns).difference(["mean"])) #[0, 1, 2, 3, 4]
    

    Then, you can use a lambda to move a specific column to the front by:

    In [1]: import numpy as np                                                                               
    
    In [2]: import pandas as pd                                                                              
    
    In [3]: df = pd.DataFrame(np.random.rand(10, 5))                                                         
    
    In [4]: df["mean"] = df.mean(1)                                                                          
    
    In [5]: move_col_to_front = lambda df, col: df[[col]+list(set(df.columns).difference([col]))]            
    
    In [6]: move_col_to_front(df, "mean")                                                                    
    Out[6]: 
           mean         0         1         2         3         4
    0  0.697253  0.600377  0.464852  0.938360  0.945293  0.537384
    1  0.609213  0.703387  0.096176  0.971407  0.955666  0.319429
    2  0.561261  0.791842  0.302573  0.662365  0.728368  0.321158
    3  0.518720  0.710443  0.504060  0.663423  0.208756  0.506916
    4  0.616316  0.665932  0.794385  0.163000  0.664265  0.793995
    5  0.519757  0.585462  0.653995  0.338893  0.714782  0.305654
    6  0.532584  0.434472  0.283501  0.633156  0.317520  0.994271
    7  0.640571  0.732680  0.187151  0.937983  0.921097  0.423945
    8  0.562447  0.790987  0.200080  0.317812  0.641340  0.862018
    9  0.563092  0.811533  0.662709  0.396048  0.596528  0.348642
    
    In [7]: move_col_to_front(df, 2)                                                                         
    Out[7]: 
              2         0         1         3         4      mean
    0  0.938360  0.600377  0.464852  0.945293  0.537384  0.697253
    1  0.971407  0.703387  0.096176  0.955666  0.319429  0.609213
    2  0.662365  0.791842  0.302573  0.728368  0.321158  0.561261
    3  0.663423  0.710443  0.504060  0.208756  0.506916  0.518720
    4  0.163000  0.665932  0.794385  0.664265  0.793995  0.616316
    5  0.338893  0.585462  0.653995  0.714782  0.305654  0.519757
    6  0.633156  0.434472  0.283501  0.317520  0.994271  0.532584
    7  0.937983  0.732680  0.187151  0.921097  0.423945  0.640571
    8  0.317812  0.790987  0.200080  0.641340  0.862018  0.562447
    9  0.396048  0.811533  0.662709  0.596528  0.348642  0.563092
    

提交回复
热议问题