Turn all items in a dataframe to strings

Given a pandas dataframe, we have to turn all items in a dataframe to strings.
Submitted by Pranit Sharma, on September 09, 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.

How to turn all items in a dataframe to strings?

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.

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

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 code 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:

Turn all items in a dataframe to strings

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.