Built with Tutify.io

    AIStudyLabs

    Pandas Convert Integer to String in DataFrame

    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.

    Key Points –

    <a id="h-convert-integer-to-string-using-astype"></a>

    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.

    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,

    <a id="h-using-astype-str-for-the-entire-dataframe"></a>

    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,

    <a id="h-convert-integer-to-string-using-apply-method"></a>

    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.

    <a id="h-convert-a-series-to-string-using-map-str-method"></a>

    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,

    <a id="h-using-applymap-str-on-the-entire-dataframe"></a>

    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.

    <a id="h-faq-on-pandas-convert-integer-to-string-in-dataframe"></a>

    FAQ on Pandas Convert Integer to String in DataFrame

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

    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.

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

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

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

    <a id="h-conclusion"></a>

    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!!

    <a id="h-related-articles"></a>

    Related Articles

    <a id="h-reference"></a>

    Reference