4、提取并读取数据、提取并读取数据
知道数据所在的索引位置之后,首先我们先读取每天的最高气温。
修改修改highs_lows.py文件文件
import csv
#将文件名存储在filename中
filename='sitka_weather_07-2018_simple.csv'
with open(filename) as f:
#创建阅读器(调用csv.reader()将前面存储的文件对象最为实参传给它)
reader=csv.reader(f)
#调用了next()一次,所以这边只调用了文件的第一行,并将头文件存储在header_row中
header_row=next(reader)
highs=[] for row in reader:
highs.append(row[5])
print(highs)
创建了一个空列表highs,遍历我们需要的数据那一列,得到的数据附加到highs末尾。
效果图如下所示:效果图如下所示:
并将字符串转换为数字形式:并将字符串转换为数字形式:
用int()来转换
highs=[] for row in reader:
high=int(row[5])
highs.append(high)
print(highs)
效果图如下所示:效果图如下所示:
5、绘制气温图标、绘制气温图标
对数据进行可视化,用matplotlib创建一个简单图形
修改修改highs_lows.py文件文件
import csv
from matplotlib import pyplot as plt
#将文件名存储在filename中
filename='sitka_weather_07-2018_simple.csv'
with open(filename) as f:
#创建阅读器(调用csv.reader()将前面存储的文件对象最为实参传给它)
reader=csv.reader(f)
#调用了next()一次,所以这边只调用了文件的第一行,并将头文件存储在header_row中
header_row=next(reader)
highs=[] for row in reader:
high=int(row[5])
highs.append(high)
#print(highs)
#头文件索引
#for index,column_header in enumerate(header_row):
#print(index,column_header)
#根据数据绘制图形
fig=plt.figure(dpi=128,figsize=(10,6))
plt.plot(highs,c='red')
#设置图形格式
plt.title("Daily high temperatures July 2018",fontsize=24)
plt.xlabel('',fontsize=24)
plt.ylabel('Temperature(F)',fontsize=16)
评论1
最新资源