赞
踩
首先导入两个包:
import json
import pandas as pd
打开json 文件并读取:
with open('2.json', encoding='utf-8') as f:
line = f.readline()
d = json.loads(line)
f.close()
读取的json数据会以字典的形势保存,按照字典的读取方式获取自己想要的数据:
datas_x = []
datas_y = []
for dss in d:
datas_x.append(float(dss["pos"]["x"]))
datas_y.append(float(dss["pos"]["z"]))
将数据保存到列表中,然后创建pandas的DataFrame,DataFrame是由多种类型的列构成的二维标签数据结构。
path_x = pd.Series(datas_x)
path_y = pd.Series(datas_y)
path_df = pd.DataFrame()
path_df['pathx'] = path_x
path_df['pathy'] = path_y
最后将数据保存到csv中。
filepath = "E:\\python\\python\\2021\\202104\\0409\\path_data.csv"
path_df.to_csv(filepath, index=False, header=False)
完整代码:
import json import pandas as pd filepath = "E:\\python\\python\\2021\\202104\\0409\\path_data.csv" with open('2.json', encoding='utf-8') as f: line = f.readline() d = json.loads(line) f.close() datas_x = [] datas_y = [] for dss in d: datas_x.append(float(dss["pos"]["x"])) datas_y.append(float(dss["pos"]["z"])) path_x = pd.Series(datas_x) path_y = pd.Series(datas_y) path_df = pd.DataFrame() path_df['pathx'] = path_x path_df['pathy'] = path_y path_df.to_csv(filepath, index=False, header=False)
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。