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

2024-09-30 06:15:24 发布

您现在位置:Python中文网/ 问答频道 /正文

我当前被阻止是因为我想创建一个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,而且原始的[' ', ' ',...]数据并没有得到真正的优化。。。 我认为解决方案是pd.MultiIndexpd.Series,但我不知道如何在我的代码中应用这两种解决方案。你知道吗


Tags: nameidjsonexamplelibtypestatuscustomer
1条回答
网友
1楼 · 发布于 2024-09-30 06:15:24

试试这个:

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'])
           )

相关问题 更多 >

    热门问题