How to set dtypes by column in pandas dataframe?

Given a pandas dataframe, we have to set dtypes by column in it.
Submitted by Pranit Sharma, on September 12, 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.

Setting dtypes by column in pandas dataframe

Suppose, we have a DataFrame with multiple columns and all columns have the same data type.

We need to set the actual data type to all the columns. For this purpose, we will create a dictionary with keys representing the column names and values representing the data types.

Dictionaries are used to store heterogeneous data. The data is stored in key:value pair. A dictionary is a mutable collection and ordered in nature and does not allow duplicates which mean there are unique keys in a dictionary.

A dictionary key can have any type of data as its value, for example, a list, tuple, string, or dictionary itself.

We will loop over this dictionary and set the data type of each column as the value for each key.

Let us understand with the help of an example,

Python code to set dtypes by column in pandas dataframe

# Importing pandas package
import pandas as pd

# Creating a dictionary
d = {
    'one':[1,2,3,4,5],
    'two':[1.2,2.3,3.4,4.5,5.6],
    'three':[True,True,False,False,True]
}

# Creating DataFrame
df = pd.DataFrame(d)

# Display the DataFrame and its dtype
print("Original DataFrame:\n",df,"\n")
print("Data type of original DataFrame is:\n",df.dtypes,"\n")

# Dictionary of columns and dtype
d2 = {'one':'float','two':'str','three':'str'}

# setting the dtypes
for k, v in d2.items():
    df[k] = df[k].astype(v)

# Display result
print("Modified Data type of DataFrame:\n",df.dtypes,"\n")

Output:

Example: Set dtypes by column in pandas dataframe

Python Pandas Programs »



ADVERTISEMENT
ADVERTISEMENT




Comments and Discussions!




Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.