Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pandas data frame to dictionary of lists

How to use Python or Pandas (preferably) to convert a Pandas DataFrame to dictionary of lists for input into highcharts?

The closest I got was:

df.T.to_json('bar.json', orient='index')

But this is a dict of dicts instead of dict of lists.

My input:

import pandas
import numpy as np
 
df = pandas.DataFrame({
    "date": ['2014-10-1', '2014-10-2', '2014-10-3', '2014-10-4', '2014-10-5'],
    "time": [1, 2, 3, 4, 5],
    "temp": np.random.random_integers(0, 10, 5),
    "foo": np.random.random_integers(0, 10, 5)
})

df2 = df.set_index(['date'])
df2

Output:

           time  temp  foo
date                      
2014-10-1     1     3    0
2014-10-2     2     8    7
2014-10-3     3     4    9
2014-10-4     4     4    8
2014-10-5     5     6    2

Desired Output: I am using this output in Highcharts, which requires it to be a dictionary of lists like so:

{'date': ['2014-10-1', '2014-10-2', '2014-10-3', '2014-10-4', '2014-10-5'],
 'foo': [7, 2, 5, 5, 6],
 'temp': [8, 6, 10, 10, 3],
 'time': [1, 2, 3, 4, 5]}
like image 706
Abi K Avatar asked Nov 17 '14 03:11

Abi K


People also ask

Can I convert DataFrame to dictionary?

to_dict() method is used to convert a dataframe into a dictionary of series or list like data type depending on orient parameter.

Can we create DataFrame from Dictionary of lists?

It is the most commonly used pandas object. Creating pandas data-frame from lists using dictionary can be achieved in multiple ways. Let's discuss different ways to create a DataFrame one by one. With this method in Pandas, we can transform a dictionary of lists into a dataframe.

When we create DataFrame from Dictionary of list then list becomes the _?

On Initialising a DataFrame object with this kind of dictionary, each item (Key / Value pair) in dictionary will be converted to one column i.e. key will become Column Name and list in the value field will be the column data i.e.

How do I turn a list of dictionaries into a pandas DataFrame?

Use pd. DataFrame. from_dict() to transform a list of dictionaries to pandas DatFrame. This function is used to construct DataFrame from dict of array-like or dicts.


1 Answers

In [199]: df2.reset_index().to_dict(orient='list')
Out[199]: 
{'date': ['2014-10-1', '2014-10-2', '2014-10-3', '2014-10-4', '2014-10-5'],
 'foo': [8, 1, 8, 8, 1],
 'temp': [10, 10, 8, 3, 10],
 'time': [1, 2, 3, 4, 5]}
like image 135
unutbu Avatar answered Oct 17 '22 08:10

unutbu