convert all values in a df in str in python

To convert all values in a Pandas DataFrame to string data type, you can use the astype() method. Here's an example:

main.py
import pandas as pd

# create sample dataframe
df = pd.DataFrame({
    'A': [1, 2, 3],
    'B': [4.5, 5.6, 6.7],
    'C': ['x', 'y', 'z']
})

# convert all values to string
df = df.astype(str)

print(df.dtypes)
211 chars
14 lines

Output:

main.py
A    object
B    object
C    object
dtype: object
50 chars
5 lines

In this example, the astype() method is called on the DataFrame df and passed the argument str to convert all values to string data type. The resulting DataFrame is stored back in df. The dtypes attribute of df is then printed to confirm that all columns contain object (string) data type.

gistlibby LogSnag