代码之家  ›  专栏  ›  技术社区  ›  Stpete111

使用具有重复密钥名的熊猫从csv文件创建JSON对象

  •  2
  • Stpete111  · 技术社区  · 4 年前

    我一直在使用Pandas从csv文件创建JSON文件——JSON文件中的键名是从csv文件中的头名生成的。我遇到了一个问题,我必须多次使用相同的密钥名(在嵌套对象中),但csv文件中不能有两个同名的头。

    例子:

    到目前为止,我的csv文件将有4列: id data , type , location . 我需要从这些文件中创建一个JSON对象(包括嵌套对象)文件,并使用以下代码完成此操作:

    import pandas as pd
    import json
    import os
    
    csv = "/Users/me/file.csv"
    csv_file = pd.read_csv(csv, sep=",", header=0, index_col=False)
    csv_file['org'] = csv_file[['data', 'type']].apply(lambda s: s.to_dict(), axis=1)
    csv_file[['id', 'org']].to_json("file.json", orient="records", lines=True, date_format="iso", double_precision=10, force_ascii=True, date_unit="ms", default_handler=None)
    

    假设我在csv文件中有一行带有值的数据 1 , ABC XYZ 123 ,上述代码将分别使用此对象创建json文件:

    {
      "id":1,
         "org":{
            "data":"ABC",
            "type":"XYZ"
               },
         "location":"123"
    }
    

    但今天我收到了一个新的csv文件,其中有6列,与上面的4列相同,另外还有两列名为 data1 type1 ,代表 org_2 . 我需要JSON文件中的键名,以便这些值也可以 数据 类型 但我无法将csv文件中的列命名为该名称,b/c已经有具有这些名称的列。

    所以我需要的是,假设6列的值是 , , XYZ 123 , Foo Bar 创建文件中的JSON对象如下所示:

    {
      "id":1,
         "org":{
            "data":"ABC",
            "type":"XYZ"
               },
         "location":"123",
         "org_2":{
            "data":"Foo",
            "type":"Bar"
               }
    }
    

    csv = "/Users/me/file.csv"
    csv_file = pd.read_csv(csv, sep=",", header=0, index_col=False)
    
    csv_file['org'] = csv_file[['data', 'type']].apply(lambda s: s.to_dict(), axis=1)
    csv_file['org_2'] = csv_file[['data1', 'type1']].apply(lambda s: s.to_dict(), axis=1)
    
    csv_file[['id', 'org', 'org_2']].to_json("file.json", orient="records", lines=True, date_format="iso", double_precision=10, force_ascii=True, date_unit="ms", default_handler=None)
    

    除此之外,上面当然要创建名为 数据1 类型1 而我需要他们只是 数据

    2 回复  |  直到 4 年前
        1
  •  3
  •   Mike Henderson    4 年前

    在应用之前,需要重命名列:

    csv_file['org_2'] = csv_file[['data1', 'type1']].set_axis(['data', 'type'], axis=1).apply(lambda s: s.to_dict(), axis=1)
    
        2
  •  1
  •   Durgesh Kumar    4 年前

    我们可以使用rename函数返回一个新的 数据帧 使用重命名的列,并在其上应用lambda函数。

    csv = "/Users/me/file.csv"
    csv_file = pd.read_csv(csv, sep=",", header=0, index_col=False)
    csv_file['org'] = csv_file[['data', 'type']].apply(lambda s: s.to_dict(), axis=1)
    
    csv_file['org_2'] = csv_file[['data1', 'type1']].rename(['data1' : 'data', 'type1':'type']).apply(lambda s: s.to_dict(), axis=1)
    
    csv_file[['id', 'org', 'org_2']].to_json("file.json", orient="records", lines=True, date_format="iso", double_precision=10, force_ascii=True, date_unit="ms", default_handler=None)