Q:

How to convert column value to string in pandas DataFrame?

belongs to collection: Python Pandas Programs

0

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

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

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

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Python Pandas Programs

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
How to find the installed pandas version?... >>
<< How to select rows with one or more nulls from a P...