DataFrame有3列到词典字典

时间:2017-10-12 20:54:56

标签: python pandas dataframe

我跟随{'user_id': 10, 'orders_count': 4, 'name': 'bob'} 有3列

DataFrame

如何将其转换为词典词典:

my_label               product             count

175                    '409'                41
175                    '407'                 8
175                    '0.5L'                4
175                    '1.5L'                4
177                    'SCHWEPPES'           6
177                    'TONIC 1L'            4

非常感谢您的帮助。

3 个答案:

答案 0 :(得分:3)

直接的方法是groupby my_label然后迭代生成的行,抓住你需要的值:

In [7]: df
Out[7]:
   my_label      product  count
0       175        '409'     41
1       175        '407'      8
2       175       '0.5L'      4
3       175       '1.5L'      4
4       177  'SCHWEPPES'      6
5       177   'TONIC-1L'      4

In [8]: {k:{t.product:t.count for t in g.itertuples(index=False)} for k,g in df.groupby('my_label')}
Out[8]:
{175: {"'0.5L'": 4, "'1.5L'": 4, "'407'": 8, "'409'": 41},
 177: {"'SCHWEPPES'": 6, "'TONIC-1L'": 4}}

这里的嵌套词典理解写得更整齐:

{k:{t.product:t.count for t in g.itertuples(index=False)} 
    for k,g in df.groupby('my_label')}

答案 1 :(得分:2)

这是一个丑陋的单行:

In [83]: df.set_index('my_label') \
           .groupby(level=0) \
           .apply(lambda x: x.set_index('product').T.to_dict('r')[0]) \
           .to_dict()
Out[83]:
{175: {'0.5L': 4, '1.5L': 4, '407': 8, '409': 41},
 177: {'SCHWEPPES': 6, 'TONIC 1L': 4}}

答案 2 :(得分:0)

My original answer for you previous question

df.groupby(level='Id').apply(lambda x : x.set_index('product').T.to_dict(orient='records')).apply(lambda x : x[0]).to_dict()
Out[137]: 
{175: {"'0.5L'": 4, "'1.5L'": 4, "'407'": 8, "'409'": 41},
 177: {"'SCHWEPPES'": 6, "'TONIC1L'": 4}}