How to change the order of DataFrame columns?

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

    I ran into a similar question myself, and just wanted to add what I settled on. I liked the reindex_axis() method for changing column order. This worked:

    df = df.reindex_axis(['mean'] + list(df.columns[:-1]), axis=1)
    

    An alternate method based on the comment from @Jorge:

    df = df.reindex(columns=['mean'] + list(df.columns[:-1]))
    

    Although reindex_axis seems to be slightly faster in micro benchmarks than reindex, I think I prefer the latter for its directness.

提交回复
热议问题