【问题标题】:Pandas groupby and get dict in listPandas groupby 并在列表中获取字典
【发布时间】:2019-05-24 02:08:41
【问题描述】:

我正在尝试提取分组的行数据以使用值将其与标签颜色一起绘制到另一个文件中。

我的数据框如下所示。

df = pd.DataFrame({'x': [1, 4, 5], 'y': [3, 2, 5], 'label': [1.0, 1.0, 2.0]})

    x   y   label
0   1   3   1.0
1   4   2   1.0
2   5   5   2.0

我想得到一组标签列表,如

{'1.0': [{'index': 0, 'x': 1, 'y': 3}, {'index': 1, 'x': 4, 'y': 2}],
 '2.0': [{'index': 2, 'x': 5, 'y': 5}]}

如何做到这一点?

【问题讨论】:

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


    【解决方案1】:

    您可以将collections.defaultdictto_dict 一起使用:

    from collections import defaultdict
    
    # add 'index' series
    df = df.reset_index()
    
    # initialise defaultdict
    dd = defaultdict(list)
    
    # iterate and append
    for d in df.to_dict('records'):
        dd[d['label']].append(d)
    

    结果:

    print(dd)
    
    defaultdict(list,
                {1.0: [{'index': 0.0, 'x': 1.0, 'y': 3.0, 'label': 1.0},
                       {'index': 1.0, 'x': 4.0, 'y': 2.0, 'label': 1.0}],
                 2.0: [{'index': 2.0, 'x': 5.0, 'y': 5.0, 'label': 2.0}]})
    

    一般来说,不需要转换回常规的dict,因为defaultdictdict 的子类。

    【讨论】:

    • 感谢它有效。我知道 defaultdict 可以像 dict 一样使用。
    【解决方案2】:

    @cph_sto 提供的几乎是您想要的最快解决方案,

    >>> df.reset_index().to_dict('records')
    [{'index': 0.0, 'label': 1.0, 'x': 1.0, 'y': 3.0}, {'index': 1.0, 'label': 1.0, 'x': 4.0, 'y': 2.0}, {'index': 2.0, 'label': 2.0, 'x': 5.0, 'y': 5.0}]
    

    也就是说,将索引转换为常规列,然后应用to_dictrecords 版本。另一个感兴趣的选择:

    >>> df.to_dict('index')
    {0: {'label': 1.0, 'x': 1.0, 'y': 3.0}, 1: {'label': 1.0, 'x': 4.0, 'y': 2.0}, 2: {'label': 2.0, 'x': 5.0, 'y': 5.0}}
    

    查看to_dict 上的帮助以获取更多信息。

    【讨论】:

      【解决方案3】:

      您可以使用itertuplesdefulatdict

      itertuples 返回命名元组以迭代数据帧:

      for row in df.itertuples():
          print(row)
      Pandas(Index=0, x=1, y=3, label=1.0)
      Pandas(Index=1, x=4, y=2, label=1.0)
      Pandas(Index=2, x=5, y=5, label=2.0)
      

      因此利用这一点:

      from collections import defaultdict
      dictionary = defaultdict(list)
      for row in df.itertuples():
          dummy['x'] = row.x
          dummy['y'] = row.y
          dummy['index'] = row.Index
          dictionary[row.label].append(dummy)
      
      dict(dictionary)
      > {1.0: [{'x': 1, 'y': 3, 'index': 0}, {'x': 4, 'y': 2, 'index': 1}],
       2.0: [{'x': 5, 'y': 5, 'index': 2}]}
      

      【讨论】:

        【解决方案4】:
        df = pd.DataFrame({'x': [1, 4, 5], 'y': [3, 2, 5], 'label': [1.0, 1.0, 2.0]})
        df['index'] = df.index
        df
           label  x  y  index
        0    1.0  1  3      0
        1    1.0  4  2      1
        2    2.0  5  5      2
        
        df['dict']=df[['x','y','index']].to_dict("records")
        df
           label  x  y  index                             dict
        0    1.0  1  3      0  {u'y': 3, u'x': 1, u'index': 0}
        1    1.0  4  2      1  {u'y': 2, u'x': 4, u'index': 1}
        2    2.0  5  5      2  {u'y': 5, u'x': 5, u'index': 2}
        
        df = df[['label','dict']]
        df['label'] = df['label'].apply(str) #Converting integer column 'label' to string
        df = df.groupby('label')['dict'].apply(list) 
        desired_dict = df.to_dict()
        desired_dict 
            {'1.0': [{'index': 0, 'x': 1, 'y': 3}, {'index': 1, 'x': 4, 'y': 2}],
             '2.0': [{'index': 2, 'x': 5, 'y': 5}]}
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2017-12-22
          • 2015-05-04
          • 2022-12-01
          • 2019-02-15
          • 2013-07-14
          • 1970-01-01
          • 2021-08-07
          相关资源
          最近更新 更多