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

This article will explain the AttributeError: can only use .str accessor with string values! the causes for it, and how to resolve it. By looking at the error, you can anticipate that something must have gone wrong because of the datatype. These are common errors you experience when working with Pandas dataframe in Python.

Let us look and try to understand the cause of the AttributeError: can only use .str accessor with string values! error and the ways to rectify it.

What is the problem of AttributeError? You can only use .str accessor with string values! mean?

Here .str accessor symbolizes using a specific method that can only be used with string values. When we try using this method on values other than string then AttributeError: can only use .str accessor with string values! error is generally raised. To avoid this error, you should use only string values and nothing other than that.

What generates the problem of AttributeError: Can only use .str accessor with string values!?

The problem of AttributeError: can only use .str accessor with string values! arises while using the ‘.str’ accessor on values that are not strings. This can occur when you attempt to substitute a certain DataFrame (pandas) pattern that is present in a string column, but the column you are working on is not a string.

import pandas as pd

data = pd.DataFrame({"a": [10, 20, 30]}) 

data.a.str.lower()

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

Look at the code above; it is easy to identify the mistake from the warning. Here, you can see that a string is used on an array consisting of numeric values. You cannot use integers and strings together like this. Here, ‘a’ contains integers, not a string, whereas ‘a’ symbolizes a string itself. There are several causes of generation of this error. Let’s look at them;

  • Using .str accessor on a date-time column.
  • Applying this accessor to a None or a Boolean type of data.
  • Calling .str accessor method on an integer or float or other numeric columns.
  • Using diverse datatypes in the same and exclusive column.

How to resolve the AttributeError: can only use .str accessor with string values! error?

Resolving AttributeError: can only use .str accessor with string values! error is indeed an easy task. First and foremost, you should check whether you are calling string values only and not other data types like integers, floats, lists, etc.; if you are stuck due to the error, then check these ways out.

Using astype()

This function is used to convert the given values into the strings beforehand using the .str accessor. Pandas astype() is a method that forms any object into a specified data type. Here, the integers are converted into strings, and the values are returned with their indexes. The astype() method can also be used to compare any column data type.

import pandas as pd
data = pd.DataFrame({"a": [10, 20, 30]})
data.a = data.a.astype(str)
data.a.str.lower() 

Output:

#Returns  0    10
                1    20
                2    30
                Name: a, dtype: object

Using apply()

It is one of the common methods of preprocessing of data. This method is used in Pandas to pass any required function and apply it to each element present in the series. This function’s ability to apply the appropriate DataFrame to the function employed as the necessary input makes it beneficial.

import pandas as pd

data = pd.DataFrame({
    'roll no.': [1, 2, 3, 4],
    'name': ['Alan', 'Bob', 'Mario', 'James'],
    'marks': [75,82, 90, 42],
})
data['marks'] = data['marks'].apply(lambda x: str(x))
print(data)

Output:

#Returns 
               roll no.   name marks
               0         1   Alan    75
               1         2    Bob    82
               2         3  Mario    90
               3         4  James    42

In the above code, we have used replace and lambda functions and apply(). Here, lambda’s anonymous function is called using every floating-point value. This returns the result of the string values.

FAQs

Can I convert all the columns to strings beforehand?

Yes, if you wish, then you can. But it is best to convert columns to strings only when needed. If you convert it beforehand, it will eat up your memory, and you will eventually lose the type of information.

Is it possible to use .str techniques directly on indices or series?

Yes, it is possible, as a string is also a type of series, and the indices and series should only contain the string data.

Conclusion

To conclude, AttributeError: can only use .str accessor with string values! error will be prevented by applying string methods to only the string data. If string methods are applied to non-string data, it is apparent that your code will throw an error. Always be conscious of what data type and frames you apply in Python programming.

References

  1. astype()
  2. string

To learn more about fixes for common mistakes when writing in Python, follow us at Python Clear.

Leave a Comment