ADVERTISEMENT
ADVERTISEMENT

How to convert column value to string in pandas DataFrame?

Given a DataFrame, we need to convert a column value which is not of string type into string data type.
Submitted by Pranit Sharma, on May 17, 2022

A string is a group of characters. A string can contains any type of character including numerical characters, alphabetical characters, special characters, etc.

To check the data type of each column in a DataFrame, we use pandas.DataFrame.info() method which tells us about every piece of information of the DataFrame.

Syntax of pandas.DataFrame.info() Method:

DataFrame.info(
    verbose=None, 
    buf=None, 
    max_cols=None, 
    memory_usage=None, 
    show_counts=None, 
    null_counts=None
    )

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

import pandas as pd

Example for converting column value to string in pandas DataFrame

# Importing Pandas package
import pandas as pd

# Create a dictionary
d = {
    'One':[1,2,3,4],
    'Two':['One','Two','Three','Four']
}

# Create DataFrame
df = pd.DataFrame(d)

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

Output:

Example 1: convert column value to string

Now let's understand how pandas.DataFrame.info() works?

# Display df.info
print(df.info())

Output:

Example 2: convert column value to string

We can observe that the values of column 'One' is an int, we need to convert this data type into string or object.

For this purpose we will use pandas.DataFrame.astype() and pass the data type inside the function.

Let us understand with the help of an example,

# Importing Pandas package
import pandas as pd

# Create a dictionary
d = {
    'One':[1,2,3,4],
    'Two':['One','Two','Three','Four']
}

# Create DataFrame
df = pd.DataFrame(d)

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

# Display df.info
print("Original Data Type:\n",df.info())


# Converting column One values into string type
df['One'] = df['One'].astype('string')

# Display df.info
print("New Data Type:\n",df.info())

Output:

Example 3: convert column value to string

Python Pandas Programs »



ADVERTISEMENT
ADVERTISEMENT


Comments and Discussions!



ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT

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.