Python - Selecting Pandas Columns by dtype

Learn, how can we select pandas DataFrame column on the basis of data type? 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.

In a programming language, data types are the particular format in which a value is being stored. A data type is a kind of data item, which represents what values it can take, the programming language used, or the operations that can be performed on it.

There are multiple data types in pandas,

  • Int: for integer values
  • Float: for decimal values
  • Object: string values
  • Boolean: True or False
  • List
  • Dictionary
  • Set
  • Tuple

Selecting pandas dataframe column on the basis of data type

We will We will select the dataframe column based on data type with the help of with the help of pandas.DataFrame.select_dtypes() method inside which we will pass a parameter call include=[]. This parameter itself accepts the list inside which we will pass the particular data type.

Let us understand with the help of an example,

Python program to select pandas columns by dtype

# Importing pandas package
import pandas as pd

# Creating two dictionaries
d1 = {
    'int':[1,2,3,4,5],
    'float':[1.5,2.5,3.5,4.5,5.5],
    'object':['a','b','c','d','e'],
    'boolean':[True,False,True,False,True]
}

# Creating DataFrame
df = pd.DataFrame(d1)

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

# Selecting on the basis of dtype int
res1 = df.select_dtypes(include=['int'])

# Selecting on the basis of dtype object
res2 = df.select_dtypes(include=['object'])

# Display results
print("DataFrame with type int:\n",res1,"\n")
print("DataFrame with type Object:\n",res2,"\n")

Output

The output of the above program is:

Example: Selecting Pandas Columns by dtype

Python Pandas Programs »

Comments and Discussions!

Load comments ↻





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