Velvet Star Monitor

Standout celebrity highlights with iconic style.

news

TypeError: Cannot index by location index with a non-integer key

Writer Andrew Henderson

I am trying to re-write this code, which was written a while ago.

It has multiple chuncks, hence, I separated it into smaller pieces and re-write step by step. For instance, converting .ix to iloc, etc.

This chunk gives me an error:

#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)

Get an error

TypeError: Cannot index by location index with a non-integer key

I guess there is something here, which requires updating, but cannot find what exactly. I do not think it is about data. It is just about updating the code.

Appreciate any tips!

2

2 Answers

Both answers were correct - by @nosuchthingasmagic and @Quang Hoang. Managed to debug everything.

I messed up with .iloc and .loc

The problem is here:

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]

I'm not exactly sure what that piece of code is supposed to do (though it seems like there may be a more efficient way of doing it). Also, it looks like you are referencing j outside the j loop.

However, the specific error you're getting is mostly likely related to:

product_top_names = data_neighbours.iloc[product][1:10]

iloc only works with integers, and I guess product is a string. If that's the case, something like

product_top_names = data_neighbours[product].iloc[1:10] 

should get rid of the error (assuming product is the name of a column).

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.