Skip to main content
 首页 » 编程设计

python之无法将 Json 转换为 Pandas 数据框

2024年12月31日13小虾米

我有一个这样的 json 文件:

{ 
    "info": [ 
        { 
            "product": "ABC", 
            "email-adr": "abc08@gmail.com", 
            "Gender": "M", 
            "Name": "João", 
            "id": "1069", 
            "mobile": "iOS | 9.1", 
            "client": " " 
        }, 

我尝试过:

data2 = pd.read_json('file.json', encoding=str) 

但是得到了一个只有一列的df:

                      info 
0  {u'id':u'1069',u'client'..     

将此 json 文件读取到 pandas df 的最佳方法是什么?

请您参考如下方法:

您必须仅将内部对象作为参数传递:

import json 
 
z="""{ 
"info": 
[ 
{"product": "ABC", "email-adr": "abc08@gmail.com", "Gender": "M", "Name": "João", "id": "1069", "mobile": "iOS | 9.1", "client": " " }]}""" 
>>> pd.DataFrame(json.loads(z)['info']) 
 
  Gender  Name client        email-adr    id     mobile product 
0      M  João         abc08@gmail.com  1069  iOS | 9.1     ABC 

加载一个json文件:

with open("file.json", "r") as f: 
  data = json.load(f) 

然后你可以做

pd.DataFrame(data['info'])