2017-10-12 73 views
2

我有以下DataFrame 3列数据帧与3列词典的词典

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 

我怎样才能把它转换为词典的词典:

{175: {'409':41,'407':8, '0.5L':4, '1.5L':4}, 
177: {'SCHWEPPES':6, 'TONIC 1L':4}} 

非常感谢帮助。

+1

1.你已经试过了什么? 2.保证'my_label'和'product'对是唯一的吗? – DeepSpace

+0

@DeepSpace这个组合是独一无二的 –

+0

您是否看到过我对您先前问题的回答? – Wen

回答

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')} 
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}} 
+0

现在,这是令人印象深刻的。 +1 –

+0

@ScottBoston,谢谢:) – MaxU

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}}