【问题标题】:How to create a json array from certain csv columns with pandas如何使用熊猫从某些 csv 列创建 json 数组
【发布时间】:2019-03-06 00:52:42
【问题描述】:

我有一个包含大约一千行的 csv 文件,如下所示:

id,name,email,date_of_birth,arrive_time
4657,name1,email1,01/10/1987,15:50
7594,name2,email2,02/10/1987,10:05

我需要在json数组视图中转换:

[
      {
        "name": "name1",
        "date_of_birth": "01/10/1987"
      },
      {
        "name": "name2",
        "date_of_birth": "02/10/1987"
      }
]

我用过的代码:

import csv
import json

file = 'myCsvFile.csv'
json_file = 'myLsonFile.json'

def read_CSV(file, json_file):
    csv_rows = []
    with open(file) as csvfile:
        reader = csv.DictReader(csvfile)
        field = reader.fieldnames
        for row in reader:
            csv_rows.extend([{field[i]:row[field[i]] for i in range(len(field))}])

def convert_write_json(data, json_file):
    with open(json_file, "w") as f:
        f.write(json.dumps(data, sort_keys=False, indent=4, separators=(',', ': ')))
        f.write(json.dumps(data))


read_CSV(file,json_file)

这段代码的输出是

{
    "name": "id;name;email;date_of_birth;arrange_time",
    "date_of_birth": null
}
{
    "name": "4657;name1;email1;01/10/1987;15:50",
    "date_of_birth": null
}

但我不知道如何从 csv 中选择某些列并创建一个数组。

【问题讨论】:

    标签: python json pandas csv jupyter-notebook


    【解决方案1】:

    由于您正在使用熊猫:

    import pandas as pd
    
    pd.read_csv("myCsvFile.csv").to_json("myJsonFile.json")
    

    【讨论】:

      【解决方案2】:

      找到的答案比我预想的要简单

      import csv
      import json
      
          my_list = []
          with open(' myCsvFilr.csv') as csvfile:
              reader = csv.DictReader(csvfile)
              for row in reader:
                  name = row["name"]
                  date_of_birth = row["date_of_birth"]
                  my_dict = {"name":name, "date_of_birth":date_of_birth}   
                  my_list.append(my_dict)
      
          with open('myJsonFile.json', 'w') as outfile:
              json.dump(my_list, outfile, indent= 4)
      

      【讨论】:

        猜你喜欢
        • 2016-07-30
        • 1970-01-01
        • 2017-08-26
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-06-08
        • 2021-09-29
        • 1970-01-01
        相关资源
        最近更新 更多