Pandas:计算每个 "year" 的 Dataframe 列值的平均值

Pandas: calculate mean of Dataframe column values per "year"

我有一个数据框代表餐厅的顾客签到(访问)。 year 就是餐厅签到发生的那一年。

data = {
        'restaurant_id':  ['--1UhMGODdWsrMastO9DZw', '--1UhMGODdWsrMastO9DZw','--1UhMGODdWsrMastO9DZw','--1UhMGODdWsrMastO9DZw','--1UhMGODdWsrMastO9DZw','--1UhMGODdWsrMastO9DZw','--6MefnULPED_I942VcFNA','--6MefnULPED_I942VcFNA','--6MefnULPED_I942VcFNA','--6MefnULPED_I942VcFNA'],
        'year': ['2016','2016','2016','2016','2017','2017','2011','2011','2012','2012'],
        }
df = pd.DataFrame (data, columns = ['restaurant_id','year'])


# here i count the total number of checkins a restaurant had
d = df.groupby('restaurant_id')['year'].count().to_dict()
df['nb_checkin'] = df['restaurant_id'].map(d)


mean_checkin= df.groupby(['restaurant_id','year']).agg({'nb_checkin':[np.mean]})
mean_checkin.columns = ['mean_checkin']
mean_checkin.reset_index()

# the values in mean_checkin makes no sens

#I need to merge it with df to add that new column

我对 pandas 库还是陌生的,我尝试过类似的方法,但我的结果毫无意义。我的语法有问题吗?如果需要任何说明,请询问。

每年的平均访问次数可以计算为餐厅的总访问次数除以您拥有数据的唯一年份数。

grouped = df.groupby(["restaurant_id"])
avg_annual_visits = grouped["year"].count() / grouped["year"].nunique()
avg_annual_visits = avg_annual_visits.rename("avg_annual_visits")

print(avg_annual_visits)
restaurant_id
--1UhMGODdWsrMastO9DZw    3.0
--6MefnULPED_I942VcFNA    2.0
Name: avg_annual_visits, dtype: float64

然后,如果您想将其合并回原始数据:

df = df.merge(avg_annual_visits, left_on="restaurant_id", right_index=True)

print(df)
            restaurant_id  year  avg_annual_visits
0  --1UhMGODdWsrMastO9DZw  2016                3.0
1  --1UhMGODdWsrMastO9DZw  2016                3.0
2  --1UhMGODdWsrMastO9DZw  2016                3.0
3  --1UhMGODdWsrMastO9DZw  2016                3.0
4  --1UhMGODdWsrMastO9DZw  2017                3.0
5  --1UhMGODdWsrMastO9DZw  2017                3.0
6  --6MefnULPED_I942VcFNA  2011                2.0
7  --6MefnULPED_I942VcFNA  2011                2.0
8  --6MefnULPED_I942VcFNA  2012                2.0
9  --6MefnULPED_I942VcFNA  2012                2.0