如何解决python中透视表的错误

2024-04-27 21:39:17 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个类似的文件,如下所示:

    movieId     title   genres  userId  rating  timestamp

0   1   Toy Story (1995)    Adventure|Animation|Children|Comedy|Fantasy     1   4.0     964982703
1   1   Toy Story (1995)    Adventure|Animation|Children|Comedy|Fantasy     5   4.0     847434962
2   1   Toy Story (1995)    Adventure|Animation|Children|Comedy|Fantasy     7   4.5     1106635946
3   1   Toy Story (1995)    Adventure|Animation|Children|Comedy|Fantasy     15  2.5     1510577970
4   1   Toy Story (1995)    Adventure|Animation|Children|Comedy|Fantasy     17  4.5     1305696483
5   6   Heat (1995)     Action|Crime|Thriller   373     5.0     846830247
6   6   Heat (1995)     Action|Crime|Thriller   380     5.0     1494278663
7   6   Heat (1995)     Action|Crime|Thriller   385     3.0     840648313
8   6   Heat (1995)     Action|Crime|Thriller   386     3.0     842613783
9   6   Heat (1995)     Action|Crime|Thriller   389     5.0     857934242

我运行此代码以获取完整数据并对其进行处理:

! wget https://www.dropbox.com/s/z4zoofdgdrxe01r/movies.csv
! wget https://www.dropbox.com/s/f328xczt6vju6hi/ratings.csv
import pandas as pd
df_movies = pd.read_csv('movies.csv')
df_ratings = pd.read_csv('ratings.csv')
df_merged=pd.merge(df_movies, df_ratings, how='inner')

这是我有问题的代码:

df_merged.pivot(index='movieId', columns='title', values='rating')

我得到:

---------------------------------------------------------------------------

ValueError                                Traceback (most recent call last)

<ipython-input-74-ad6b3a589ea8> in <module>()
----> 1 df_merged.pivot(index='movieId', columns='title', values='rating')

5 frames

/usr/local/lib/python3.6/dist-packages/pandas/core/reshape/reshape.py in _make_selectors(self)
    177 
    178         if mask.sum() < len(self.index):
--> 179             raise ValueError("Index contains duplicate entries, cannot reshape")
    180 
    181         self.group_index = comp_index

ValueError: Index contains duplicate entries, cannot reshape

我想知道的是,通过在excel中制作一个类似于Dynamic Table的简历表,哪部电影的投票率更高


Tags: csvdfindexactionmoviesfantasychildrentoy
1条回答
网友
1楼 · 发布于 2024-04-27 21:39:17

获取组计数的最直接的方法是使用pandas 1.1中引入的DataFrame.value_counts()方法。对于pandas的早期版本,可以通过使用Series.value_counts()方法获得类似的结果。其他替代方案包括DataFrame.gropuby()DataFrame.pivot_table()。如果您希望使用多个条件聚合数据,而不仅仅是计算项目数,那么这些条件可能是首选条件

设置

import pandas as pd

df_merged = pd.DataFrame({'movie id': [1, 1, 1, 1, 1, 6, 6, 6, 6, 6], 
                  'title': ['Toy Story (1995)', 'Toy Story (1995)', 'Toy Story (1995)','Toy Story (1995)', 'Toy Story (1995)', 'Heat (1995)', 'Heat (1995)', 'Heat (1995)', 'Heat (1995)', 'Heat (1995)'], 
                  'rating': [4.0, 4.0, 4.5, 2.5, 4.5, 5.0, 5.0, 3.0, 3.0, 5.0]})

值\u计数()

要获得投票数,请使用.value_counts()计算项目数:

df_merged.value_counts('title')

这将返回一个新的系列,其中电影的标题作为索引,每部电影的收视率作为值

Heat (1995)         5
Toy Story (1995)    5
Name: title, dtype: int64

对于pandas 1.1之前的版本,您可以对一个系列使用.value_counts()来获得类似的结果:

df_merged['title'].value_counts()

groupby

另一种方法是将.gropuby().size()一起使用:

df_merged.groupby('title').size()

透视表()

这也可以使用.pivot_table()方法完成:

df_merged.pivot_table(values='rating', index=['title'], aggfunc='count')

将生成一个数据帧作为输出:

               rating
title   
Heat (1995)         5
Toy Story (1995)    5

如果您想使用多个标准(例如,评分数量和平均(平均)评分)进行汇总,那么pivot_table方法可能非常有用:

df_merged.pivot_table(values='rating', index=['title'], aggfunc=('count','mean'))

                  count  mean
title                        
Heat (1995)           5   4.2
Toy Story (1995)      5   3.9

相关问题 更多 >