【问题标题】:how to parse multi index values and create a csv file while parsing json data in python如何在python中解析json数据时解析多索引值并创建csv文件
【发布时间】:2019-05-31 05:51:50
【问题描述】:

我有几个静态键列 EmployeeId、type 和几个来自第一个 FOR 循环的列。

在第二个 FOR 循环中,如果我有一个特定的键,那么只有值应该附加到现有的数据框列,否则无论从第一个 for 循环获取的列应该保持不变。

第一个 For 循环输出:

"EmployeeId","type","KeyColumn","Start","End","Country","Target","CountryId","TargetId"
"Emp1","Metal","1212121212","2000-06-17","9999-12-31","","","",""

在第二个 For 循环之后,我有以下输出:

"EmployeeId","type","KeyColumn","Start","End","Country","Target","CountryId","TargetId"
"Emp1","Metal","1212121212","2000-06-17","9999-12-31","","AMAZON","1",""
"Emp1","Metal","1212121212","2000-06-17","9999-12-31","","FLIPKART","2",""

根据代码,如果我有可用的员工标签,我有超过 2 条记录,但我可能有几个没有员工标签的 json 文件,那么输出应该与第一个循环输出相同。

但是根据我的代码,我得到了 0 条记录。如果我的编码方式错误,请帮助我。

真的很抱歉 - 如果提问的方式不清楚,因为我是 python 新手。请在下面的超链接中找到代码

请在下面找到代码

    for i in range(len(json_file['enty'])):
        temp = {}
        temp['EmployeeId'] = json_file['enty'][i]['id']
        temp['type'] = json_file['enty'][i]['type']
        for key in json_file['enty'][i]['data']['attributes'].keys():        
            try:
                temp[key] = json_file['enty'][i]['data']['attributes'][key]['values'][0]['value']
            except:
                temp[key] = None      

        for key in json_file['enty'][i]['data']['attributes'].keys(): 
            if(key == 'Employee'):
                for j in range(len(json_file['enty'][i]['data']['attributes']['Employee']['group'])):
                    for key in json_file['enty'][i]['data']['attributes']['Employee']['group'][j].keys():
                        try:
                            temp[key] = json_file['enty'][i]['data']['attributes']['Employee']['group'][j][key]['values'][0]['value']
                        except:
                            temp[key] = None

                    temp_df = pd.DataFrame([temp])
                    df = pd.concat([df, temp_df], sort=True)

    # Rearranging columns
    df = df[['EmployeeId', 'type'] + [col for col in df.columns if col not in ['EmployeeId', 'type']]]

    # Writing the dataset
    df[columns_list].to_csv("Test22.csv", index=False, quotechar='"', quoting=1)

如果员工标签不可用,我将获得 0 条记录作为输出,但我希望根据第一个 FOR 循环的输出有 1 条记录。如果“员工标签”可用,那么我期待 2 条记录以及我的静态列“EmployeeId”、“type”、“KeyColumn”、“Start”、“End”,否则如果标签不可用,则所有静态列列 "EmployeeId","type","KeyColumn","Start","End",其余列为空白

enter link description here

【问题讨论】:

    标签: python json pandas dataframe


    【解决方案1】:

    修改代码的长期解决方案,因此添加一个循环、更改索引以及修改 range 参数:

    df = pd.DataFrame()
    
    num = max([len(v) for k,v in json_file['data'][0]['data1'].items()])
    for i in range(num):
        temp = {}
        temp['Empid'] = json_file['data'][0]['Empid']
        temp['Empname'] = json_file['data'][0]['Empname']
        for key in json_file['data'][0]['data1'].keys():
            if key not in temp:
                temp[key] = []
            try:
                for j in range(len(json_file['data'][0]['data1'][key])):
                    temp[key].append(json_file['data'][0]['data1'][key][j]['relative']['id']) 
            except:
                temp[key] = None                    
        temp_df = pd.DataFrame([temp])
        df = pd.concat([df, temp_df],ignore_index=True)
    for i in json_file['data'][0]['data1'].keys():
        df[i] = pd.Series([x for y in df[i].tolist() for x in y]).drop_duplicates()
    

    现在:

    print(df)
    

    是:

      Empid Empname    XXXX   YYYYY
    0  1234     ABC  Naveen   Kumar
    1  1234     ABC     NaN  Rajesh
    

    【讨论】:

    • 非常感谢您的回复。我试过了,但出现错误“IndexError: list index out of range”
    • 我只是根据我的数据进行处理,这种方法奏效了......非常感谢。
    • 需要一个建议..在其中一个功能中..我可以问吗?
    • 非常感谢您的回复。我附上了一张屏幕截图。我收到“TypeError: 'int' object is not iterable”。请帮我提出任何建议..
    • 问题:实际上我有“员工”标签作为多值。因此,对于某些 Json 文件,我可能有“EmployeeTag”,但对于某些 Json 文件,我可能没有它。为了克服,我提供了“IF”条件。但是,如果标签不可用,我会在使用上述 Max(Len) 建议之前获得 0 条记录。我想要的输出就像我有“员工”标签,那么我需要获取值,如果没有,我应该将它们设为空白并且需要显示一条记录。为了处理这种情况,我添加了这个建议,我正面临 TypeError
    猜你喜欢
    • 1970-01-01
    • 2018-11-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多