2

I am trying out the set_index() method in Pandas but I get an exception I can not explain:

df

    movieId title        genres
1   2   Jumanji (1995)  Adventure|Children|Fantasy
5   6   Heat (1995) Action|Crime|Thriller
10  11  American President, The (1995)  Comedy|Drama|Romance

df.set_index(['a' , 'b' , 'c'], inplace = True)
df

KeyError: 'a'

1 Answer 1

1

If want set index by nested list (double []) with same length as df:

df.set_index([['a' , 'b' , 'c']], inplace = True)
print (df)
   movieId                          title                      genres
a        2                 Jumanji (1995)  Adventure|Children|Fantasy
b        6                    Heat (1995)       Action|Crime|Thriller
c       11  American President The (1995)        Comedy|Drama|Romance

If use list ([]) pandas try set columns a,b,c to MultiIndex and because does not exist error is raised.

So if want set index by columns:

df.set_index(['movieId' , 'title'], inplace = True)
print (df)
                                                           genres
movieId title                                                    
2       Jumanji (1995)                 Adventure|Children|Fantasy
6       Heat (1995)                         Action|Crime|Thriller
11      American President The (1995)        Comedy|Drama|Romance
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.