pandas 数据框到列表字典 [英] Pandas data frame to dictionary of lists

查看:68
本文介绍了 pandas 数据框到列表字典的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

How to use python or pandas (preferably) to convert a pandas data_frame to dictionary of lists for input into highcharts.

我最接近的是(在此处查看tmp笔记本: https://b9ad8d-iad-002.tmpnb.org/user-fVD4OAy9K8wR/notebooks/pd_to_json.ipynb )

The closest I got to was (see tmp notebook here: https://b9ad8d-iad-002.tmpnb.org/user-fVD4OAy9K8wR/notebooks/pd_to_json.ipynb)

df.T.to_json('bar.json',orient ='index') 但这是字典的字典"而不是列表的字典"

df.T.to_json('bar.json', orient='index') But this is a 'dict of dicts' instead of 'dict of lists'

我的输入:

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

所需的输出:我在Highcharts中使用此输出,这要求它是列表字典",如下所示:

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
]

}

非常感谢您的帮助!

推荐答案

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

这篇关于 pandas 数据框到列表字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆