Pandas dataframe remove constant column

Given a pandas dataframe, we have to remove constant column. 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.

Problem statement

We are given a DataFrame that may or may not have columns that are the same value.

Remove constant column of a pandas dataframe

We will use pandas.DataFrame.iloc property for this purpose, i in pandas.DataFrame.iloc 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 pandas.DataFrame.iloc property. Inside pandas.DataFrame.iloc property, the index value of the row comes first followed by the number of columns.

Let us understand with the help of an example,

Python program to remove constant column

# Importing pandas package
import pandas as pd

# Creating a dictionary
d = {
    'id':[1,2,3,4],
    'A':[10,7,4,1],
    'B':[0,0,0,0,]
}

# Creating DataFrame
df = pd.DataFrame(d)

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

# Using iloc property
res = df.loc[:, (df != df.iloc[0]).any()]

# Display result
print("Result:\n", res)

Output

The output of the above program is:

Example: Pandas dataframe remove constant column

Python Pandas Programs »

Comments and Discussions!

Load comments ↻





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