【问题标题】:In Python, TypeError: unsupported operand type(s) for -: 'str' and 'int'在 Python 中,TypeError: unsupported operand type(s) for -: 'str' and 'int'
【发布时间】:2017-05-30 08:36:15
【问题描述】:

我正在通过使用 Movielens 数据集的协同过滤来制作电影推荐系统。 我关注thishttp://blog.ethanrosenthal.com/2015/11/02/intro-to-collaborative-filtering/

但它在 ln[8] 上不起作用:

import numpy as np
import pandas as pd

data = open('ratings.csv')

names = ['user_id','item_id','rating','timestamp']
df = pd.read_csv('ratings.csv', sep=',', names=names)
df.head()

n_users = df.user_id.unique().shape[0]
n_items = df.item_id.unique().shape[0]
print (str(n_users) + ' users')
print (str(n_items) + ' items')

ratings = np.zeros((n_users, n_items))
for row in df.itertuples():
    ratings[row[1]-1, row[2]-1] = row[3]
ratings

sparsity = float(len(ratings.nonzero()[0]))
sparsity /= (ratings.shape[0] * ratings.shape[1])
sparsity *= 100
print ('Sparsity: {:4.2f}%'.format(sparsity))

并且有这样的错误:

  line 17, in <module>
    ratings[row[1]-1, row[2]-1] = row[3]
TypeError: unsupported operand type(s) for -: 'str' and 'int'

【问题讨论】:

  • Exception 很清楚 - 你 rows 持有 strs。

标签: python recommendation-engine collaborative-filtering


【解决方案1】:

您从 CSV 读取数据帧,默认情况下将该数据读取为 字符串。然后,您尝试使用数据框中的行,期望这些值是数字(从中减去 1),但失败了。

要么指定dtype(应用于所有列或使用每列的映射),要么使用converters 映射中的传递(将列索引或列名映射到转换函数)。鉴于数据都是整数(id 编号、评级和时间戳,以从一个纪元开始的秒数为单位),一个快速的解决方法是在此处使用 dtype=np.int32

df = pd.read_csv('ratings.csv', sep=',', names=names, dtype=np.int32)

【讨论】:

    猜你喜欢
    • 2020-04-04
    • 2021-03-27
    • 2020-04-14
    • 1970-01-01
    • 2016-04-29
    • 2023-04-02
    • 2016-08-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多