Pandas: Change data type from series to string

Given a Pandas DataFrame, we have to change data type from series to string.
Submitted by Pranit Sharma, on June 29, 2022

A Series in pandas contains a single list that can store heterogeneous types of data, because of this, a series is also considered a 1-dimensional data structure.

When we analyze a series, each value can be considered as a separate row of a single column.

Strings, on the other hand, is a group of characters, these characters may consist of all the lower, upper, and special characters present on the keyboard of a computer system. A string is a data type. To convert a series into a string, we will use the astype('string') method. The astype() method is used to convert dtype any value into the specific dtype passed inside it as a parameter.

To work with pandas, we need to import pandas package first, below is the syntax:

import pandas as pd

Let us understand with the help of an example,

Python code to change data type from series to string

# Importing pandas package
import pandas as pd

# Creating a dictionary
d = {
    'Foo':[35,54,'abcd',45,33,'efgh'],
    'Boo':['Agra','Surat','Ajmer','Gwalior','Raipur','Chandigarh'],
    'Coo':['UP','Guj','Raj','MP','Cg','Pb']
}

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

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

# Converting series type to string
df['Foo'] = df['Foo'].astype("string")

# Display dtypes
print(df.dtypes)

Output:

Example: Change data type from series to string

Python Pandas Programs »



ADVERTISEMENT
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.