代码之家  ›  专栏  ›  技术社区  ›  Cookie

熊猫重新排列groupby对象(多对多)

  •  0
  • Cookie  · 技术社区  · 4 年前

    我有一个类似这样的多对多数据帧,其中和id可能包含多个区域,一个区域也可能包含多个id:

    t = pd.DataFrame({
        'id': ['a', 'a', 'b', 'c', 'c', 'c'],
        'land': ['A', 'B', 'A', 'A', 'B', 'C'],
        'area': [123, 234, 123, 23, 342, 12],
        'info': ['Im', 'never', 'gonna', 'give', 'you', 'up']
    })
    

    最终,我将把它加入到GIS中,我需要重新排列数据,以一对一的格式按土地分组。

    我的预期输出可能是这样的: (我也很难让它打印出groupby对象。我想要 完整数据 而不是使用count()或size(),但它只返回pandas。groupbyObject。)

    地区 信息
    土地 身份证件
    A. A. 123 伊姆河
    B 123 将要
    C 23 给
    B A. 234 从不
    C 342 你
    C C 12 向上的

    ...并将数据合并为一对一: (只是一个示例输出格式。可以是您自己的可读方式,只要能够正确显示所有ID和信息)

    土地 身份证件 地区 信息
    A. 1.a;2.b;3.c a:123;b:123;c:23 a:‘Im’;b:“要去”;c:“给”
    B 1.a;2.c a:234;c:342 答:“永远不会”;c:“你很好。”
    C C 12 “向上”

    非常感谢。

    1 回复  |  直到 4 年前
        1
  •  2
  •   enke    4 年前

    选项1非常简单。只是 set_index + sort_index :

    option1 = t.set_index(['land','id']).sort_index()
    

    输出:

             area   info
    land id             
    A    a    123     Im
         b    123  gonna
         c     23   give
    B    a    234  never
         c    342    you
    C    c     12     up
    

    选项2有点棘手。一种方法是使用 groupby.apply 应用一个自定义函数 id 她和谁在一起 area 和 info 每人 land :

    def combine(x):
        return '; '.join(f'{i}:{j}' for i,j in x) if len(x) > 1 else f'{x[0][1]}'
    
    tmp = t.groupby('land').apply(lambda x: [combine(list(enumerate(x['id'], 1))),
                                             combine(x[['id','area']].to_numpy()),
                                             combine(x[['id','info']].to_numpy())])
    
    option2 = pd.DataFrame(tmp.tolist(), index=tmp.index, columns=['id','area','info'])
    

    输出:

                     id                area                   info
    land                                                          
    A     1:a; 2:b; 3:c  a:123; b:123; c:23  a:Im; b:gonna; c:give
    B          1:a; 2:c        a:234; c:342         a:never; c:you
    C                 c                  12                     up