【问题标题】:pandas dataframe to json python 3熊猫数据框到json python 3
【发布时间】:2017-12-04 09:09:20
【问题描述】:

我有一个包含 3 个系列的 pandas 数据框:

  import pandas as pd
  import json
  import xml.etree.ElementTree as ET

  df1 = pd.read_excel("C:\\Users\\Desktop\\xml.xlsx")
  df1['response'] = df1['response'].astype(str)

  tree = ET.parse(df1.response[1]) #This does not work

数据框中的系列是:

  userid, appid, response 

“响应”是xml文档的问题。我需要将整个东西转换成 JSON。这意味着,像这样:

  "userid" : "21",
  "appid"  : "40",
  "response" : {"xml document as json"}

我遇到问题的步骤是将 xml 转换为 json,然后将其映射到用户 ID。

示例 XML:

 <transactionControl>
<userRefNumber>Credit Report Example</userRefNumber>
<subscriber>
    <industryCode>Z</industryCode>
    <memberCode>03919359</memberCode>
    <inquirySubscriberPrefixCode>1704</inquirySubscriberPrefixCode>
</subscriber>
<options>
    <country>us</country>
    <language>en</language>
</options>
<tracking>
    <transactionTimeStamp>2014-08-02T04:27:02.808-05:00</transactionTimeStamp>
</tracking>

【问题讨论】:

    标签: json python-3.x pandas


    【解决方案1】:

    我相信你需要将strings 转换为jsons by json.loads:

    df1['response'] = df1['response'].astype(str).apply(pd.io.json.loads)
    

    或使用:

    import ast
    df1['response'] = df1['response'].astype(str).apply(ast.literal_eval)
    

    【讨论】:

    • ValueError: Expected object or value。我希望你有问题。 response 包含一个大的 xml 文档,我需要将整个内容转换为示例中的 json。
    • 我添加了另一种转换解决方案,但没有数据硬回答...
    • 我编辑了问题以添加 xml。我发布了很少量的xml。真实数据包含一个大的xml文件。
    • 所以问题不在于json,而在于函数ET.parse,因为数据看起来像xml,而不是jsons?
    • 是的兄弟,它是 xml,这就是整个问题。我需要先将此 xml 转换为 json,然后将带有 userid 和 appis 的整个内容再次转换为 json,以将此数据插入 mongo
    猜你喜欢
    • 2014-02-01
    • 2016-08-07
    • 2018-03-07
    • 2017-11-28
    • 2013-02-23
    • 2020-06-03
    • 2019-12-20
    相关资源
    最近更新 更多