2017-10-12 74 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}}