最新下载
热门教程
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
使用python把json文件转换为csv文件代码示例
时间:2021-03-13 编辑:袖梨 来源:一聚教程网
本篇文章小编给大家分享一下使用python把json文件转换为csv文件代码示例,文章代码介绍的很详细,小编觉得挺不错的,现在分享给大家供大家参考,有需要的小伙伴们可以来看看。
了解json整体格式
这里有一段json格式的文件,存着全球陆地和海洋的每年异常气温(这里只选了一部分):global_temperature.json
{ "description": { "title": "Global Land and Ocean Temperature Anomalies, January-December", "units": "Degrees Celsius", "base_period": "1901-2000" }, "data": { "1880": "-0.1247", "1881": "-0.0707", "1882": "-0.0710", "1883": "-0.1481", "1884": "-0.2099", "1885": "-0.2220", "1886": "-0.2101", "1887": "-0.2559" } }
通过python读取后可以看到其实json就是dict类型的数据,description和data字段就是key
由于json存在层层嵌套的关系,示例里面的data其实也是dict类型,那么年份就是key,温度就是value
转换格式
现在要做的是把json里的年份和温度数据保存到csv文件里
提取key和value
这里我把它们转换分别转换成int和float类型,如果不做处理默认是str类型
year_str_lst = json_data['data'].keys() year_int_lst = [int(year_str) for year_str in year_str_lst] temperature_str_lst = json_data['data'].values() temperature_int_lst = [float(temperature_str) for temperature_str in temperature_str_lst] print(year_int) print(temperature_int_lst)
使用pandas写入csv
import pandas as pd # 构建 dataframe year_series = pd.Series(year_int_lst,name='year') temperature_series = pd.Series(temperature_int_lst,name='temperature') result_dataframe = pd.concat([year_series,temperature_series],axis=1) result_dataframe.to_csv('./files/global_temperature.csv', index = None)
axis=1,是横向拼接,若axis=0则是竖向拼接
最终效果
注意
如果在调用to_csv()方法时不加上index = None,则会默认在csv文件里加上一列索引,这是我们不希望看见的
相关文章
- Golang ProtoBuf的基本语法详解 10-20
- Python识别MySQL中的冗余索引解析 10-20
- Python+Pygame绘制小球代码展示 10-18
- Python中的数据精度问题介绍 10-18
- Python随机值生成的常用方法介绍 10-18
- python3解压缩.gz文件分析 09-27