下载数据
CSV文件格式
要在文本文件中存储数据,最简单的方式是将数据作为一系列以逗号分隔的值 以 (CSV)写入文件。这样的文件称为CSV文件。
分析 CSV文件头
csv 模块包含在Python标准库中,可用于分析CSV文件中的数据行,让我们能够快速提取感兴趣的值。同时为了让文件头数据更容易理解,将列表中的每个文件头及其位置打印出来:
highs_lows.py
import csv
from datetime import datetime
filename = 'sitka_weather_07-2018_simple.csv'
with open(filename) as f:
reader = csv.reader(f)
header_row = next(reader)
for index, column_header in enumerate(header_row):
print(index, column_header)
提取并读取数据
我们创建了一个名为highs
的空列表,再遍历文件中余下的各行。阅读器对象从其停留的地方继续往下读取CSV文件,每次都自动返回当前所处位置的下一 行。由于我们已经读取了文件头行,这个循环将从第二行开始——从这行开始包含的是实际数据。每次执行该循环时,我们都将索引1处(第2列)的数据附加到highs
末尾,代码如下:
import csv
filename = 'sitka_weather_07-2018_simple.csv'
with open(filename) as f:
reader = csv.reader(f)
header_row = next(reader)
highs = []
for row in reader:
highs.append(row[1])
print(highs)
绘制气温图表
为可视化这些气温数据,我们首先使用matplotlib
创建一个显示每日最高气温的简单图形。接着在图表中添加日期,使其更有用。知道如何处理CSV文件中的日期后,就可对气温图形进行改进了,即提取日期和最高气温,并将它们传递给plot()
。我们添加了列表lows
,highs
以及dates
,用于存储最低最高气温、以及日期。接下来,我们从数据中提取每天的最低最高气温,并存储它们。添加两个数据系列后,我们就可以了解每天的气温范围了。我们添加了一个对plot()
的调用,以使用蓝色绘制最低气温,红色绘制最高气温。下面来给这个图表做最后的修饰,通过着色来呈现每天的气温范围。为此,我们将使用方法fill_between()
,它 接受一个 x 值系列和两个 y 值系列,并填充两个 y 值系列之间的空间
import csv
from datetime import datetime
from matplotlib import pyplot as plt
filename = 'data/sitka_weather_2018_simple.csv'
with open(filename) as f:
reader = csv.reader(f)
header_row = next(reader)
# Get dates, and high and low temperatures from this file.
dates, highs, lows = [], [], []
for row in reader:
current_date = datetime.strptime(row[2], '%Y-%m-%d')
high = int(row[5])
low = int(row[6])
dates.append(current_date)
highs.append(high)
lows.append(low)
# 从文件中获取最高气温最低气温
plt.style.use('seaborn')
fig, ax = plt.subplots()
ax.plot(dates, highs, c='red', alpha=0.5)
ax.plot(dates, lows, c='blue', alpha=0.5)
plt.fill_between(dates, highs, lows, facecolor='blue', alpha=0.1)
# 根据数据绘制图形
plt.title("Daily high and low temperatures - 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()
运行结果如下: