Dennis Dennis - 2 months ago 13x
Python Question

An Error: 'Numpy.str_' object has no attribute 'decode'

I tried to run a test on Crab(an open source recommender system) based on python3. Then an error occurred:

Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/Users/Dennis/anaconda/lib/python3.5/site-packages/scikits/crab/datasets/", line 201, in load_sample_movies
data_songs[u_ix][i_ix] = float(rating)
ValueError: could not convert string to float: "b'3.0'"

I tried to use 'decode()' to convert the string, but it's not working:

Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/Users/Dennis/anaconda/lib/python3.5/site-packages/scikits/crab/datasets/", line 202, in load_sample_movies
rating = rating.decode('utf-8')
AttributeError: 'numpy.str_' object has no attribute 'decode'

Any help will be appreciated!


The problem is that rating is a string within a string, so when you try casting a string like "b'3.0'" into a float, it gives a valueError because you still have the b in front which cannot be converted into float.

I imagine you need the byte encoding in front of the '3.0', so one way would be to evaluate rating to convert it from a string to bytes before typecasting it into a float (beware though, eval can have some safety issues).

>>> type(eval(rating))
<class 'bytes'>
>>> data_songs[u_ix][i_ix] = float(eval(rating))