Pandas - GroupBy 2 列 - 无法重置索引

She*_*ahn 4 python python-3.x pandas pandas-groupby

我有一个 DF 如下:

Date Bought | Fruit
2018-01       Apple
2018-02       Orange
2018-02       Orange
2018-02       Lemon
Run Code Online (Sandbox Code Playgroud)

我希望按“购买日期”和“水果”对数据进行分组并计算出现次数。

预期结果:

Date Bought | Fruit | Count
2018-01       Apple     1
2018-02       Orange    2
2018-02       Lemon     1
Run Code Online (Sandbox Code Playgroud)

我得到的:

Date Bought | Fruit | Count
2018-01       Apple     1
2018-02       Orange    2
              Lemon     1
Run Code Online (Sandbox Code Playgroud)

使用的代码:

Initial attempt:
df.groupby(['Date Bought','Fruit'])['Fruit'].agg('count')

#2
df.groupby(['Date Bought','Fruit'])['Fruit'].agg('count').reset_index()
ERROR: Cannot insert Fruit, already exists

#3
df.groupby(['Date Bought','Fruit'])['Fruit'].agg('count').reset_index(inplace=True)
ERROR: Type Error: Cannot reset_index inplace on a Series to create a DataFrame

Run Code Online (Sandbox Code Playgroud)

文档显示 groupby 函数返回一个“groupby 对象”而不是标准 DF。如何将上述数据分组并保留 DF 格式?

jez*_*ael 7

这里的问题是,通过重置索引,您最终会得到 2 列同名。因为有工作Series,可以设置参数name在Series.reset_index:

df1 = (df.groupby(['Date Bought','Fruit'], sort=False)['Fruit']
         .agg('count')
         .reset_index(name='Count'))
print (df1)
  Date Bought   Fruit  Count
0     2018-01   Apple      1
1     2018-02  Orange      2
2     2018-02   Lemon      1
Run Code Online (Sandbox Code Playgroud)