如何将列表列表格式的ECharts数据集导出为格式化文件?
问题描述
现有如下Pandas DataFrame:
import pandas as pd data = {'product': ['Matcha Latte', 'Milk Tea', 'Cheese Cocoa', 'Walnut Brownie'], '2015': [43.3, 83.1, 86.4, 72.4], '2016': [85.8, 73.4, 65.2, 53.9], '2017': [93.7, 55.1, 82.5, 39.1]} df = pd.DataFrame(data)
将其转换为ECharts所需的dataset格式:
content = df.T.reset_index().T.values.tolist()
得到的content结构如下:
[['product', '2015', '2016', '2017'], ['Matcha Latte', 43.3, 85.8, 93.7], ['Milk Tea', 83.1, 73.4, 55.1], ['Cheese Cocoa', 86.4, 65.2, 82.5], ['Walnut Brownie', 72.4, 53.9, 39.1]]
使用以下代码导出到文件时,结果为一行紧凑格式,如何导出为带换行的格式化文件?
import json with open('output', 'w') as foo: json.dump(content, foo)
解决方案
使用json.dump()时,添加indent参数指定缩进空格数,同时建议配置字符编码与非ASCII字符保留参数,避免乱码:
修改后的导出代码:
import json with open('output.json', 'w', encoding='utf-8') as foo: json.dump(content, foo, indent=4, ensure_ascii=False)
参数说明
indent=4:设置每行缩进4个空格,生成带换行和缩进的格式化JSON结构ensure_ascii=False:保留中文等非ASCII字符,避免被转义为Unicode编码encoding='utf-8':指定文件编码,防止中文写入时出现乱码
导出后的文件内容示例:
[ [ "product", "2015", "2016", "2017" ], [ "Matcha Latte", 43.3, 85.8, 93.7 ], [ "Milk Tea", 83.1, 73.4, 55.1 ], [ "Cheese Cocoa", 86.4, 65.2, 82.5 ], [ "Walnut Brownie", 72.4, 53.9, 39.1 ] ]
内容的提问来源于stack exchange,提问作者crocefisso
相关产品推荐
相关产品推荐

