[英]Convert pandas DataFrame to JSON dictionary of lists
I have a pandas dataframe representing some basic weather info which looks like this我有一个 pandas dataframe 代表一些基本的天气信息,看起来像这样
location![]() |
dDate ![]() |
min-temp![]() |
max-temp![]() |
rain![]() |
---|---|---|---|---|
Sydney![]() |
2013-01-01 ![]() |
15 ![]() |
35 ![]() |
10 ![]() |
Sydney![]() |
2013-01-02 ![]() |
16 ![]() |
36 ![]() |
5 ![]() |
Sydney![]() |
2013-01-03 ![]() |
16 ![]() |
31 ![]() |
0 ![]() |
Sydney![]() |
2013-01-04 ![]() |
16 ![]() |
31 ![]() |
2 ![]() |
To graph it using a JavaScript library such as C3, I need each column as an array in the JSON要使用 JavaScript 库(例如 C3)绘制它,我需要将每一列作为 JSON 中的数组
{
"x": ["2013-01-01", "2013-01-02", "2013-01-03", "2013-01-04"],
"rain": [10, 5, 0, 2],
"max-temp": [35, 36, 31, 31]
}
formatting as column doesn't quite work格式化为列不太有效
df = client.query(query).to_dataframe()
jsonstr = df.to_json(orient='columns')
It results in this结果是这样
{
“location”:{
“0”:Sydney,
“1”:Sydney,
“2”:Sydney,
“3”:Sydney
},
"dDate":{
"0":2013-01-01,
"1":2013-01-02,
"2":2013-01-03,
"3":2013-01-04
},
“min-temp”:{
“0”:15,
“1”:16,
“2”:16,
“3”:16
},
…….
}
How can I reproduce the desired JSON where each colum is just an array of values?如何重现所需的 JSON ,其中每个列只是一个值数组?
to_json
only supports records and nested dict formats. to_json
仅支持记录和嵌套字典格式。 To get a dict of lists, convert to dictionary first using to_dict
, then convert to json:要获取列表的字典,首先使用
to_dict
转换为字典,然后转换为 json:
pd.io.json.dumps(df.to_dict(orient='list'))
# '{"x":["2013-01-01","2013-01-02","2013-01-03","2013-01-04"],"rain":[10,5,0,2],"max-temp":[35,36,31,31]}'
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.