• Post author:
  • Post category:Pandas
  • Post last modified:December 4, 2024
  • Reading time:16 mins read
You are currently viewing Pandas Convert Integer to String in DataFrame

To convert an integer column to a string in a pandas DataFrame, you can use the astype(str) method. Additionally, other Pandas functions like apply(), applymap(), and map() can also convert integers to strings in a DataFrame or series. In this article, I will explain how to convert single or multiple integer columns to string type in a DataFrame with examples.

Advertisements

Key Points –

  • Use the .astype(str) method to convert integer columns to strings.
  • Convert all integer columns to strings by applying .astype(str) on the DataFrame.
  • Convert integer values to strings using the .map(str) function for series.
  • Use .apply(lambda x: f"{x}") for adding custom formats during conversion.
  • Check the data type using .dtypes or .info() after conversion to ensure correctness.
  • Use .applymap(str) if you need to convert all values in the entire DataFrame to strings.
  • .convert_dtypes() is a method that can handle conversion of data types, but may not always convert integers to strings directly.
  • Converting to string can help in data manipulation tasks like concatenation or formatted outputs.

Convert Integer to String using astype()

To convert integers to strings in a Pandas DataFrame, you can use the .astype(str) method, which is straightforward and efficient. Converting integers to strings can be necessary for various reasons, such as preparing data for visualization, exporting data to a text-based format (like CSV), combining numerical and text data, or maintaining consistent data types across columns for further processing.

To run some examples of converting integer to string in pandas DataFrame, let’s create Pandas DataFrame using data from a dictionary.


# Create the DataFrame
import pandas as pd
import numpy as np
technologies= ({
   'Courses':["Spark","PySpark","Hadoop","Pandas"],
    'Fee' :[22000,25000,24000,26000],
    'Duration':['30days','50days','40days','60days'],
    'Discount':[1000,2300,2500,1400]
              })
df = pd.DataFrame(technologies)

print("Create DataFrame:\n", df)
print("------------------------------------")
print("Get type of the columns of DataFrame:\n", df.dtypes)

Yields below output.

pandas convert integer string

To convert a single column in the DataFrame to a string, you can use the .astype(str) method. It will convert the specific column type from integer to string.


# Convert the 'Fee' column to string
df['Fee'] = df['Fee'].astype(str)
print("Data types after conversion:\n", df.dtypes)

Here,

  • The .astype(str) method is applied to the 'Fee' column to convert all integer values in this column to strings.
  • The printed DataFrame shows the updated 'Fee' column with string values, and the data types are displayed to confirm the change.
pandas convert integer string

Using astype(str) for the Entire DataFrame

Alternatively, you can convert all columns in a DataFrame to string type using the .astype(str) method. By passing the entire DataFrame into this function, it will convert the data type of all columns to strings.


# Convert the entire DataFrame to string
df = df.astype(str)
print("Data types after conversion:\n", df.dtypes)

# Output:
# Data types after conversion:
# Courses     object
# Fee         object
# Duration    object
# Discount    object
# dtype: object

Here,

  • The .astype(str) method is applied to the DataFrame df to convert all columns to string types.
  • When printed, the DataFrame will reveal that all values have been transformed into strings, and the displayed data types will confirm this change.

Convert Integer to String Using apply() Method

To convert a single column in a Pandas DataFrame to strings using the apply(str) method, you can apply it directly to the specified column.


# Convert the 'Fee' column to string using apply(str)
df['Fee'] = df['Fee'].apply(str)
print("Data types after conversion:\n", df.dtypes)

# Output:
# Data types after conversion:
# Courses     object
# Fee         object
# Duration    object
# Discount     int64
# dtype: object

In the above example, the apply(str) method is call on the 'Fee' column. This method applies the str function to each element in the column, transforming each integer value into a string. The resulting string values are then reassigned to the 'Fee' column. Finally, the data types of all columns are shown to verify that the 'Fee' column is now of type object, indicating it contains strings.

Similarly, to convert integers to strings using the apply() method in Pandas, you can use a lambda function. This approach allows for more complex transformations if needed.


# Convert the 'Fee' column to string using apply()
df['Fee'] = df['Fee'].apply(lambda x: str(x))
print("Data types after conversion:\n", df.dtypes)

In the above example, the apply() method is called on the 'Fee' column. A lambda function is provided to apply(), which converts each value x from the column to a string using str(x). This process replaces the original integer values in the 'Fee' column with their corresponding string represe.

Convert a Series to String Using map(str) Method

To convert a Pandas Series to strings using the map(str) method, you can apply the str function to each element in the Series. This method is similar to apply() but can be more concise for this specific task.


# Convert the 'Fee' column to string using map(str)
df['Fee'] = df['Fee'].map(str)
print("Data types after conversion:\n", df.dtypes)

# Output:
# Data types after conversion:
# Courses     object
# Fee         object
# Duration    object
# Discount     int64
# dtype: object

Here,

  • The map(str) method is called on the 'Fee' column.
  • This applies the str function to each element in the column, converting each integer value to a string.
  • The converted values replace the original integer values in the 'Fee' column.

Using applymap(str) on the Entire DataFrame

Finally, to convert all the values in a pandas DataFrame to strings using the applymap(str) method.


# Convert the entire DataFrame to strings 
# Using applymap(str)
df = df.applymap(str)
print("Data types after conversion:\n", df.dtypes)

# Output:
# Data types after conversion:
# Courses     object
# Fee         object
# Duration    object
# Discount    object
# dtype: object

In the above example, this function applies the str function to every value in the DataFrame, converting each entry to a string. By checking df.dtypes, you can verify that all columns have been changed to the object type, which is how pandas represents strings.

FAQ on Pandas Convert Integer to String in DataFrame

How can I convert a single column of integers to strings?

To convert a single column of integers to strings in a pandas DataFrame, you can use the astype(str) method.

How do I convert multiple columns of integers to strings?

To convert multiple columns of integers to strings in a pandas DataFrame, you can use the astype(str) method and specify the columns to target.

Can I convert all integer columns in the DataFrame to strings?

ou can convert all integer columns in a DataFrame to strings using the select_dtypes() function to target columns with an integer data type.

Can I add a prefix or suffix while converting to strings?

You can add a prefix or suffix while converting columns to strings using the apply() method or astype(str) in combination with string operations.

Is there a way to convert the entire DataFrame to strings?

You can convert the entire DataFrame to strings in Pandas using the astype() function.

Conclusion

In conclusion, converting integer to string in a Pandas DataFrame is a common operation that can be accomplished using methods like astype(str), apply(str), applymap(str), or map(str). This process is essential for data manipulation tasks where uniform data types are required, such as data formatting, exporting, or text processing.

Happy Learning!!

Reference