熊猫数据框到列表的字典

Abi*_*i K 5 python highcharts pandas

如何使用python或pandas(最好)将pandas data_frame转换为列表字典以输入到highcharts中.

我最接近的是(请参阅tmp笔记本:https://b9ad8d-iad-002.tmpnb.org/user-fVD4OAy9K8wR/notebooks/pd_to_json.ipynb)

df.T.to_json('bar.json',orient ='index')但这是'dicts的词典'而不是'list of dict'

我的意见:

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
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

期望的输出:我在Highcharts中使用此输出,这需要它是一个'列表字典',如下所示:

{
"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
]
Run Code Online (Sandbox Code Playgroud)

}

任何帮助深表感谢!

unu*_*tbu 15

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]}
Run Code Online (Sandbox Code Playgroud)

  • 我有点惊讶没有'to_json`这个方向! (2认同)