【问题标题】:Iterating through first groupby level to get second level dataframe遍历第一个 groupby 级别以获得第二级数据帧
【发布时间】:2019-05-25 22:19:41
【问题描述】:

我已将数据框按两列(用户和月份)分组,然后使用 mean() 来获取每个月的“分数”值的平均值。我现在想做的是按用户遍历组,并能够获得每个月的月份和平均分数,以便我可以使用 matplotlib 绘制它们。问题是,当我遍历组时,我会为每个用户重复一个月,而不是仅仅遍历第一个(用户)组。请告诉我这是怎么可能的,谢谢。

这是我目前所拥有的:

user_group = past_year.groupby(['User','month'])['Score'].mean()
for group in user_group:
    #I want to be able to access all months and mean scores for the current user here

【问题讨论】:

    标签: python pandas pandas-groupby


    【解决方案1】:

    如果我理解您正在尝试正确执行的操作,则使用这样的多层次索引可能会起作用 - 但它很笨重:

    import pandas as pd 
    df = pd.DataFrame({"User" : ["User1", "User1", "User1", "User1", "User1", "User1"], "Month" : ["Jan", "Jan", "Jan", "Feb", "Feb", "Feb"], "Score" : [5,10,30,30,30,40]})
    
    users = df.User.unique()
    months = df.Month.unique()
    
    df =df.set_index(["User", "Month"])
    
    for i in users:
        for x in months:
            print(df.loc[i].loc[x].Score.mean())
    

    然后根据您想要对最终结果执行的操作更改打印语句。

    【讨论】:

      猜你喜欢
      • 2020-09-14
      • 1970-01-01
      • 2020-06-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-06-13
      • 2015-12-12
      • 1970-01-01
      相关资源
      最近更新 更多