Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
169 views
in Technique[技术] by (71.8m points)

python - 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]}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
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]}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...