简体   繁体   English

pandas reset_index() 在应用 groupby 后不起作用

[英]pandas reset_index() not working after applying groupby

I have a pandas dataframe like this我有一个像这样的 pandas dataframe

在此处输入图像描述

df = pd.DataFrame({'id':[1,2,3,4,5], 'Opposition':['Sri Lanka', 'Sri Lanka', 'UAE','UAE','Sri Lanka'],
                   'Inning_no':[1,2,1,2,1], 'Wickets':[13,17,14,18,29]})

I have the groupby to get the following output我有 groupby 得到以下 output

t = inn.groupby(['Opposition', 'Inning_no'])['Wickets'].agg([('Wickets', 'sum'), ('Played', 'count')])

I have the output like this我有这样的 output

                                    Wickets   Played
            Opposition  Inning_no       
            v Sri Lanka    1           42       4
                           2           17       2
            v UAE          1           14       4
                           2           18       6

The problem is that reset_index() is not working with the group by .问题是 reset_index() 无法与 group by 一起使用 The multi column index is set on Opposition and Innings_no column.多列索引设置在 Opposition 和 Innings_no 列上。 I want the index to be reset and show all in one level like below.我希望重置索引并在一个级别中显示所有内容,如下所示。

在此处输入图像描述

I am having this error我有这个错误

ValueError: cannot insert Opposition, already exists

You can just add reset_index at the end您可以在最后添加reset_index

t = inn.groupby(['Opposition', 'Inning_no'])['Wickets'].agg([('Wickets', 'sum'), ('Played', 'count')]).reset_index()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM