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

PANDAS数据帧groupby into list,list in cell data

  •  1
  • Joylove  · 技术社区  · 6 年前

    考虑这个输入df

    my_input_df = pd.DataFrame({
    'export_services': [[1],[2,4,5],[4,6], [2,4,5],[1]], 
    'seaport':['china','africa','europe', 'mexico','europe'], 
    'price_of_fish':['100','200','250','125','75']})
    

    如何对包含列表的列进行分组,并将其他列组合到列表中?

    my_output_df = pd.DataFrame({
    'export_services': [[1],[2,4,5],[4,6]], 
    'seaport':[['china','europe'],['africa','mexico'],'europe'], 
    'price_of_fish':[['100','75'],'200',['250','125']]})
    

    我试过了

    my_input_df.groupby('export_services').apply(list)
    

    哪个给了

    类型错误:不可显示的类型:“list”

    有什么想法吗?

    注意:如果“我的输出”df中的所有分组行都是列表,即使是单个条目,也可以。

    1 回复  |  直到 6 年前
        1
  •  1
  •   user3483203    6 年前

    首先,转换为 tuple ,可以散列:

    df.export_services = df.export_services.apply(tuple)
    

    groupby 具有 agg

    df.groupby('export_services').agg(list).reset_index()
    
      export_services           seaport price_of_fish
    0            (1,)   [china, europe]     [100, 75]
    1       (2, 4, 5)  [africa, mexico]    [200, 125]
    2          (4, 6)          [europe]         [250]