【问题标题】:Create JSON object(s) from csv file with Pandas with duplicate key names使用具有重复键名的 Pandas 从 csv 文件创建 JSON 对象
【发布时间】:2021-09-14 06:33:22
【问题描述】:

Python 3.9.5/熊猫 1.1.3

我一直在使用 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 文件中的键名也为 data 和 type 但我无法将 csv 文件中的列命名为,b/c 已经存在具有这些名称的列。

所以我需要的是,假设 6 列值是 1、ABC、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)

除了上面当然会创建名为data1和type1的键,而我需要它们只是data和type。

【问题讨论】:

    标签: python pandas csv


    【解决方案1】:

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

    csv_file['org_2'] = csv_file[['data1', 'type1']].set_axis(['data', 'type'], axis=1).apply(lambda s: s.to_dict(), axis=1)
    

    【讨论】:

    • 正是我想要的。谢谢迈克。
    【解决方案2】:

    我们可以使用重命名函数,它返回一个带有重命名列的新数据框,并在其上应用 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)
    
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-04-11
      • 1970-01-01
      • 2017-10-04
      • 2017-07-12
      • 2019-08-04
      • 1970-01-01
      • 2020-10-27
      相关资源
      最近更新 更多