+2 votes
in Programming Languages by (77.2k points)

I want to make the last column the first column in an existing DataFrame. How can I do this?

E.g.:

 A   B   C

11  21  31

12  22  32

13  23  33

to

 C   A   B

31  11  21

32  12  22

33  13  23

1 Answer

+1 vote
by (354k points)
selected by
 
Best answer

You can try one of the following approaches:

1. Get the values of the last column in a variable, drop the last column, and insert it to the DataFrame as the first column.

Example:

>>> import pandas as pd
>>> a={'A':[11,12,13], 'B':[21,22,23],'C':[31,32,33]}
>>> df=pd.DataFrame(a)
>>> df
    A   B   C
0  11  21  31
1  12  22  32
2  13  23  33
>>> v=df[list(df.columns)[-1]] #get the values of the last column
>>> df=df.drop(['C'],axis=1)  #drop the column
>>> df
    A   B
0  11  21
1  12  22
2  13  23
>>> df.insert(0,'C',v) #insert as the first column
>>> df
    C   A   B
0  31  11  21
1  32  12  22
2  33  13  23

2. Get the column names of the DataFrame in a list, rearrange the list of columns in your desired order, and use the rearranged list as an index for the DataFrame.

>>> import pandas as pd
>>> a={'A':[11,12,13], 'B':[21,22,23],'C':[31,32,33]}
>>> df=pd.DataFrame(a)
>>> df
    A   B   C
0  11  21  31
1  12  22  32
2  13  23  33
>>> cols = list(df.columns)  #column names
>>> cols
['A', 'B', 'C']
>>> cols = [cols[-1]] + cols[:-1]  #make last column first
>>> cols
['C', 'A', 'B']
>>> df=df[cols]
>>> df
    C   A   B
0  31  11  21
1  32  12  22
2  33  13  23


...