Python 熊猫-GroupBy 2列-无法重置索引

Python 熊猫-GroupBy 2列-无法重置索引,python,python-3.x,pandas,pandas-groupby,Python,Python 3.x,Pandas,Pandas Groupby,我的DF如下所示: Date Bought | Fruit 2018-01 Apple 2018-02 Orange 2018-02 Orange 2018-02 Lemon 我希望按“购买日期”和“水果”对数据进行分组,并统计发生的次数 预期结果: Date Bought | Fruit | Count 2018-01 Apple 1 2018-02 Orange 2 2018-02 Lemon

我的DF如下所示:

Date Bought | Fruit
2018-01       Apple
2018-02       Orange
2018-02       Orange
2018-02       Lemon
我希望按“购买日期”和“水果”对数据进行分组,并统计发生的次数

预期结果:

Date Bought | Fruit | Count
2018-01       Apple     1
2018-02       Orange    2
2018-02       Lemon     1
Date Bought | Fruit | Count
2018-01       Apple     1
2018-02       Orange    2
              Lemon     1
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

我得到的:

Date Bought | Fruit | Count
2018-01       Apple     1
2018-02       Orange    2
2018-02       Lemon     1
Date Bought | Fruit | Count
2018-01       Apple     1
2018-02       Orange    2
              Lemon     1
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

使用的代码:

Date Bought | Fruit | Count
2018-01       Apple     1
2018-02       Orange    2
2018-02       Lemon     1
Date Bought | Fruit | Count
2018-01       Apple     1
2018-02       Orange    2
              Lemon     1
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


显示groupby函数返回的“groupby对象”不是标准DF。如何按上述方式对数据进行分组并保留DF格式?

这里的问题是,通过重置索引,您将得到两个同名列。因为可以使用
系列
在以下位置设置参数
名称


虽然这基本上是一个
转换
,但其他答案如下out@yatu-你确定吗?我想不会。不过你失去了索引。“你必须重新分配任务。”耶斯雷尔:谢谢,答案是错的。我已经删除了这篇文章。