@

了解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文件里加上一列索引,这是我们不希望看见的

最新文章

  1. Nginx配置文件nginx.conf中文详解(转)
  2. MSSQLSERVER
  3. LeetCode:Find the Difference_389
  4. ubuntu下Eclipse下添加GBK编码
  5. iOS的三种多线程技术NSThread/NSOperation/GCD
  6. 任务调度quartz
  7. HDU 1300
  8. OK335xS psplash Screen 移植
  9. Android学习 RadioButton
  10. Boa服务器在ARM+Linux上的移植
  11. Scrapy安装问题
  12. PHP 单态设计模式复习
  13. scrapy学习笔记
  14. android webview和 javascript 进行交互
  15. 彻底清除Linux centos minerd木马
  16. shell 问题备忘
  17. docker 在centos6 和centos7上的区别
  18. JGUI源码:解决手机端点击出现半透明阴影(4)
  19. 用java连接RabbitMQ
  20. Illegalmixofcollations (utf8_unicode_ci,IMPLICIT) and (utf8_general_ci,IMPLICIT)foroperation '= 连表查询排序规则问题

热门文章

  1. 如何实现批量上传----------Java解析excel
  2. Bootstrap 中的 aria-label 和 aria-labelledby
  3. 深入理解gradle中的task
  4. matplotlib 单figure多图
  5. es6 curry function
  6. 高阶类 & HOC & anonymous class extends
  7. Interview Questions All In One
  8. AirPods 2 声音非常小
  9. TypeScript 3.7 RC & Assertion Functions
  10. c++ x86_x64挂钩无参数函数