【发布时间】:2020-09-24 19:43:08
【问题描述】:
我有一个数据框,其中包含顾客对他们去过的餐馆的评分以及其他一些属性。
- 我要做的是计算去年的平均星级和平均星级之间的差异 餐厅的第一年。
data = {'rating_id': ['1', '2','3','4','5','6','7'],
'user_id': ['56', '13','56','99','99','13','12'],
'restaurant_id': ['xxx', 'xxx','yyy','yyy','xxx','zzz','zzz'],
'star_rating': ['2.3', '3.7','1.2','5.0','1.0','3.2','1.0'],
'rating_year': ['2012','2012','2020','2001','2020','2015','2000'],
'first_year': ['2012', '2012','2001','2001','2012','2000','2000'],
'last_year': ['2020', '2020','2020','2020','2020','2015','2015'],
}
df = pd.DataFrame (data, columns = ['rating_id','user_id','restaurant_id','star_rating','rating_year','first_year','last_year'])
df.head()
df['star_rating'] = df['star_rating'].astype(float)
# calculate the average of the stars of the first year
ratings_mean_firstYear= df.groupby(['restaurant_id','first_year']).agg({'star_rating':[np.mean]})
ratings_mean_firstYear.columns = ['avg_firstYear']
ratings_mean_firstYear.reset_index()
# calculate the average of the stars of the last year
ratings_mean_lastYear= df.groupby(['restaurant_id','last_year']).agg({'star_rating':[np.mean]})
ratings_mean_lastYear.columns = ['avg_lastYear']
ratings_mean_lastYear.reset_index()
# merge the means into a single table
ratings_average = ratings_mean_firstYear.merge(
ratings_mean_lastYear.groupby('restaurant_id')['avg_lastYear'].max()
, on='restaurant_id'
)
ratings_average.head(20)
我的问题是第一年和最后几年的平均值完全相同,这毫无意义,我真的不知道我在这里的思考过程中做错了什么..我怀疑@有什么问题987654325@因为这是我第一次使用pandas lib。
有什么建议吗?
【问题讨论】:
-
这能回答你的问题吗? Aggregation in pandas
-
不是真的。
-
存在逻辑错误:您将聚合应用于同一列星。您需要为第一年和最后一年设置星号,但将聚合应用于相同的星号。所以结果刚刚好。使用
stars first和stars last创建列,它会起作用。 -
@OliverPrislan 哦,我会试试的!
-
您的数据是以这样一种方式提供的,即每个用户/餐厅对具有单一评级,并且您在第一年和去年的聚合中都使用它 - 因此这两个年份自然是相等的。我首先使用
rating_year == first_year标准过滤数据,然后应用groupby 和agg。然后对去年重复相同的操作,然后合并 2 个结果。在您的示例中,没有一条评论的数据与任何餐厅的第一年或去年相匹配。因此,要显示适当的示例将需要更多数据。我假设您在较大的数据框中拥有它。
标签: python pandas jupyter-notebook feature-engineering