Convert Integers to Strings in Pandas DataFrame

Here are 2 ways to convert integers to strings in Pandas DataFrame:

(1) Using apply(str):

df["DataFrame Column"] = df["DataFrame Column"].apply(str)

(2) Using astype(str):

df["DataFrame Column"] = df["DataFrame Column"].astype(str)

Steps to Convert Integers to Strings in Pandas DataFrame

Step 1: Create a DataFrame with Integers

To start, create a DataFrame with integers.

For example, here is a DataFrame where the ‘price‘ column contains integers:

import pandas as pd

data = {"product": ["abc", "ddd", "xyz"], "price": [350, 370, 410]}

df = pd.DataFrame(data)

print(df)
print(df.dtypes)

As you can see, the data type of the ‘price‘ column is integer:

  product  price
0     abc    350
1     ddd    370
2     xyz    410
product    object
price       int64
dtype: object

Step 2: Convert the Integers to Strings in Pandas DataFrame

You can then convert the values under the ‘price‘ column from integers to strings using apply(str):

import pandas as pd

data = {"product": ["abc", "ddd", "xyz"], "price": [350, 370, 410]}

df = pd.DataFrame(data)
df["price"] = df["price"].apply(str)

print(df)
print(df.dtypes)

As you can see, the data type of the ‘price’ column is now object, which represents strings:

  product  price
0     abc    350
1     ddd    370
2     xyz    410
product    object
price      object
dtype: object

Similarly, you can convert the integers to strings using astype(str):

import pandas as pd

data = {"product": ["abc", "ddd", "xyz"], "price": [350, 370, 410]}

df = pd.DataFrame(data)
df["price"] = df["price"].astype(str)

print(df)
print(df.dtypes)

You’ll get the same results:

  product  price
0     abc    350
1     ddd    370
2     xyz    410
product    object
price      object
dtype: object

You may also want to check the following tutorials that review the steps to convert:

Leave a Comment