一、处理CSV数据
1、模块:csv
2、相关函数
1)reader()—返回以“行”为元素的列表,【后面贴出help(csv.reader)】
2)next()—传入阅读对象,返回文件的下一行。当调用next()一次时,得到文件的头行。
3)int()—返回与字符串对应的整数【后面有代码测试补充】
4)datetime模块中的striptime(),将字符串日期装换成日期的格式
5)fig.autofmt_xdate()—绘制斜的日期标签
6)fill_between(x,y1,y2)—填充两个y值系列的空间
3、实例(天气数据)【中间有个注释的try-except-else模块,用于防止日期数据出错】
import csv
from datetime import datetime
from matplotlib import pyplot as plt
filename = 'E:\jupyter_code\二零一八年天气数据.csv'
#从文件中获取最高气温、最低气温
with open(filename) as f:
reader = csv.reader(f)
header_row = next(reader)
dates, highs, lows = [],[],[]
for row in reader:
current_date = datetime.strptime(row[2],"%Y-%m-%d")
dates.append(current_date)
high = int(row[5])
highs.append(high)
low = int(row[6])
lows.append(low)
"""""
try:
current_date = datetime.strptime(row[2],"%Y-%m-%d")
high = int(row[5])
low = int(row[6])
except:ValueError
print('missing date')
else:
dates.append(current_date)
highs.append(high)
lows.append(low)
"""
#根据数据绘制图形
fig = plt.figure(dpi=128, figsize=(10,6))
plt.plot(dates,highs) #plt.plot(dates,highs,lows)这样会报错,还是要分开画
plt.plot(dates,lows)
plt.fill_between(dates,highs,lows,facecolor='blue', alpha=0.1)
#设置图像的格式
plt.title("Daily high and low temperature - 2018",fontsize=24)
plt.xlabel('',fontsize=16)
fig.autofmt_xdate()
plt.ylabel("Temperature (F)",fontsize=16)
plt.tick_params(axis='both',which='major',labelsize=16)
plt.show()
二、处理JSON文件
前面提过对json文件的操作,这里不再重复。
1、所用模块:json
2、涉及的函数
1)float()—将字符串转换成浮点数
3、应用(人口地图)
import json
import pygal
from pygal_maps_world.i18n import COUNTRIES #位置01——与书籍代码不一样之处
from pygal.style import LightColorizedStyle as LCS,RotateStyle as RS #设置样式,主题参数
#载入数据
filename = 'E:\jupyter_code\population.json'
with open(filename) as f:
pop_data = json.load(f)
#获取国别代码
def get_country_code(country_name):
for code,name in COUNTRIES.items():
if country_name == name:
return code
#创建字典{国家:人口数}
cc_populations = {}
for pop_dict in pop_data:
if pop_dict["Year"] == 2010: #位置02-与书籍代码不一样之处
country = pop_dict['Country Name']
population = int(float(pop_dict['Value']))
code = get_country_code(country)
if code:
cc_populations[code] = population
#根据人口数量将所有国家分成三组
cc_pops_1, cc_pops_2, cc_pops_3 = {},{},{}
for cc, pop in cc_populations.items():
if pop < 10000000:
cc_pops_1[cc] = pop
elif pop < 1000000000:
cc_pops_2[cc] = pop
else:
cc_pops_3[cc] = pop
#看看每组包含多少个国家
print(len(cc_pops_1),len(cc_pops_2),len(cc_pops_3))
wm_style = RS('#336699',base_style=LCS)
wm = pygal.maps.world.World() #位置03-与书籍代码不一样之处
wm.title = "world population in 2010,by country"
wm.add('0-10m',cc_pops_1)
wm.add('10m-1bm',cc_pops_2)
wm.add('>1bm',cc_pops_3)
wm.render_to_file('E:\jupyter_code\world_population_2.svg')