【发布时间】:2021-05-10 11:27:26
【问题描述】:
我有一个包含以下列的数据框
Movie Rating Genre_0 Genre_1 Genre_2
MovieA 8.9 Action Comedy Family
MovieB 9.1 Horror NaN NaN
MovieC 4.4 Comedy Family Adventure
MovieD 7.7 Action Adventure NaN
MovieE 9.5 Adventure Comedy NaN
MovieF 7.5 Horror NaN NaN
MovieG 8.6 Horror NaN NaN
我想要一个数据框,其中包含每种类型的值计数以及每次出现该类型时的平均评分
Genre value_count Average_Rating
Action 2 8.3
Comedy 3 7.6
Horror 3 8.4
Family 2 6.7
Adventure 3 7.2
我已经尝试了以下代码并且能够获取值计数。但是,我无法根据每种类型出现的次数获得每种类型的平均评分。非常感谢任何形式的帮助,谢谢。
#create a list for the genre columns
genre_col = [col for col in df if col.startswith('Genre_')]
#get value counts of genres
genre_counts = df[genre_col].apply(pd.Series.value_counts).sum(1).to_frame(name='Count')
genre_counts.index.name = 'Genre'
genre_counts = genre_counts.reset_index()
【问题讨论】:
标签: python pandas dataframe pandas-groupby series