如何使用python把json文件转换为csv文件
2024-09-20 22:35:25
@
了解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文件里加上一列索引,这是我们不希望看见的
最新文章
- Nginx配置文件nginx.conf中文详解(转)
- MSSQLSERVER
- LeetCode:Find the Difference_389
- ubuntu下Eclipse下添加GBK编码
- iOS的三种多线程技术NSThread/NSOperation/GCD
- 任务调度quartz
- HDU 1300
- OK335xS psplash Screen 移植
- Android学习 RadioButton
- Boa服务器在ARM+Linux上的移植
- Scrapy安装问题
- PHP 单态设计模式复习
- scrapy学习笔记
- android webview和 javascript 进行交互
- 彻底清除Linux centos minerd木马
- shell 问题备忘
- docker 在centos6 和centos7上的区别
- JGUI源码:解决手机端点击出现半透明阴影(4)
- 用java连接RabbitMQ
- Illegalmixofcollations (utf8_unicode_ci,IMPLICIT) and (utf8_general_ci,IMPLICIT)foroperation '= 连表查询排序规则问题
热门文章
- 如何实现批量上传----------Java解析excel
- Bootstrap 中的 aria-label 和 aria-labelledby
- 深入理解gradle中的task
- matplotlib 单figure多图
- es6 curry function
- 高阶类 &; HOC &; anonymous class extends
- Interview Questions All In One
- AirPods 2 声音非常小
- TypeScript 3.7 RC &; Assertion Functions
- c++ x86_x64挂钩无参数函数