How to Fix AttributeError: can only use .str accessor with string values

AttributeError: can only use str accessor with string values error typically occurs “when trying to replace a pattern in a string column of a pandas DataFrame, but the column you are working with isn’t a string.”

To fix the error, “use the .astype() method.”

Flow diagram

Diagram of How to Fix AttributeError: can only use .str accessor with string values

Reproduce the error

Visual representation of AttributeError - Can only use .str accessor with string values

import pandas as pd

df = pd.DataFrame({'col': [11, 21, 33]})

df['first_digit'] = df['col'].str[0] # Extracts the first character

print(df)

Output

AttributeError: Can only use .str accessor with string values!

The .str accessor only works on string values. If you use it on an object that is not a string, you will get an AttributeError.

How to fix the error?

    To use the .str.replace() method, you need to convert the integer column to a string column using the .astype(str) method.

    Fixing the TypeError

    import pandas as pd
    
    df = pd.DataFrame({'col': [11, 21, 33]})
    
    # Convert the 'col' column to string type
    df['col'] = df['col'].astype(str)
    
    df['first_digit'] = df['col'].str[0] # Extracts the first character
    
    print(df)
    

    Output

       col   first_digit
    0  11       1
    1  21       2
    2  33       3
    

    And we fixed the error.

    Related posts

    AttributeError: ‘DataFrame’ object has no attribute ‘str’

    AttributeError: ‘series’ object has no attribute ‘split’

    Leave a Comment

    This site uses Akismet to reduce spam. Learn how your comment data is processed.