How to change the order of DataFrame columns?

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

    Here is a function to do this for any number of columns.

    def mean_first(df):
        ncols = df.shape[1]        # Get the number of columns
        index = list(range(ncols)) # Create an index to reorder the columns
        index.insert(0,ncols)      # This puts the last column at the front
        return(df.assign(mean=df.mean(1)).iloc[:,index]) # new df with last column (mean) first
    

提交回复
热议问题