Convert columns to string in Pandas
To convert all columns in a Pandas DataFrame to strings, you can use the following code snippet:
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)
Watch a video course
Python - The Practical Guide
Alternatively, you can also 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.
df['A'] = df['A'].astype(str)