我有一个 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 文件时出错。
你能帮我解决这个问题吗?
提前致谢
最佳答案
好吧,问题是
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
它有效。
关于Python Pandas DataFrame JSON 转换器列表错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43262397/