简体   繁体   English

使用 python pandas 将 CSV 转换为 JSON

[英]Convert CSV to JSON using python pandas

Till now I can come up with this only:直到现在我只能想出这个:

filename = "newsample2.csv"
jsonFileName = "myjson2.json"

import pandas as pd
df = pd.read_csv ('newsample2.csv')

df.to_json ('myjson2.json', indent=4, orient='recod')

CSV File: https://drive.google.com/file/d/19u8M0wFrUq8E9um3l6sw0UZeQZRWTxNb/view?usp=sharing CSV 文件: https : //drive.google.com/file/d/19u8M0wFrUq8E9um3l6sw0UZeQZRWTxNb/view?usp=sharing

Sample JSON (I need json in this format only) https://drive.google.com/file/d/1UXCi5u_ywmhst_vW3s1Z2HdjO_auFDZz/view?usp=sharing示例 JSON(我只需要这种格式的 json) https://drive.google.com/file/d/1UXCi5u_ywmhst_vW3s1Z2HdjO_auFDZz/view?usp=sharing

Here is what you need to do.这是您需要做的。

  • Read the csv file using pandas.使用 Pandas 读取 csv 文件。

csv_data = pd.read_csv('newsample.csv') final_dic_json = {"ReelStripsDefinition":[]}

  • Initialize lists to store temporary data.初始化列表以存储临时数据。 For example,例如,

base_strip = []

  • Iterate over each column in DataFrame, and store data in lists created in last step.迭代 DataFrame 中的每一列,并将数据存储在上一步创建的列表中。

  • Create a dictionary like this (I have used the keys as in json file you provided): base_strip1_dic = {"base_strip1": { "Enabled": true, "Stops": []}}创建这样的字典(我使用了您提供的 json 文件中的键): base_strip1_dic = {"base_strip1": { "Enabled": true, "Stops": []}}

  • Similarly you will create other dictionaries.同样,您将创建其他词典。

  • Finally final_dic_json["ReelStripsDefinition"] = base_strip1_dic final_dic_json.append(base_strip2_dic) and so on.最后final_dic_json["ReelStripsDefinition"] = base_strip1_dic final_dic_json.append(base_strip2_dic)等等。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM