How to change the order of DataFrame columns?

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

    import numpy as np
    import pandas as pd
    df = pd.DataFrame()
    column_names = ['x','y','z','mean']
    for col in column_names: 
        df[col] = np.random.randint(0,100, size=10000)
    

    You can try out the following solutions :

    Solution 1:

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

    Solution 2:


    df = df[['mean', 'x', 'y', 'z']]
    

    Solution 3:

    col = df.pop("mean")
    df = df.insert(0, col.name, col)
    

    Solution 4:

    df.set_index(df.columns[-1], inplace=True)
    df.reset_index(inplace=True)
    

    Solution 5:

    cols = list(df)
    cols = [cols[-1]] + cols[:-1]
    df = df[cols]
    

    solution 6:

    order = [1,2,3,0] # setting column's order
    df = df[[df.columns[i] for i in order]]
    

    Time Comparison:

    Solution 1:

    CPU times: user 1.05 ms, sys: 35 µs, total: 1.08 ms Wall time: 995 µs

    Solution 2:

    CPU times: user 933 µs, sys: 0 ns, total: 933 µs Wall time: 800 µs

    Solution 3:

    CPU times: user 0 ns, sys: 1.35 ms, total: 1.35 ms Wall time: 1.08 ms

    Solution 4:

    CPU times: user 1.23 ms, sys: 45 µs, total: 1.27 ms Wall time: 986 µs

    Solution 5:

    CPU times: user 1.09 ms, sys: 19 µs, total: 1.11 ms Wall time: 949 µs

    Solution 6:

    CPU times: user 955 µs, sys: 34 µs, total: 989 µs Wall time: 859 µs

提交回复
热议问题