Attribute Error

My Code:

autos["price"] = (autos["price"]
                          .str.replace("$","")
                          .str.replace(",","")
                          .astype(int)
                          )
autos["price"].head()

What I expected to happen:

0 5000
1 8500
2 8990
3 4350
4 1350
Name: price, dtype: int64

What actually happened:

AttributeErrorTraceback (most recent call last)
<ipython-input-13-1dd5e2ff59de> in <module>()
      1 
----> 2 autos["price"] = (autos["price"]
      3                           .str.replace("$","")
      4                           .str.replace(",","")
      5                           .astype(int)

/dataquest/system/env/python3/lib/python3.4/site-packages/pandas/core/generic.py in __getattr__(self, name)
   3608         if (name in self._internal_names_set or name in self._metadata or
   3609                 name in self._accessors):
-> 3610             return object.__getattribute__(self, name)
   3611         else:
   3612             if name in self._info_axis:

/dataquest/system/env/python3/lib/python3.4/site-packages/pandas/core/accessor.py in __get__(self, instance, owner)
     52             # this ensures that Series.str.<method> is well defined
     53             return self.accessor_cls
---> 54         return self.construct_accessor(instance)
     55 
     56     def __set__(self, instance, value):

/dataquest/system/env/python3/lib/python3.4/site-packages/pandas/core/strings.py in _make_accessor(cls, data)
   1908             # (instead of test for object dtype), but that isn't practical for
   1909             # performance reasons until we have a str dtype (GH 9343)
-> 1910             raise AttributeError("Can only use .str accessor with string "
   1911                                  "values, which use np.object_ dtype in "
   1912                                  "pandas")

AttributeError: Can only use .str accessor with string values, which use np.object_ dtype in pandas

Pandas and Numpy are imported properly and I verified that there is a column labeled exactly as “price”.

1 Like

Hi @jonathandeleon. The first time I ran your code, I got the desired results. When I ran the cell a second time, though, I got the same error you described here. This happened for me because I had already converted the price column to integers once. Is it possible that the code was run previously and running it again gives the error? (See if you see the results when you run autos["price"].head() in a separate cell.)

2 Likes

Problem solved! That makes sense, thank you.

1 Like

Yes, it happened to me too, exactly the same reason, then I commented out that code part and it solved.

Ran into this error. The suggestion was helpful. Thanks