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
Reproduce the error
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.
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’
Krunal Lathiya is a seasoned Computer Science expert with over eight years in the tech industry. He boasts deep knowledge in Data Science and Machine Learning. Versed in Python, JavaScript, PHP, R, and Golang. Skilled in frameworks like Angular and React and platforms such as Node.js. His expertise spans both front-end and back-end development. His proficiency in the Python language stands as a testament to his versatility and commitment to the craft.