Pandas How To Uncategorized How to cast to string in Pandas

How to cast to string in Pandas

In Pandas, you can convert a column in a DataFrame to a string type by using the astype() method and specifying str as the argument. For example:

import pandas as pd
df = pd.DataFrame({"col1": [1, 2, 3, 4], "col2": [10, 20, 30, 40]})
df["col1"] = df["col1"].astype(str)

The resulting DataFrame will have the col1 column cast to the string type:

col1 col2
0 1 10
1 2 20
2 3 30
3 4 40

You can also cast multiple columns to string type by passing a list of column names to astype():

df[["col1", "col2"]] = df[["col1", "col2"]].astype(str)

The resulting DataFrame will have both col1 and col2 cast to the string type:

col1 col2
0 1 10
1 2 20
2 3 30
3 4 40
Tags:

Leave a Reply

Your email address will not be published. Required fields are marked *

Related Post