如何使多列各列具有不同的行

时间:2019-12-02 13:03:34

标签: python json pandas csv

我目前被封锁,因为我想制作一个CSV文件,其第一列仅用键填充,而第二列则用值和标题填充。像这样 : Screenshot 1

但实际上看起来像这样: Screenshot 2

我的JSON测试文件:

{
 "name":"<customer>_<datetime>.zip",
 "status":"OK",
 "lib_status":"SUCCESS",
 "ID":" ",
 "ID_emitter":"<customer>",
 "recipient":" ",
 "validator":{
     "sender_email_address":"example@example.com",
     "sender_email_address_no_reply":"example@example.com"
     },
 "connexFileList":[
   {
        "connexFile":"<customer>_<datetime>",
        "type":"json"
   }
   ],
  "PReS":{
    "domain":" ",
    "client":" ",
    "inputFlowList":[
        {
            "inputFile":" ",
            "type":" ",
            "status":" "
        }
        ]
    }
   }

我当前的代码:

import json
import pandas as pd

with open('test.json') as f:
    json_dict = json.load(f)

name = json_dict['name']
status = json_dict['status']
lib_status = json_dict['lib_status']
ID_emitter = json_dict['ID_emitter']

for connexFileList in json_dict['connexFileList']:
    connexFile = connexFileList['connexFile'],
    type2 = connexFileList['type']

for PReS in json_dict['PReS']['inputFlowList']:
    inputFile = PReS['inputFile']
    type3 = PReS['type']
    status2 = PReS['status']

raw_data = {
"firstitem": [name, status, lib_status, ID_emitter, '', '', '', '', ''],
"connexFileList": ['', '', '', '', connexFile, type2, '', '', ''],
"PReS": ['','','','','','', inputFile, type3, status2],
}

df = pd.DataFrame(raw_data,
              index=pd.Index(['name :', 'status :', 'lib_status', 'ID_emitter', 
                              'connexFile','type','inputFile', 'type', 'status']),
              columns=pd.Index(['firstitem', 'connexFileList', 'PReS'])
              )
df.to_csv('test.csv', sep=";")

但这不是我想要的CSV,而[' ', ' ',...]的raw_data并没有真正优化... 我认为解决方案是pd.MultiIndexpd.Series,但我不知道这两种解决方案在我的代码中如何应用。

1 个答案:

答案 0 :(得分:1)

只需尝试一下:

raw_data = {
 "firstitem": [name, status, lib_status, ID_emitter, '', '', '', '', ''],
 " ": ['connexFile','type','', '', '', '', '', '', ''],
 "connexFileList": [connexFile, type2, '', '', '','', '', '', ''],
 "PReS": ['','','','','','', inputFile, type3, status2],
"": ['inputFile','type','status', '', '', '', '', '', '']
 }

df = pd.DataFrame(raw_data,
           index=pd.Index(['name', 'status', 'lib_status', 'ID_emitter', 
                           '','','', '', '']),
           columns=pd.Index(['firstitem', ' ','connexFileList','', 'PReS'])
           )