Pandas: Change data type from series to string

Given a Pandas DataFrame, we have to change data type from series to string. By Pranit Sharma Last updated : September 23, 2023

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.

Changing data type from series to string

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.

Note

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 program 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

The output of the above program is:

Example: Change data type from series to string

Python Pandas Programs »

Comments and Discussions!

Load comments ↻





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