Pandas 数据框到列表字典
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/26964993/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Pandas data frame to dictionary of lists
提问by Abi K
How to use python or pandas (preferably) to convert a pandas data_frame to dictionary of lists for input into highcharts.
如何使用 python 或 Pandas(最好)将 Pandas data_frame 转换为列表字典以输入到 highcharts。
The closest I got to was (see tmp notebook here: https://b9ad8d-iad-002.tmpnb.org/user-fVD4OAy9K8wR/notebooks/pd_to_json.ipynb)
我最接近的是(请参阅此处的 tmp 笔记本:https: //b9ad8d-iad-002.tmpnb.org/user-fVD4OAy9K8wR/notebooks/pd_to_json.ipynb)
df.T.to_json('bar.json', orient='index') But this is a 'dict of dicts' instead of 'dict of lists'
df.T.to_json('bar.json', orient='index') 但这是一个“dict of dicts”而不是“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


Desired Output: I am using this output in Highcharts, which requires it to be a 'dictionary of lists' like so:
所需输出:我在 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
]
}
}
Any help is much appreciated!
任何帮助深表感谢!
回答by unutbu
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]}
回答by mongotop
to create a list of the dictionaries per line
为每行创建一个字典列表
post_data_list = []
for i in df2.index:
data_dict = {}
for column in df2.columns:
data_dict[column] = df2[column][i]
post_data_list.append(data_dict)

