代码之家  ›  专栏  ›  技术社区  ›  Amir

熊猫数据框架中的多索引系列

  •  5
  • Amir  · 技术社区  · 7 年前

    我有一个熊猫系列,有两个指数:

    df_agg=df.groupby(['yearID','teamID']).sum()['Salary']
    df_agg.head()
    
    yearID  teamID
    1985    ATL       14807000
            BAL       11560712
            BOS       10897560
            CAL       14427894
            CHA        9846178
    

    我想将int转换为pandas数据帧,如

    yearID     teamID    Salary
    1985        ATL       14807000
    1985        BAL       11560712
    1985        BOS       10897560
    1985        CAL       14427894
    1985        CHA        9846178
    

    我厌倦了使用:

    df_new=df_agg.reset_index(inplace=True)
    

    但我有以下错误:


    TypeError回溯(最后一次调用) 在() ----&燃气轮机;1 df\u new=df\u agg。reset\U索引(就地=真)

    C: \用户\ameimand\AppData\Local\Continuum\Anaconda3\lib\site packages\pandas\core\series。重置索引中的py(self、level、drop、name、inplace) 966

        index=new_index).__finalize__(self)
        967         elif inplace:
    --> 968             raise TypeError('Cannot reset_index inplace on a Series '
        969                             'to create a DataFrame')
        970         else:
    
    TypeError: Cannot reset_index inplace on a Series to create a DataFrame
    
    1 回复  |  直到 7 年前
        1
  •  7
  •   jezrael    7 年前

    我认为有两个很好的解决方案参数 as_index=False :

    df_new = df.groupby(['yearID','teamID'], as_index=False)['Salary'].sum()
    

    reset_index 没有 inplace=True :

    df_new = df.groupby(['yearID','teamID'])['Salary'].sum().reset_index()
    

    注意 :

    最好是在 groupby 在里面 [] 喜欢 ['Salary'] :

    df.groupby(['yearID','teamID'], as_index=False)['Salary']
    

    作为:

    df.groupby(['yearID','teamID']).sum()['Salary']
    

    因为这会聚合所有列,然后仅选择 Salary .