The AttributeError: can only use str accessor with string values error occurs in Python when are trying to use a string accessor on a value that is not a string. String accessors are methods specific to string objects and can only be used on values that are strings.
import pandas as pd
df = pd.DataFrame({'data': [11, 21, 19]})
df.data.str.replace('x', 'y')
print(df)
Output
AttributeError: Can only use .str accessor with string values!
In this code, we got the AttributeError because the `data` column has integer values, not string values.
Python .str accessor is used to access individual characters in a string. The accessor allows you to index into a string using square brackets. For example, string[0].
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 AttributeError: can only use .str accessor with string values
- To fix the AttributeError: can only use .str accessor with string values error in Python, ensure that you are only using the .str accessor on string values.
- Use the type() function to check the data type of objects.
- Ensure that you use the
+
operator to concatenate strings, not the,
operator. - Make sure that you use the correct type of quotes around your strings.
- Use the isinstance() function to check if an object is an instance of a specific data type.
Method 1: Using the type() function
The type() is a built-in Python function that returns the data type of an input object.
import pandas as pd
df = pd.DataFrame({'data': [11, 21, 19]})
print(type(df.data[0]))
Output
<class 'numpy.int64'>
You can see that the value’s data type is `numpy.int64`. Now, if you try to apply a string function on integer values, it will throw the error.
Method 2: Using instance() function
The isinstance() method checks if an object is an instance of a particular type.
import pandas as pd
import numpy as np
df = pd.DataFrame({'data': [11, 21, 19]})
print(isinstance(df.data[0], np.int64))
Output
True
You can see that the data type of value is np.int64, and that’s why the isinstance() function returns True because it’s an integer data type and not a string data type.
Conclusion
Avoid accessing a string method or attribute on a non-string object; otherwise, you might get this type of AttributeError.
Use the type() or isinstance() method to verify the object’s data type at any time.
That’s it.