【问题标题】:dataframe to dictionary of list of tuples grouped by key数据帧到按键分组的元组列表字典
【发布时间】:2017-01-18 17:10:31
【问题描述】:

我有一个数据框 df,它看起来如下:

        a    b    c    d
0       8    xx   17   1.0  
1       8    xy   19   1.0 
2       8    zz   13   0.0
3       9    tt   8    5.0

我正在尝试创建一个字典,其中包含一个包含元组列表的键 像下面这样:

{8:[(17,1.0),(19,1.0),(13,0.0)], 9:[(8,5.0)]} 

这里,key来自a列,元组列表是c列和d列,其中key为a。我也将其应用于其他数据集并尝试过

df_new = df.groupby(['a'])[['c','d']).apply(lambda x: [tuple(x) for x in x.values])

但是,我不断收到错误

raise TypeError('Series.name must be a hashable type')
TypeError: Series.name must be a hashable type

我已尝试删除 groupby 中的 ['a'] 并将其保留为 'a',如下所示:

df_new = df.groupby('a')[['c','d']).apply(lambda x: [tuple(x) for x in x.values])

但是,我得到相同的以下错误:

raise TypeError('Series.name must be a hashable type')
TypeError: Series.name must be a hashable type

我不想让原始数据框 df 中的所有内容都不可变。我想保持原样。

有没有办法使用 pandas 功能来实现这一点?我真的不想制作列表,然后按索引将一些压缩在一起并从中创建一个字典。

【问题讨论】:

  • 你的熊猫版本是什么? print (pd.show_versions()) ?

标签: python pandas dictionary dataframe


【解决方案1】:

使用defaultdict

from collections import defaultdict

d = defaultdict(list)
for tup in df.itertuples():
    d[tup.a].append((tup.c, tup.d))

dict(d)

{8: [(17, 1.0), (19, 1.0), (13, 0.0)], 9: [(8, 5.0)]}

*使用to_dictgroupby *

df.set_index(['c', 'd']).groupby('a').apply(lambda df: df.index.tolist()).to_dict()

{8: [(17, 1.0), (19, 1.0), (13, 0.0)], 9: [(8, 5.0)]}

【讨论】:

    【解决方案2】:

    我认为这是错误,但 applyzip 一起工作:

    df = pd.DataFrame({'d': [1.0, 1.0, 0.0, 5.0], 
                       'b': ['xx', 'xy', 'zz', 'tt'], 
                       'a': [8, 8, 8, 9], 
                       'c': [17, 19, 13, 8]})
    print (df)
       a   b   c    d
    0  8  xx  17  1.0
    1  8  xy  19  1.0
    2  8  zz  13  0.0
    3  9  tt   8  5.0
    
    df_new = df.groupby(['a']).apply(lambda x: list(zip(x.c, x.d))).to_dict()
    print (df_new)
    {8: [(17, 1.0), (19, 1.0), (13, 0.0)], 9: [(8, 5.0)]}
    

    对我来说,您的版本适用于(有一个小错字,) 已更改为 ]):

    df_new = df.groupby('a')[['c','d']].apply(lambda x: [tuple(x) for x in x.values]).to_dict()
    print (df_new)
    {8: [(17.0, 1.0), (19.0, 1.0), (13.0, 0.0)], 9: [(8.0, 5.0)]}
    

    【讨论】:

      【解决方案3】:

      只是另一个细微的变化

      df.set_index('a')[['c', 'd']]\
        .apply(tuple, 1)\
        .groupby(level=0)\
        .apply(list)\
        .to_dict()
      
      {8: [(17, 1), (19, 1), (13, 0)], 9: [(8, 5)]}
      

      【讨论】:

        【解决方案4】:

        您可以使用字典理解:

        {k: list(map(tuple, g[['c','d']].values)) for k, g in df.groupby('a')}
        # {8: [(17, 1), (19, 1), (13, 0)], 9: [(8, 5)]}
        

        或者其他方式:

        dict((k, list(map(tuple, g[['c','d']].values))) for k, g in df.groupby('a'))
        

        【讨论】:

        • 这告诉我“['a'] 不在索引中”
        猜你喜欢
        • 1970-01-01
        • 2016-10-10
        • 2021-06-26
        • 2020-03-03
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-12-17
        相关资源
        最近更新 更多