How to change the order of DataFrame columns?

前端 未结 30 1600
南旧
南旧 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

    Here is a very simple answer to this(only one line).

    You can do that after you added the 'n' column into your df as follows.

    import numpy as np
    import pandas as pd
    
    df = pd.DataFrame(np.random.rand(10, 5))
    df['mean'] = df.mean(1)
    df
               0           1           2           3           4        mean
    0   0.929616    0.316376    0.183919    0.204560    0.567725    0.440439
    1   0.595545    0.964515    0.653177    0.748907    0.653570    0.723143
    2   0.747715    0.961307    0.008388    0.106444    0.298704    0.424512
    3   0.656411    0.809813    0.872176    0.964648    0.723685    0.805347
    4   0.642475    0.717454    0.467599    0.325585    0.439645    0.518551
    5   0.729689    0.994015    0.676874    0.790823    0.170914    0.672463
    6   0.026849    0.800370    0.903723    0.024676    0.491747    0.449473
    7   0.526255    0.596366    0.051958    0.895090    0.728266    0.559587
    8   0.818350    0.500223    0.810189    0.095969    0.218950    0.488736
    9   0.258719    0.468106    0.459373    0.709510    0.178053    0.414752
    
    
    ### here you can add below line and it should work 
    # Don't forget the two (()) 'brackets' around columns names.Otherwise, it'll give you an error.
    
    df = df[list(('mean',0, 1, 2,3,4))]
    df
    
            mean           0           1           2           3           4
    0   0.440439    0.929616    0.316376    0.183919    0.204560    0.567725
    1   0.723143    0.595545    0.964515    0.653177    0.748907    0.653570
    2   0.424512    0.747715    0.961307    0.008388    0.106444    0.298704
    3   0.805347    0.656411    0.809813    0.872176    0.964648    0.723685
    4   0.518551    0.642475    0.717454    0.467599    0.325585    0.439645
    5   0.672463    0.729689    0.994015    0.676874    0.790823    0.170914
    6   0.449473    0.026849    0.800370    0.903723    0.024676    0.491747
    7   0.559587    0.526255    0.596366    0.051958    0.895090    0.728266
    8   0.488736    0.818350    0.500223    0.810189    0.095969    0.218950
    9   0.414752    0.258719    0.468106    0.459373    0.709510    0.178053
    
    

提交回复
热议问题