python - Pandas DataFrame to List of Dictionaries -


i have following dataframe:

 customer    item1      item2    item3 1           apple      milk     tomato 2           water      orange   potato 3           juice      mango    chips 

which want translate list of dictionaries per row

rows = [{'customer': 1, 'item1': 'apple', 'item2': 'milk', 'item3': 'tomato'},     {'customer': 2, 'item1': 'water', 'item2': 'orange', 'item3': 'potato'},     {'customer': 3, 'item1': 'juice', 'item2': 'mango', 'item3': 'chips'}] 

use df.t.to_dict().values(), below:

in [1]: df out[1]:    customer  item1   item2   item3 0         1  apple    milk  tomato 1         2  water  orange  potato 2         3  juice   mango   chips  in [2]: df.t.to_dict().values() out[2]: [{'customer': 1.0, 'item1': 'apple', 'item2': 'milk', 'item3': 'tomato'},  {'customer': 2.0, 'item1': 'water', 'item2': 'orange', 'item3': 'potato'},  {'customer': 3.0, 'item1': 'juice', 'item2': 'mango', 'item3': 'chips'}] 

as john galt mentions in his answer , should instead use df.to_dict('records'). it's faster transposing manually.

in [20]: timeit df.t.to_dict().values() 1000 loops, best of 3: 395 µs per loop  in [21]: timeit df.to_dict('records') 10000 loops, best of 3: 53 µs per loop 

Popular posts from this blog

c# - ODP.NET Oracle.ManagedDataAccess causes ORA-12537 network session end of file -

matlab - Compression and Decompression of ECG Signal using HUFFMAN ALGORITHM -

utf 8 - split utf-8 string into bytes in python -