【问题标题】:Pandas groupby unique issue熊猫 groupby 独特的问题
【发布时间】:2018-07-19 17:26:49
【问题描述】:

我有一个数据框“region_group”。如下所示,此数据框在“Town/City”列中没有“ARTHOG”值。但是,当我首先在此列上执行 groupby-first 时,此值会重新出现。我试图了解为什么会发生这种情况。

注意:region_group 数据框基于另一个数据框,该数据框在“Town/City”列中具有“ARTHOG”作为值。但是它已经被过滤掉了,如下所示,在 Out[25] 中也很明显

region=k[['my_ID','Town/City','District','County','month','year']]
region=region.loc[(region['month'] == 12) & (region['year'] == 2016)]
region_noid=region.drop(['my_ID','month','year'], axis=1)

region_group=region_noid.groupby(['Town/City','District','County']).size().reset_index(name='Count')

【问题讨论】:

  • dtype 是您的“城镇/城市”列吗?只是排除了分类。
  • 不,它是分类数据类型。
  • region_group.dtypes Out[29]: Town/City category District category County category Count int64 dtype: object

标签: python pandas


【解决方案1】:

Pandas 使用groupby 操作中所有分类列的乘积来确定输出的索引。这意味着即使一个类别没有在基础数据中表示,它也会在groupby 结果中表示。

可以在我质疑此行为目的的问题中找到有关此问题的详细信息以及可能的解决方案: Pandas groupby with categories

pandas 开发团队有taken the stance,所有类别组合必须在groupby 分类系列操作中表示。

【讨论】:

    【解决方案2】:

    Category数据会继承category,当没有值时,仍然保留category,但将值填充为NaN

    df=pd.DataFrame({'A':[1,1,3,4,5],'B':[1,2,2,2,2]})
    df.A=df.A.astype('category',categories=[1,2,3,4,5])
    
    df.groupby('A').B.first()
    Out[905]: 
    A
    1    1.0
    2    NaN
    3    2.0
    4    2.0
    5    2.0
    Name: B, dtype: float64
    

    解决办法,把它转回str或者numeric

    df.A=df.A.astype(int)
    df.groupby('A').B.first()
    Out[907]: 
    A
    1    1
    3    2
    4    2
    5    2
    Name: B, dtype: int64
    

    或者我们使用remove_unused_categories

    df.A=df.A.cat.remove_unused_categories()
    df.groupby('A').B.first()
    Out[910]: 
    A
    1    1
    3    2
    4    2
    5    2
    Name: B, dtype: int64
    

    【讨论】:

    • wen 和 jp_data_analysis。感谢你们俩。很高兴知道这一点。你们俩都是对的,我只能接受一个答案。我接受了 jp_data_analysis 的答案,因为他先回答了。再次感谢。
    • @MadhukarJha 好吧,我给你提供更多选择
    【解决方案3】:

    从 Pandas 0.23.0 开始,groupby 方法现在可以采用参数“observed”,如果将其设置为 True(默认为 False),则可以解决此问题。

    【讨论】:

      猜你喜欢
      • 2021-03-21
      • 1970-01-01
      • 2019-02-24
      • 1970-01-01
      • 1970-01-01
      • 2020-03-25
      • 1970-01-01
      • 1970-01-01
      • 2012-09-01
      相关资源
      最近更新 更多