W3docs

Convert columns to string in Pandas

To convert all columns in a Pandas DataFrame to strings, you can use the following code snippet:

To convert all columns in a Pandas DataFrame to strings, you can use the following code snippet:

Convert all columns in a Pandas DataFrame to strings

import pandas as pd

# Create a sample dataframe
df = pd.DataFrame({'A': [1, 2, 3], 'B': [4, 5, 6], 'C': [7, 8, 9]})

# Convert all columns to strings
df = df.astype(str)

<div class="alert alert-info flex not-prose"> Watch a course <span class="hidden md:block">Watch a video course </span> Python - The Practical Guide</div>

Alternatively, you can also use the applymap() function to convert all elements of the DataFrame to strings:

Use the applymap() function to convert all elements of the DataFrame to strings

df = df.applymap(str)

You can also convert specific columns to string by selecting that column and then use above method on it.

Convert specific columns to string by selecting that column

df['A'] = df['A'].astype(str)