Turn all items in a dataframe to strings

Given a pandas dataframe, we have to turn all items in a dataframe to strings. By Pranit Sharma Last updated : September 30, 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.

A string is a group of characters, these characters may consist of all the lower case, upper case, and special characters present on the keyboard of a computer system. A string is a data type and the number of characters in a string is known as the length of the string.

Problem statement

Suppose, we have a DataFrame with multiple columns and we need to convert the dtype of each column to a string.

How to turn all items in a dataframe to strings?

We can do this by converting the data type of each column but this will require a lot of effort if there are more columns. A better way to do this is to directly use astype() method with DataFrame.

Let us understand with the help of an example,

Python program to turn all items in a dataframe to strings

# Importing pandas package
import pandas as pd

# Importing numpy package
import numpy as np

# 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")

# Converting all the column to string type
df = df.astype(str)

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

Output

The output of the above program is:

Turn all items in a dataframe to strings

Python Pandas Programs »

Comments and Discussions!

Load comments ↻





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