Fix: Can only use .str accessor with string values.

The .str accessor is a method that can be used to access or modify values in a string. This means it can only be used with string values, and not with other data types such as integers or floats. If you try to use the .str accessor on a value that is not a string, you will get an error. Therefore, if you want to use the .str accessor, you must make sure you are using it with a string value.


One error you may encounter when using Python is:

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

This error usually occurs when you attempt to replace a pattern in a string column of a pandas DataFrame, but the column you’re working with isn’t actually a string.

The following example shows how to fix this error in practice.

How to Reproduce the Error

Suppose we have the following pandas DataFrame:

import pandas as pd

#create DataFrame
df = pd.DataFrame({'team': ['A', 'A', 'A', 'A', 'B', 'B', 'B', 'B'],
                   'points': [6.5, 7.8, 8.0, 9.0, 7.5, 3.4, 6.6, 6.8],
                   'assists': [5, 7, 7, 9, 12, 9, 9, 4],
                   'rebounds': [11, 8, 10, 6, 6, 5, 9, 12]})

#view DataFrame
df

	team	points	assists	rebounds
0	A	6.5	5	11
1	A	7.8	7	8
2	A	8.0	7	10
3	A	9.0	9	6
4	B	7.5	12	6
5	B	3.4	9	5
6	B	6.6	9	9
7	B	6.8	4	12

Now suppose we attempt to replace every decimal in the “points” column with a blank:

#attempt to replace decimal in "points" column with a blank
df['points'] = df['points'].str.replace('.', '')

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

We receive an error because the “points” column is not a string column.

How to Fix the Error

The easiest way to get around this error is to use the .astype(str) function before attempting to replace any values in the “points” column:

#replace decimal in "points" column with a blank
df['points'] = df['points'].astype(str).str.replace('.', '')

#view updated DataFrame
df

	team	points	assists	rebounds
0	A	65	5	11
1	A	78	7	8
2	A	80	7	10
3	A	90	9	6
4	B	75	12	6
5	B	34	9	5
6	B	66	9	9
7	B	68	4	12

Notice that each decimal in the “points” column has been replaced and we don’t receive any error since we used the .astype(str) function before attempting to replace any values in the “points” column.

Note: You can find the complete documentation for the replace() function .

The following tutorials explain how to fix other common errors in Python:

x