【问题标题】:How to make multi columns with different rows for each columns如何为每列制作具有不同行的多列
【发布时间】:2020-03-27 02:23:37
【问题描述】:

我目前被阻止,因为我想创建一个 CSV 文件,其中我的第一列只填充键,第二列填充我的值和标题。像这样 :

但实际上看起来像这样:

我的 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,但我不知道如何在我的代码中应用这两个解决方案。

【问题讨论】:

    标签: python json pandas csv


    【解决方案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'])
               )
    

    【讨论】:

    • 这正是我想要的!谢谢,但是您对优化 raw_data 有什么想法吗,主要是这些列表 [' ', ' ', ' ',...]
    • @PunkyLama 很高兴它解决了您的问题。如果您愿意,可以将解决方案标记为已接受。让我看看我是否可以帮助优化
    猜你喜欢
    • 2016-03-10
    • 1970-01-01
    • 2018-12-08
    • 2019-08-31
    • 2021-09-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-07-01
    相关资源
    最近更新 更多