将Pandas Dataframe转换为特定的json表单

2024-04-18 19:12:52 发布

您现在位置:Python中文网/ 问答频道 /正文

我一直在研究将pandas数据帧导出到json文件中的不同方法,但是我不确定如何在json中包含其他字符串“constants”。在

其目的是输出一个JSON文件,该文件可以由图表.js. 在

示例中熊猫数据帧的格式为:

df = pandas.DataFrame({
    "labels" : [1,2,3,4,5],
    "data" : [5,4,3,2,1]
})

JSON所需文件的格式为:

^{pr2}$

我可以使用pandas的内置函数将pandas文件导出为JSON,但我不知道如何分离向量并添加上面所示的常量值。在


Tags: 文件数据方法字符串目的json示例dataframe
0条回答
网友
1楼 · 发布于 2024-04-18 19:12:52

我建议使用mako或{a2}这样的模板库。下面是一个包含JSON的快速mako文件,但是它引用了一个DataFrame参数{},当要求mako呈现文档的最终形式(即使用实际数据)时,mako将传递给它。在

以下是文件"pandas_to_json.mako"

<%page args="df"/>

<%
"""Comments about this template file.
"""
# Python imports, helper function definitions, etc.
import pandas
%>

<%text> 
{
    labels: </%text> ${df.labels.values.tolist()} <%text>,
    datasets: [
        {
            label: "My First dataset",
            fillColor: "rgba(220,220,220,0.2)",
            strokeColor: "rgba(220,220,220,1)",
            pointColor: "rgba(220,220,220,1)",
            pointStrokeColor: "#fff",
            pointHighlightFill: "#fff",
            pointHighlightStroke: "rgba(220,220,220,1)",
            data: </%text> ${df.data.values.tolist()} <%text>
        }
    ]
}
</%text>

然后在一个名为what you want的.py文件中(我称之为"pandas_to_json.py"),您可以运行(从与.mako文件相同的目录):

^{pr2}$

它打印出这个:

In [1]: %run pandas_to_json.py




{
    labels:  [1, 2, 3, 4, 5] ,
    datasets: [
        {
            label: "My First dataset",
            fillColor: "rgba(220,220,220,0.2)",
            strokeColor: "rgba(220,220,220,1)",
            pointColor: "rgba(220,220,220,1)",
            pointStrokeColor: "#fff",
            pointHighlightFill: "#fff",
            pointHighlightStroke: "rgba(220,220,220,1)",
            data:  [5, 4, 3, 2, 1] 
        }
    ]
}

要使其工作,您只需安装mako。如果您使用conda包管理工具,那么这段代码对我在ubuntu13上安装makoforpython2.7有用:

conda install -c auto mako

但您也可以使用其他安装工具,如pip,或者只需遵循mako的安装说明。在

出于某种原因,更基本的conda install mako不起作用,声称在linux-64通道中找不到名为mako的包(尽管在我的第一个命令中使用binstar的“auto”通道确实起作用,这表面上应该是等效的)。在

我也听说过jinja的优点,它可能更方便,更容易安装/使用,或者出于其他原因对您更好。在选择一个使用之前,您可能应该检查一下它们。在

这里最重要的一点是,您可以控制模板渲染过程生成什么,而不是任由pandas来为您完成。在

相关问题 更多 >