2017-04-06 73 views
1

我有一個數據幀,其中一些列我JSON數據,這樣在列表錯誤Python的熊貓數據幀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文件時出現錯誤。

你能幫我解決這個問題嗎?

預先感謝

回答

0

您確定您有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' 

你會得到什麼錯誤?

+0

沒有錯誤,所有工作正常,但Json數據未正確轉換。 – user7311536

+0

請使用:https://www.tutorialspoint.com/execute_python_online.php 編譯代碼: 進口JSON 字符串=「{ 「1」:3.4796488185359, 「2」:0,1 「3」:0 ,「4」:4.4588689023021,「5」:0,「6」:0,「7」:2.3752536905642,「8」:3.7376712853646,「9」:0}' print(json.loads(string).values ()) 正如你將看到編譯器將回答解碼Json的錯誤 – user7311536

+0

對我來說很好。只需注意python 2和3之間'print'語句的區別。 – pansen

1

好了,問題是,在JSON數據下令

json.loads 

不返回列表。

正確的腳本是:

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 

它的工作原理。