【问题标题】:Pandas groupby index is incorrectPandas groupby 索引不正确
【发布时间】:2020-01-27 13:08:29
【问题描述】:

我可能误解了pd.GroupBy 函数的作用,但我认为这应该断言True. 为什么要断言False

a = pd.DataFrame([range(3)]*3,index=map(str, range(3))).T
a.iloc[:,0] = [10, 11, 11]

a.groupby('0').apply(lambda x: print(x.index))

indexes = a.groupby('0').apply(lambda x: x.index)
print(indexes)

index_lengths = a.groupby('0').apply(lambda x: len(x.index))
print(index_lengths)

indexes_lengths = a.groupby('0').apply(lambda x: x.index).apply(len)
print(indexes_lengths)

assert indexes_lengths.equals(index_lengths), "Apply indexes are returning the wrong index"

【问题讨论】:

    标签: python pandas group-by apply


    【解决方案1】:

    我猜这是apply 中的一个错误。如果您仍希望输出为index 对象列表,只需通过添加.copy 为每个组创建新的索引对象

    a.groupby('0').apply(lambda x: x.index.copy())
    
    Out[706]:
    0
    10       Int64Index([0], dtype='int64')
    11    Int64Index([1, 2], dtype='int64')
    dtype: object
    

    index 中的len 似乎没有遇到这个错误

    a.groupby('0').apply(lambda x: len(x.index))
    
    Out[707]:
    0
    10    1
    11    2
    dtype: int64
    

    只有直接申请index时才会出现这个bug。所以,添加.copy 会如你所愿地返回

    a.groupby('0').apply(lambda x: x.index.copy()).apply(len)
    
    Out[708]:
    0
    10    1
    11    2
    dtype: int64
    

    【讨论】:

      【解决方案2】:

      可能是错误,但如果将索引转换为 list 一切正常:

      indexes = a.groupby('0').apply(lambda x: list(x.index))
      print(indexes)
      0
      10       [0]
      11    [1, 2]
      dtype: object
      
      indexes_lengths = a.groupby('0').apply(lambda x: list(x.index)).apply(len)
      print(indexes_lengths)
      0
      10    1
      11    2
      dtype: int64
      
      index_lengths = a.groupby('0').apply(lambda x: len(x.index))
      print(index_lengths)
      0
      10    1
      11    2
      dtype: int64
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2018-09-22
        • 1970-01-01
        • 2018-08-29
        • 2018-04-17
        • 2014-02-02
        • 2022-07-19
        • 2018-08-31
        相关资源
        最近更新 更多