【问题标题】:Pandas: calculate the std of total column value per "year"熊猫:计算每“年”总列值的标准差
【发布时间】:2020-09-28 17:26:12
【问题描述】:

我有一个数据框,代表餐馆的顾客签到(访问)。 year 只是发生在餐厅登记的年份。

  • 我想做的是在我的初始数据框df 中添加一列std_checkin,它表示每年访问的标准差。所以,我需要计算每年总访问量的标准差。
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'])

# total number of checkins per restaurant
d = df.groupby('restaurant_id')['year'].count().to_dict()
df['nb_checkin'] = df['restaurant_id'].map(d)


grouped = df.groupby(["restaurant_id"])
avg_annual_visits = grouped["year"].count() / grouped["year"].nunique()
avg_annual_visits = avg_annual_visits.rename("avg_annual_visits")
df = df.merge(avg_annual_visits, left_on="restaurant_id", right_index=True)

df.head(10)

从这里开始,我不确定如何用 pandas 编写我想要的内容。如果需要任何澄清,请询问。

谢谢!

【问题讨论】:

    标签: python pandas dataframe standard-deviation feature-engineering


    【解决方案1】:

    我想你想做:

    counts = df.groupby('restaurant_id')['year'].value_counts()
    counts.std(level='restaurant_id')
    

    counts 的输出,即每年每家餐厅的总访问量:

    restaurant_id           year
    --1UhMGODdWsrMastO9DZw  2016    4
                            2017    2
    --6MefnULPED_I942VcFNA  2011    2
                            2012    2
    Name: year, dtype: int64
    

    std 的输出

    restaurant_id
    --1UhMGODdWsrMastO9DZw    1.414214
    --6MefnULPED_I942VcFNA    0.000000
    Name: year, dtype: float64
    

    【讨论】:

    • 嗯,好的,但我怎样才能将它添加到初始 Dataframe df 中?
    • df['annual_std'] = df['restaurant_id'].map(counts.std(level='restaurant_id')).
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-06
    • 2021-06-03
    • 1970-01-01
    • 1970-01-01
    • 2017-08-13
    相关资源
    最近更新 更多