Drop non-numeric columns from a pandas dataframe

Given a pandas dataframe, we have to drop non-numeric columns. By Pranit Sharma Last updated : September 29, 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

Suppose we have a DataFrame df with multiple columns A, B, and C. Suppose, the data type of column A is an object, the data type of B is a number (int) and the data type of column C is a list.

Dropping non-numeric columns

We need to filter out that column that has a data type int. For this purpose, we will use df.get_numeric_data() method.

Let us understand with the help of an example,

Python program to drop non-numeric columns from a pandas dataframe

# Importing pandas package
import pandas as pd

# Importing methods from sklearn
from sklearn.preprocessing import MinMaxScaler

# Creating a dictionary
d = {
    'A':['Madison','California','Boston','Las Vegas'],
    'B':[1,2,3,4],
    'C':[[1,2,3],[4,5,6],[7,8,9],[10,11,12]]
}

# Creating DataFrame
df = pd.DataFrame(d)

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

# Finding that column that has only numbers
result = df._get_numeric_data()

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

Output

The output of the above program is:

Example: Drop non-numeric columns from a pandas dataframe

Python Pandas Programs »

Comments and Discussions!

Load comments ↻





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