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)
Anda dapat mencoba solusi berikut:
Solusi 1:
df = df[ ['mean'] + [ col for col in df.columns if col != 'mean' ] ]
Solusi 2:
df = df[['mean', 'x', 'y', 'z']]
Solusi 3:
col = df.pop("mean")
df = df.insert(0, col.name, col)
Solusi 4:
df.set_index(df.columns[-1], inplace=True)
df.reset_index(inplace=True)
Solusi 5:
cols = list(df)
cols = [cols[-1]] + cols[:-1]
df = df[cols]
solusi 6:
order = [1,2,3,0] # setting column's order
df = df[[df.columns[i] for i in order]]
Perbandingan waktu:
Solusi 1:
Waktu CPU: pengguna 1.05 ms, sistem: 35 µs, total: 1.08 ms Waktu dinding: 995 µs
Solusi 2 :
Waktu CPU: pengguna 933 µs, sistem: 0 ns, total: 933 μs Waktu dinding: 800 µs
Solusi 3 :
Waktu CPU: pengguna 0 ns, sistem: 1,35 ms, total: 1,35 ms Waktu dinding: 1,08 ms
Solusi 4 :
Waktu CPU: pengguna 1,23 ms, sistem: 45 μs, total: 1,27 ms Waktu dinding: 986 μs
Solusi 5 :
Waktu CPU: pengguna 1,09 ms, sistem: 19 μs, total: 1,11 ms Waktu dinding: 949 μs
Solusi 6 :
Waktu CPU: pengguna 955 µs, sistem: 34 µs, total: 989 µs Waktu dinding: 859 µs