Python - Find all columns of dataframe in Pandas whose type is float, or a particular type

Given a Pandas DataFrame, we have to find all columns whose type is float, or a particular type.
Submitted by Pranit Sharma, on August 04, 2022

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.

Pandas allows us to find all the columns whose type is any particular data type supported by pandas.

There are multiple data types that are supported by pandas.

  • Int
  • Float
  • Object
  • Boolean
  • Datetime

All these data types can be converted into some other data types using the astype() method.

Find all columns of Pandas dataframe based on a particular type

To find all the columns of DataFrame whose type is float, or a particular type, we will use the select_dtypes() method inside which we will pass a parameter as include=[np.float].

Let us understand with the help of an example,

Python program to find all columns of dataframe in Pandas whose type is float, or a particular type

# Importing pandas package
import pandas as pd

# Creating a dictionary
d = {
    'col1':[1.2,4.4,7.2],
    'col2':[2,5,8],
    'col3':[3.9,6.2,9.1],
    'col4':['A','B','C'],
    'col5':[True,False,True]
}

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

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

# Filtering columns having dtype float
result = df.select_dtypes(include=[float])

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

Output:

Example: Find all columns of whose type is float, or a particular type

Python Pandas Programs »

Comments and Discussions!

Load comments ↻





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