How to change the order of DataFrame columns?

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

    You can use reindex which can be used for both axis:

    df
    #           0         1         2         3         4      mean
    # 0  0.943825  0.202490  0.071908  0.452985  0.678397  0.469921
    # 1  0.745569  0.103029  0.268984  0.663710  0.037813  0.363821
    # 2  0.693016  0.621525  0.031589  0.956703  0.118434  0.484254
    # 3  0.284922  0.527293  0.791596  0.243768  0.629102  0.495336
    # 4  0.354870  0.113014  0.326395  0.656415  0.172445  0.324628
    # 5  0.815584  0.532382  0.195437  0.829670  0.019001  0.478415
    # 6  0.944587  0.068690  0.811771  0.006846  0.698785  0.506136
    # 7  0.595077  0.437571  0.023520  0.772187  0.862554  0.538182
    # 8  0.700771  0.413958  0.097996  0.355228  0.656919  0.444974
    # 9  0.263138  0.906283  0.121386  0.624336  0.859904  0.555009
    
    df.reindex(['mean', *range(5)], axis=1)
    
    #        mean         0         1         2         3         4
    # 0  0.469921  0.943825  0.202490  0.071908  0.452985  0.678397
    # 1  0.363821  0.745569  0.103029  0.268984  0.663710  0.037813
    # 2  0.484254  0.693016  0.621525  0.031589  0.956703  0.118434
    # 3  0.495336  0.284922  0.527293  0.791596  0.243768  0.629102
    # 4  0.324628  0.354870  0.113014  0.326395  0.656415  0.172445
    # 5  0.478415  0.815584  0.532382  0.195437  0.829670  0.019001
    # 6  0.506136  0.944587  0.068690  0.811771  0.006846  0.698785
    # 7  0.538182  0.595077  0.437571  0.023520  0.772187  0.862554
    # 8  0.444974  0.700771  0.413958  0.097996  0.355228  0.656919
    # 9  0.555009  0.263138  0.906283  0.121386  0.624336  0.859904
    

提交回复
热议问题