Move the last column to the first column in a DataFrame
Introduction
To rearrange columns in a Pandas DataFrame, you can use the indexing operator []
and the iloc
indexer. Here's an example of how to move the last column to the first of a DataFrame:
import pandas as pd
# create a sample DataFrame
df = pd.DataFrame({'A': [1, 2, 3], 'B': [4, 5, 6], 'C': [7, 8, 9]})
# move last column to first
last_col = df.iloc[:, -1]
# extract last column
df = pd.concat([last_col, df.iloc[:, :-1]], axis=1)
# concatenate last column with all other columns except last
Note that this method works for any DataFrame with at least two columns. If your DataFrame has only one column, you cannot move the last column to the first as there is no other column to swap it with.
In this example, we first create a sample DataFrame with columns 'A', 'B', and 'C'. To move the last column ('C') to the first, we extract it using the iloc indexer and the -1 index, which represents the last column. We then concatenate the extracted last column with all other columns except the last using the pd.concat()
function along the axis=1
direction. This results in a new DataFrame with the last column moved to the first.
Moving the last n columns to the front of a DataFrame
To move the last n columns of a Pandas DataFrame to the front, you can use the same method as above, but with a slight modification. Instead of extracting the last column using -1
, you can use -n
to extract the last n columns. Then, concatenate the extracted columns with all other columns except the last n using pd.concat()
along the axis=1
direction.
Here's an example of how to move the last 2 columns to the front of a DataFrame:
import pandas as pd
# create a sample DataFrame
df = pd.DataFrame({'A': [1, 2, 3], 'B': [4, 5, 6], 'C': [7, 8, 9], 'D': [10, 11, 12], 'E': [13, 14, 15]})
# move last 2 columns to front
n = 2
last_cols = df.iloc[:, -n:] # extract last 2 columns
df = pd.concat([last_cols, df.iloc[:, :-n]], axis=1) # concatenate last 2 columns with all other columns except last 2
In this example, we first create a sample DataFrame with columns 'A', 'B', 'C', 'D', and 'E'. To move the last 2 columns ('D' and 'E') to the front, we extract them using the iloc
indexer and the -2:
index, which represents the last 2 columns. We then concatenate the extracted last 2 columns with all other columns except the last 2 using the pd.concat()
function along the axis=1
direction. This results in a new DataFrame with the last 2 columns moved to the front.
Custom Function
As with some of the other functions, you can create your own custom function within a package that houses a number of different functions you use.
def moveNcolumns(df:pd.DataFrame, n:integer):
df = pd.concat([last_cols, df.iloc[:, :-n]], axis=1)
return df
When calling this function you would call it was something to the effect of:
df = tools.moveNcolumns(df,2)