如何使用熊猫从某些csv列创建json数组

时间:2018-09-30 21:08:24

标签: python json pandas csv jupyter-notebook

我有一个约有1000行的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中选择某些列并创建数组。

2 个答案:

答案 0 :(得分:0)

由于您正在使用熊猫:

import pandas as pd

pd.read_csv("myCsvFile.csv").to_json("myJsonFile.json")

答案 1 :(得分:0)

找到答案,结果比我预期的要简单

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)