Selecting last n columns and excluding last n columns in dataframe

Given a pandas dataframe, we have to select last n columns and excluding last n columns. By Pranit Sharma Last updated : October 03, 2023

Pandas is a special tool that allows us to perform complex manipulations of data effectively and efficiently. Inside pandas, we mostly deal with a dataset in the form of DataFrame. DataFrames are 2-dimensional data structures in pandas. DataFrames consist of rows, columns, and data.

Selecting last n columns and excluding last n columns

Here we are going to perform two different operations on a Dataframe but conceptually both the operations use iloc method for execution. i in pandas.DataFrame.iloc property stands for 'index'. This is also a data selection method but here, we need to pass the proper index as a parameter to select the required row or column. Indexes are nothing but the integer value ranging from 0 to n-1 which represents the number of rows or columns. We can perform various operations using the pandas.DataFrame.iloc property. Inside the pandas.DataFrame.iloc property, the index value of row comes first followed by the number of columns.

Now, if we want to select the last n columns in a DataFrame, we will use iloc inside which we will select all the rows and when it comes to columns, we will slice our column from n till the end.
On the other hand, if we want to exclude the last n columns, we will again use iloc inside which we will select all the rows but this time, we will slice the columns from the 1st column till the nth column.

Let us understand with the help of an example,

Python program to select last n columns and excluding last n columns in dataframe

# Importing pandas package
import pandas as pd

# Creating a dictionary
d = {
    'A':[10,9,8,20,23,30],
    'B':[1,2,7,5,11,20],
    'C':[1,2,3,4,5,90]
}

# Creating a DataFrame
df = pd.DataFrame(d)

# Display original DataFrame
print("Original Dataframe:\n",df,"\n")

# Declaring a value of n
n = 2

# selecting last n column
res = df.iloc[:,-n:]

# Display last n selected columns
print("Last n column selected:\n",res,"\n")

# Excluding last n columns
res = df.iloc[:,:-n]

# Display last n excluded columns
print("Last n excluded columns:\n",res)

Output

The output of the above program is:

Example: Selecting last n columns and excluding last n columns

Python Pandas Programs »

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.