Search code examples
pythonpandaspivot-tablekeyerror

Pandas Pivot_table KeyError


My data looks like below;

  'userID'  'songID'  'rating'
0         0      7171         5
1         0      8637         4
2         0     21966         4
3         0     35821         5
4         0     82446         5

My code is below in order to create a pivot_table;

ratings = pd.pivot_table(data,
                         index="userID",
                         columns="songID",
                         values="rating")

I get a KeyError:'rating'

I checked other answers, most of them suggest .reset_index(), but it didn't work. I keep getting same error.

Any suggestion to solve this problem?

Thanks in advance.


Solution

  • There is problem in columns names:

    print (data.columns.tolist())
    ["'userID'", "'songID'", "'rating'"]
    

    You can strip traling ' by:

    ratings.columns = ratings.columns.str.strip("'")
    ratings = pd.pivot_table(data, index = "userID", columns = "songID", values = 'rating')