How to rearrange Pandas column sequence?

后端 未结 6 510
暗喜
暗喜 2020-12-08 05:16
>>> df =DataFrame({\'a\':[1,2,3,4],\'b\':[2,4,6,8]})
>>> df[\'x\']=df.a + df.b
>>> df[\'y\']=df.a - df.b
>>> df
   a  b   x  y
0          


        
6条回答
  •  既然无缘
    2020-12-08 05:45

    There may be an elegant built-in function (but I haven't found it yet). You could write one:

    # reorder columns
    def set_column_sequence(dataframe, seq, front=True):
        '''Takes a dataframe and a subsequence of its columns,
           returns dataframe with seq as first columns if "front" is True,
           and seq as last columns if "front" is False.
        '''
        cols = seq[:] # copy so we don't mutate seq
        for x in dataframe.columns:
            if x not in cols:
                if front: #we want "seq" to be in the front
                    #so append current column to the end of the list
                    cols.append(x)
                else:
                    #we want "seq" to be last, so insert this
                    #column in the front of the new column list
                    #"cols" we are building:
                    cols.insert(0, x)
    return dataframe[cols]
    

    For your example: set_column_sequence(df, ['x','y']) would return the desired output.

    If you want the seq at the end of the DataFrame instead simply pass in "front=False".

提交回复
热议问题