Python 3.x ValueError:将Json数据转换为DataFrame时未正确调用DataFrame构造函数
当我尝试使用pandas和Json包将Json数据转换为数据帧时,遇到了一个问题 Json文件中的原始数据如下所示:Python 3.x ValueError:将Json数据转换为DataFrame时未正确调用DataFrame构造函数,python-3.x,pandas,Python 3.x,Pandas,当我尝试使用pandas和Json包将Json数据转换为数据帧时,遇到了一个问题 Json文件中的原始数据如下所示: {"Number":41,"Type":["A1","A2","A3","A4","A5"],"Percent":{"Very Good":1.2,"Good":2.1,"OK":1.1,"Bad":1.3,"Very Bad":1.7}} Type 0 A1 1 A2 2 A3 3 A4 4 A5 我的代码是: import pandas as p
{"Number":41,"Type":["A1","A2","A3","A4","A5"],"Percent":{"Very Good":1.2,"Good":2.1,"OK":1.1,"Bad":1.3,"Very Bad":1.7}}
Type
0 A1
1 A2
2 A3
3 A4
4 A5
我的代码是:
import pandas as pd
import json
with open('Test.json', 'r') as filename:
json_file=json.load(filename)
df =pd.DataFrame(json_file['Type'],columns=['Type'])
问题是,当我只从Json文件中读取类型时,它会给出正确的结果,如下所示:
{"Number":41,"Type":["A1","A2","A3","A4","A5"],"Percent":{"Very Good":1.2,"Good":2.1,"OK":1.1,"Bad":1.3,"Very Bad":1.7}}
Type
0 A1
1 A2
2 A3
3 A4
4 A5
但是,当仅从Json文件读取数字时:
df =pd.DataFrame(json_file['Number'],columns=['Number'])
它给了我一个错误:ValueError:DataFrame构造函数没有正确调用
如果我使用:
df = pd.DataFrame.from_dict(json_file)
我得到一个错误:
ValueError:将DICT与非系列混用可能导致排序不明确
我对谷歌做了一些研究,但仍然不知道为什么
我的目标是将此Json数据分成两个数据帧,第一个是将数字和类型组合在一起:
Number Type
0 41 A1
1 41 A2
2 41 A3
3 41 A4
4 41 A5
我想获取的另一个数据帧是百分比中的数据,它可能看起来像:
Very Good 1.2
Good 2.1
OK 1.1
Bad 1.3
Very Bad 1.7
这将为您提供所需的输出:
with open('Test.json', 'r') as filename:
json_file=json.load(filename)
df = pd.DataFrame({'Number': json_file.get('Number'), 'Type': json_file.get('Type')})
df2 = pd.DataFrame({'Percent': json_file.get('Percent')})
Number type
0 41 A1
1 41 A2
2 41 A3
3 41 A4
4 41 A5
Percent
Bad 1.3
Good 2.1
OK 1.1
Very Bad 1.7
Very Good 1.2
您可以将其概括为一个函数:
def json_to_df(d, ks):
return pd.DataFrame({k: d.get(k) for k in ks})
df = json_to_df(json_file, ['Number', 'Type'])
如果您希望避免使用json包,可以直接在pandas中使用:
_df = pd.read_json('Test.json', typ='series')
df = pd.DataFrame.from_dict(dict(_df[['Number', 'Type']]))
df2 = pd.DataFrame.from_dict(_df['Percent'], orient='index', columns=['Percent'])
看一看pandas read_jsonhello非常感谢您的回复,我对我的问题做了一些调整,我查看了实际数据,它比我之前发布的更复杂,您能给我一些想法吗?