【问题标题】:Pandas - GroupBy 2 Columns - Unable to reset index熊猫 - GroupBy 2 列 - 无法重置索引
【发布时间】:2020-06-30 13:38:48
【问题描述】:

我的 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

Documentation 表明 groupby 函数返回一个“groupby 对象”而不是标准 DF。怎么把上面提到的数据分组,保留DF格式?

【问题讨论】:

    标签: python python-3.x pandas pandas-groupby


    【解决方案1】:

    这里的问题是,通过重置索引,您最终会得到 2 个具有相同名称的列。因为使用Series 可以在Series.reset_index 中设置参数name

    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
    

    【讨论】:

    • 虽然这基本上是transform,正如另一个答案指出的那样
    • @yatu - 你确定吗?我认为不会。
    • 虽然你丢失了索引。你必须重新分配。
    • @jezrael 谢谢,答案是错误的。我已经删除了帖子。
    猜你喜欢
    • 2021-02-12
    • 1970-01-01
    • 2020-09-01
    • 2022-06-14
    • 1970-01-01
    • 1970-01-01
    • 2020-10-12
    • 2018-07-16
    • 2022-11-08
    相关资源
    最近更新 更多