Built with Tutify.io

    AIStudyLabs

    Convert Multiple Columns to String in Pandas DataFrame

    Convert Multiple Columns to String in Pandas DataFrame

    To convert multiple columns to strings in a Pandas DataFrame, you can use the astype() method and specify the columns you want to convert. In this article, I will explain how to convert multiple columns to strings in a Pandas DataFrame. I will demonstrate the use of methods such as DataFrame.astype(str), DataFrame.apply(str), DataFrame.map(str), and DataFrame.applymap(str) to convert various data types to string format.

    Key Points –

    <a id="h-convert-multiple-columns-to-strings"></a>

    Convert Multiple Columns to Strings

    To convert multiple columns in a Pandas DataFrame to strings, you can use various methods such as astype(), apply(), applymap(), or map().

    Now, let’s see a detailed example. first, create a Pandas DataFrame with a few rows and columns, and execute and validate the results.

    
    import pandas as pd
    import numpy as np
    technologies= ({
       'Courses':["Spark","PySpark","Hadoop","Python","Pandas"],
        'Fee' :[22000,25000,23000,24000,26000],
        'Duration':['30days','50days','55days','40days','60days'],
        'Discount':[1000,1200,2500,1300,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 multiple columns in a DataFrame to strings, you can use the astype(str) method. You can check the data type of each column by using the dtypes attribute.

    
    # Basic Conversion of Multiple Columns to Strings
    df[['Fee', 'Discount']] = df[['Fee', 'Discount']].astype(str)
    print("Data Types after Conversion:\n", df.dtypes)
    

    Here,

    <a id="h-convert-all-columns-to-strings"></a>

    Convert All Columns to Strings

    If you need to convert the data type of all columns in the DataFrame to strings, you can use the df.astype(str) method.

    
    # Convert all columns to strings
    df = df.astype(str)
    print("Data Types after Conversion:\n", df.dtypes)
    

    Here,

    Yields the same output as above.

    <a id="h-convert-columns-using-apply-with-lambda"></a>

    Convert Columns Using apply() with lambda

    You can convert multiple columns in a DataFrame to strings by using apply() with a lambda function. This method is flexible and allows you to apply transformations to specific columns.

    
    # Convert specific columns to strings using apply() with lambda
    df[['Fee', 'Discount']] = df[['Fee', 'Discount']].apply(lambda x: x.astype(str))
    print("Data Types after Conversion:\n", df.dtypes)
    

    Here,

    Using apply() with a lambda is an efficient way to convert specific columns while leaving the rest of the DataFrame unchanged. Yields the same output as above.

    <a id="h-convert-all-columns-to-string-using-applymap"></a>

    Convert All Columns to String Using applymap()

    To convert all columns in a DataFrame to strings using applymap(), you can apply a lambda function to each element in the DataFrame.

    
    # Convert all columns to strings using applymap()
    df = df.applymap(lambda x: str(x))
    print("Data Types after Conversion:\n", df.dtypes)
    

    Here,

    Yields the same output as above.

    <a id="h-convert-multiple-columns-to-string-using-map-str"></a>

    Convert Multiple Columns to String Using map(str)

    You can also use the map() function on each column (as a Pandas Series) to convert specific columns to strings.

    
    # Convert specific columns to strings 
    # Using series.map()
    df['Fee'] = df['Fee'].map(str)
    df['Discount'] = df['Discount'].map(str)
    print("Data Types after Conversion:\n", df.dtypes)
    

    Here,

    Yields the same output as above.

    <a id="h-faq-on-nbsp-convert-multiple-columns-to-string"></a>

    FAQ on Convert Multiple Columns to String

    You can use the astype(str) method, selecting multiple columns with double square brackets, like df[['col1', 'col2']].astype(str).

    By applying astype(str) to the entire DataFrame: df = df.astype(str). This will convert all columns to strings.

    Use df.dtypes to check each column’s data type. After conversion, the specified columns should display object as the data type, which represents strings in Pandas

    When columns contain mixed types (e.g., numbers and text), astype(str) can still handle the conversion, but make sure it aligns with your intended data structure since numeric data will also be treated as strings afterward.

    You can use select_dtypes() to select columns by data type before converting them.

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

    Conclusion

    In this article, I have explained how to convert multiple columns to string type in Pandas using the DataFrame.astype(str) and DataFrame.apply(str) methods. Additionally, you explored how to convert columns to strings using the DataFrame.map(str) and DataFrame.applymap(str) methods.

    Happy Learning !!

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

    Related Articles

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

    References