2017-10-12 134 views
0

我有以下DataFrame数据框中列键值字典对

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

我怎样才能把它转换为以下词典的清单:

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

非常感谢帮助。

回答

3
In [14]: df.set_index('product').T.to_dict('r') 
Out[14]: [{'0.5L': 4, '1.5L': 4, '407': 8, '409': 41, 'SCHWEPPES': 6, 'TONIC 1L': 4}] 
1

好像你需要groupby索引

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

输出列表

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

制作一个平面列表

ll=df.groupby(level='Id').apply(lambda x : x.set_index('product').T.to_dict(orient='records')).tolist() 


import operator 
import functools 
functools.reduce(operator.concat, ll) 

Out[130]: 
[{"'0.5L'": 4, "'1.5L'": 4, "'407'": 8, "'409'": 41}, 
{"'SCHWEPPES'": 6, "'TONIC1L'": 4}]