Error message: "object of type 'method' has no len()"

Question:

New to Python, and am trying to code a simple program which takes a user’s input of a music artist, searches for them in a CSV, looks at their genre, and uses this genre to find another, random, music artist of the same genre to output.

However, I am running into this error:

Traceback (most recent call last):
File "c:UsersjOneDriveDesktopartists.py", line 14, in
recommended_artist = random.choice(artist_with_same_genre.name.unique)
File "C:Program FilesWindowsAppsPythonSoftwareFoundation.Python.3.10_3.10.2800.0_x64__qbz5n2kfra8p0librandom.py", line 378, in choice
return seq[self._randbelow(len(seq))]
TypeError: object of type ‘method’ has no len()

Here is my code:

import pandas as pd
import csv
import random

filePath = "spotify_artists.csv"
findartist = input("Enter an artist: ")
db = pd.read_csv(filePath)

target = db[db["name"] == findartist]
if target.shape[0] > 0: 
    print("Artist has been found!") 
    genre = target.reset_index(drop=True).loc[0, "genres"]
    artist_with_same_genre = db[db.genres.apply(lambda l: any([g in genre for g in l]))]
    recommended_artist = random.choice(artist_with_same_genre.name.unique)        
    print(recommended_artist)

Sample of csv (35k+ lines):

id,name,genres
4mGnpjhqgx4RUdsIJiURdo,Juliano Cezar,"['sertanejo', 'sertanejo pop', 'sertanejo tradicional', 'sertanejo universitario']"
6YVY310fjfUzKi8hiqR7iK,Gangway,['danish pop rock']

Upon Googling the error it seems more specific to people’s code, so I’m not sure how to change mine to make it look through all the rows and find one artist of the same genre to output. Any help would be greatly appreciated, thank you.

Asked By: jak

||

Answers:

"artist_with_same_genre.name.unique" is a method.

Try this:

recommended_artist = random.choice(artist_with_same_genre.name.unique())
Answered By: Ilya Gorunov
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.