简体   繁体   中英

Dataframe columns to key value dictionary pair

I have following 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

How I can transform it to following list of dictionaries:

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

Thanks a lot for help.

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

Seems like you need groupby the index

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

Output as list

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

Making a flat list

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM