Debug School

rakesh kumar
rakesh kumar

Posted on

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

my code is

 data = pd.read_csv('quikr_car.csv')
`data['Price']=data['Price'].str.replace(',','')`
Enter fullscreen mode Exit fullscreen mode

error
`File ~\anaconda3\lib\site-packages\pandas\core\accessor.py:182, in CachedAccessor.get(self, obj, cls)
179 if obj is None:
180 # we're accessing the attribute of the class, i.e., Dataset.geo
181 return self.accessor
--> 182 accessor_obj = self._accessor(obj)
183 # Replace the property with the accessor object. Inspired by:
184 # https://www.pydanny.com/cached-property.html
185 # We need to use object.
setattr_ because we overwrite setattr on
186 # NDFrame
187 object.setattr(obj, self._name, accessor_obj)

File ~\anaconda3\lib\site-packages\pandas\core\strings\accessor.py:181, in StringMethods.init(self, data)
178 def init(self, data) -> None:
179 from pandas.core.arrays.string_ import StringDtype
--> 181 self._inferred_dtype = self._validate(data)
182 self._is_categorical = is_categorical_dtype(data.dtype)
183 self._is_string = isinstance(data.dtype, StringDtype)

File ~\anaconda3\lib`

Solution

data['Price'] = data['Price'].astype(str).str.replace(',', '')
Enter fullscreen mode Exit fullscreen mode

The error message you received indicates that the column you're trying to modify, data['Price'], is not recognized as a string column. The .str accessor in pandas is specifically used for string operations.

To fix this issue, you can try converting the column to string type before using the .str.replace() function. Here's an updated version of the code:

data['Price'] = data['Price'].astype(str).str.replace(',', '')
Enter fullscreen mode Exit fullscreen mode

In this code, the .astype(str) converts the column to a string type, allowing you to use the .str accessor. Then, the .str.replace(',', '') function is applied to replace the comma character with an empty string.

Top comments (0)