【问题标题】:Python Pandas DataFrame JSON converter in List Error列表错误中的 Python Pandas DataFrame JSON 转换器
【发布时间】:2017-09-01 21:50:33
【问题描述】:

我有一个 DataFrame,在某些列中我有 Json 数据,像这样

 A             Ferry_values     
 Ferry          {"0": 3.4796488185359, "1": 0, "2": 0, "3": 4.4588689023021, 
              "4":0, "5":0,"6": 2.3752536905642, "7": 3.7376712853646, "8": 0}

在 Python 中使用:

 import json
 df.ferry_values = df.ferry_values.apply(lambda x: json.loads(x).values())

输出的列表是:

  [0,3.479649,4.458869, 0, 0, 0, 3.737671,2.375254,0]

解码 Json 文件时出错。

你能帮我解决这个问题吗?

提前致谢

【问题讨论】:

    标签: python json list pandas dataframe


    【解决方案1】:

    你确定你有 json 字符串作为值吗?如果我重新创建您的示例,它可以正常工作:

    import json
    
    string = '{"0": 3.4796488185359, "1": 0, "2": 0, "3": 4.4588689023021, "4":0, "5":0,"6": 2.3752536905642, "7": 3.7376712853646, "8": 0}'
    
    print(json.loads(string))
    
    >>> {'0': 3.4796488185359,
         '1': 0,
         '2': 0,
         '3': 4.4588689023021,
         '4': 0,
         '5': 0,
         '6': 2.3752536905642,
         '7': 3.7376712853646,
         '8': 0}
    

    也许,您的专栏中已经有了字典。但是,你应该得到一个TypeError 然后:

    json.loads({"0": 3.4796488185359})
    >>> TypeError: the JSON object must be str, not 'dict'
    

    你得到什么错误?

    【讨论】:

    • 没有错误,一切正常,但是Json数据没有正确转换。
    • 请使用:tutorialspoint.com/execute_python_online.php编译代码: import json string = '{"1": 3.4796488185359, "2": 0 , "3": 0 , "4": 4.4588689023021, " 5": 0, "6": 0,"7": 2.3752536905642, "8": 3.7376712853646, "9": 0}' print(json.loads(string).values()) 正如你将看到的编译器将回答解码错误的 Json
    • 对我来说很好。请注意 python 2 和 3 之间 print 语句的区别。
    【解决方案2】:

    好的,问题是

      json.loads 
    

    不返回 Json 数据中排序的列表。

    正确的脚本是:

     import json
     from collections import OrderedDict
    
     string = '{"1": 3.4796488185359, "2": 0, "3": 0, "4": 4.4588689023021, "5": 
                 0, "6": 0,"7": 2.3752536905642, "8": 3.7376712853646, "9": 0}'
    
     a=json.loads(string, object_pairs_hook=OrderedDict).values()
     print a
    

    有效。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-08-11
      • 2022-01-23
      • 2018-07-13
      • 2018-03-11
      • 2021-07-16
      • 2017-04-13
      • 2021-03-29
      相关资源
      最近更新 更多