服装推荐系统用户画像构建报错:'numpy.int64'对象不可迭代
Hey there! Let's dig into this error and fix it up.
What's Causing the Error?
The TypeError: 'numpy.int64' object is not iterable happens because when a user has only one interaction record, interactions_person_df['contentId'] returns a single numpy.int64 scalar value instead of an iterable sequence (like a list or pandas Series). When this scalar gets passed to get_item_profiles, the function tries to loop over it— which doesn't work for a single number.
Quick Fixes
We just need to ensure contentId is always an iterable, even when there's only one entry. Here are two straightforward solutions:
Solution 1: Force contentId to be a list in build_users_profile
Modify the line where you fetch content IDs to convert them to a list, regardless of how many entries there are:
def build_users_profile(person_id, interactions_indexed_df): interactions_person_df = interactions_indexed_df.loc[person_id] # Ensure content_ids is always a list if isinstance(interactions_person_df['contentId'], np.int64): content_ids = [interactions_person_df['contentId']] else: content_ids = interactions_person_df['contentId'].tolist() user_item_profiles = get_item_profiles(content_ids) user_item_strengths = np.array(interactions_person_df['eventStrength']).reshape(-1,1) # Weighted average of item profiles by the interactions strength user_item_strengths_weighted_avg = np.sum(user_item_profiles.multiply(user_item_strengths), axis=0) / np.sum(user_item_strengths) user_profile_norm = sklearn.preprocessing.normalize(user_item_strengths_weighted_avg) return user_profile_norm
Solution 2: Add a safety check in get_item_profiles
Update the get_item_profiles function to automatically wrap single IDs in a list:
def get_item_profiles(ids): # Handle single ID case by wrapping it in a list if isinstance(ids, np.int64): ids = [ids] item_profiles_list = [get_item_profile(x) for x in ids] item_profiles = scipy.sparse.vstack(item_profiles_list) return item_profiles
This way, no matter if you pass a single ID or a list of IDs, the function can iterate over it safely.
Why This Works
Pandas has a quirk where accessing a Series with only one element returns a scalar instead of a length-1 Series. By explicitly converting to a list (or wrapping scalars), we make sure the input to get_item_profiles is always iterable—fixing the root cause of the error.
内容的提问来源于stack exchange,提问作者Jay

