How to change the order of DataFrame columns?

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

    I believe @Aman's answer is the best if you know the location of the other column.

    If you don't know the location of mean, but only have its name, you cannot resort directly to cols = cols[-1:] + cols[:-1]. Following is the next-best thing I could come up with:

    meanDf = pd.DataFrame(df.pop('mean'))
    # now df doesn't contain "mean" anymore. Order of join will move it to left or right:
    meanDf.join(df) # has mean as first column
    df.join(meanDf) # has mean as last column
    

提交回复
热议问题