类型错误:无法使用非整数键按位置索引进行索引

Ole*_*siy 5 python numpy pandas

我正在尝试重写这段不久前编写的代码

它有多个块,因此,我将其分成更小的块并逐步重写。例如,转换.ixiloc等。

这个块给了我一个错误:

#Loop through all rows, skip the user column, and fill with similarity scores
for i in range(0,len(data_sims.index)):
    for j in range(1,len(data_sims.columns)):
        user = data_sims.index[i]
        product = data_sims.columns[j]

    if data.iloc[i][j] == 1:
        data_sims.iloc[i][j] = 0
    else:
        product_top_names = data_neighbours.iloc[product][1:10]
        product_top_sims = data_ibs.iloc[product].order(ascending=False)[1:10]
        user_purchases = data_germany.iloc[user,product_top_names]

        data_sims.iloc[i][j] = getScore(user_purchases,product_top_sims)
Run Code Online (Sandbox Code Playgroud)

出现错误

TypeError: Cannot index by location index with a non-integer key
Run Code Online (Sandbox Code Playgroud)

我想这里有一些东西需要更新,但找不到具体是什么。我不认为这与数据有关。这只是更新代码。

感谢任何提示!

Ole*_*siy 5

这两个答案都是正确的 - 由 @nosuchthingasmagic 和 @Quang Hoang 提供。设法调试一切。

我搞砸了.iloc.loc

问题就在这里:

product_top_names = data_neighbours.loc[product][1:10]
product_top_sims = data_ibs.loc[product].sort_values(ascending=False)[1:10]
user_purchases = data_germany.loc[user,product_top_names]
Run Code Online (Sandbox Code Playgroud)


小智 3

我不太确定那段代码应该做什么(尽管似乎可能有更有效的方法来做到这一点)。另外,看起来您正在引用循环j之外j

但是,您遇到的具体错误很可能与以下内容有关:

product_top_names = data_neighbours.iloc[product][1:10]
Run Code Online (Sandbox Code Playgroud)

iloc只适用于整数,我猜product是一个字符串。如果是这样的话,就像

product_top_names = data_neighbours[product].iloc[1:10] 
Run Code Online (Sandbox Code Playgroud)

应该消除错误(假设product是列的名称)。