How to change the order of DataFrame columns?

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

    This function avoids you having to list out every variable in your dataset just to order a few of them.

    def order(frame,var):
        if type(var) is str:
            var = [var] #let the command take a string or list
        varlist =[w for w in frame.columns if w not in var]
        frame = frame[var+varlist]
        return frame 
    

    It takes two arguments, the first is the dataset, the second are the columns in the data set that you want to bring to the front.

    So in my case I have a data set called Frame with variables A1, A2, B1, B2, Total and Date. If I want to bring Total to the front then all I have to do is:

    frame = order(frame,['Total'])
    

    If I want to bring Total and Date to the front then I do:

    frame = order(frame,['Total','Date'])
    

    EDIT:

    Another useful way to use this is, if you have an unfamiliar table and you're looking with variables with a particular term in them, like VAR1, VAR2,... you may execute something like:

    frame = order(frame,[v for v in frame.columns if "VAR" in v])
    

提交回复
热议问题