Skip to content

Convert columns to string in Pandas

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

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

python
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

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

Do you find this helpful?

Dual-run preview — compare with live Symfony routes.