简体   繁体   English

Pandas Pivot_table KeyError

[英]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;为了创建一个pivot_table,我的代码在下面;

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

I get a KeyError:'rating'我收到一个KeyError:'rating'

I checked other answers, most of them suggest .reset_index(), but it didn't work.我检查了其他答案,其中大多数建议使用.reset_index(),但没有用。 I keep getting same error.我不断收到同样的错误。

Any suggestion to solve this problem?有什么建议可以解决这个问题吗?

Thanks in advance.提前致谢。

There is problem in columns names:列名有问题:

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

You can strip traling ' by:您可以通过以下方式strip traling '

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

You columns has extra quotation mark 'xx' around.您的列周围有额外的quotation mark 'xx' so if you want to keep it then use following所以如果你想保留它然后使用以下

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM