美文网首页
Python数据可视化day04|下载数据

Python数据可视化day04|下载数据

作者: 习惯芥末味 | 来源:发表于2018-04-21 18:43 被阅读0次

我们将访问并可视化以两种常见格式存储的数据:CSV 和JSON。

CSV文件格式

将数据作为一系列以逗号分隔的值写入文件的文件被称为CSV文件。例如:

2014-1-5,61,44,26,18,7,-1,56,30,9,30.34,30.27,30.15,,,,10,4,,0.00,0,,195

分析CSV文件头

csv 模块包含在Python标准库中,可用于分析CSV文件中的数据行,让我们能够快速提取感兴趣的值。下面先来查看sitka_weather_07-2014.csv文件下载地址地址文件的第一行,其中包含一系列有关数据的描述:

➜ highs_lows.py
import csv

filename = 'sitka_weather_07-2014.csv'

with open(filename) as f:
    reader = csv.reader(f)
    header_row = next(reader)
    print(header_row)

打印结果:

['AKDT', 'Max TemperatureF', 'Mean TemperatureF', 'Min TemperatureF', 'Max Dew PointF', 'MeanDew PointF', 'Min DewpointF', 'Max Humidity', ' Mean Humidity', ' Min Humidity', ' Max Sea Level PressureIn', ' Mean Sea Level PressureIn', ' Min Sea Level PressureIn', ' Max VisibilityMiles', ' Mean VisibilityMiles', ' Min VisibilityMiles', ' Max Wind SpeedMPH', ' Mean Wind SpeedMPH', ' Max Gust SpeedMPH', 'PrecipitationIn', ' CloudCover', ' Events', ' WindDirDegrees']

打印文件头及其位置

➜ highs_lows.py
import csv

filename = 'sitka_weather_07-2014.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)

输出如下,其中指出了每个文件头的索引:

(0, 'AKDT')
(1, 'Max TemperatureF')
(2, 'Mean TemperatureF')
(3, 'Min TemperatureF')
(4, 'Max Dew PointF')
(5, 'MeanDew PointF')
(6, 'Min DewpointF')
(7, 'Max Humidity')
(8, ' Mean Humidity')
(9, ' Min Humidity')
(10, ' Max Sea Level PressureIn')
(11, ' Mean Sea Level PressureIn')
(12, ' Min Sea Level PressureIn')
(13, ' Max VisibilityMiles')
(14, ' Mean VisibilityMiles')
(15, ' Min VisibilityMiles')
(16, ' Max Wind SpeedMPH')
(17, ' Mean Wind SpeedMPH')
(18, ' Max Gust SpeedMPH')
(19, 'PrecipitationIn')
(20, ' CloudCover')
(21, ' Events')
(22, ' WindDirDegrees')

提取并读取数据
知道需要哪些列中的数据后,我们来读取一些数据。首先读取每天的最高气温:

➜ highs_lows.py
import csv

#从文件中获取最高气温
filename = 'sitka_weather_07-2014.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)

下面显示了highs 现在存储的数据:

['64', '71', '64', '59', '69', '62', '61', '55', '57', '61', '57', '59', '57', '61', '64', '61', '59', '63', '60', '57', '69', '63', '62', '59', '57', '57', '61', '59', '61', '61', '66']

我们提取了每天的最高气温,并将它们作为字符串整洁地存储在一个列表中。
下面使用int() 将这些字符串转换为数字,让matplotlib能够读取它们:

--snip--
highs = []
    for row in reader:
        high = int(row[1])  #将字符串准换为数字
        highs.append(high)
    print(highs)

绘制气温图表

为可视化这些气温数据,我们使用matplotlib创建一个显示每日最高气温的简单图形:

➜ highs_lows.py
import csv
from matplotlib import pyplot as plt

#从文件中获取最高气温
--snip--
#根据数据绘制图形
fig = plt.figure(dpi=128, figsize=(10, 6))
plt.plot(highs, c='red')
# 设置图形的格式
plt.title("Daily high temperatures, July 2014", fontsize=24)
plt.xlabel('', fontsize=16)
plt.ylabel("Temperature (F)", fontsize=16) 
plt.tick_params(axis='both', which='major', labelsize=16)

plt.show()
气温折线图

模块datetime

再添加数据之前,要将字符串'2014-7-1'使用模 块datetime 中的方法strptime()将其转换为一个表示相应日期的对象:

>>> from datetime import datetime
>>> first_date = datetime.strptime('2018-4-21','%Y-%m-%d')
>>> print(first_date)

输出结果为:

2018-04-21 00:00:00

方法strptime() 可接受各种实参,并根据它们来决定如何解读日期。
模块datetime中设置日期和时间格式的实参

实参 含义
%A 星期的名称,如Monday
%B 月份名,如January
%m 用数字表示的月份(01~12)
%d 用数字表示月份中的一天(01~31)
%Y 四位的年份,如2018
%y 两位的年份,如18
%H 24小时制式的小时数(00~23)
%I 12小时制式的小时数(01~12)
%p am或pm
%M 分钟数(00~59)
%S 秒数(00~61)

在图表中添加日期

➜ highs_lows.py
import csv
from datetime import datetime

from matplotlib import pyplot as plt

#从文件中获取日期和最高气温
filename = 'sitka_weather_07-2014.csv'

with open(filename) as f:
    reader = csv.reader(f)
    header_row = next(reader)

    dates,highs = [],[]
    for row in reader:
        current_date = datetime.strptime(row[0], "%Y-%m-%d") 
        dates.append(current_date)

        high = int(row[1])
        highs.append(high)


#根据数据绘制图形
fig = plt.figure(dpi=128, figsize=(10, 6))
plt.plot(dates,highs, c='red')
# 设置图形的格式
plt.title("Daily high temperatures, July 2014", 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()
添加日期的图表

添加最低温度数据列表

➜ highs_lows.py
--snip--
#从文件中获取日期和最高气温和最低气温
filename = 'sitka_weather_2014.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[0], "%Y-%m-%d") 
        dates.append(current_date)

        high = int(row[1])
        highs.append(high)

        low = int(row[3])
        lows.append(low)

#根据数据绘制图形
fig = plt.figure(dpi=128, figsize=(10, 6))
plt.plot(dates,highs, c='red')
plt.plot(dates,lows, c='blue')
# 设置图形的格式
plt.title("Daily high temperatures, July 2014", fontsize=24)
--snip--
两条数据图表

给图表区域着色

--snip--
#根据数据绘制图形
fig = plt.figure(dpi=128, figsize=(10, 6))
plt.plot(dates, highs, c='red', alpha=0.5) 
plt.plot(dates, lows, c='blue', alpha=0.5)
plt.fill_between(dates, highs, lows, facecolor='blue', alpha=0.1)  #最高与最低温区间填充颜色
--snip--
最高温与最低温的区间着色图

错误检查

如果要调取的数据列表出现数据缺失会引发异常,所以要进行检查,下面引入缺失数据的death_valley_2014.csv文件

➜ highs_lows.py
--snip--
#从文件中获取日期和最高气温和最低气温
filename = 'death_valley_2014.csv'

with open(filename) as f:
--snip--

因为缺失数据,所以会出现下面的错误提示:

Traceback (most recent call last):
  File "/Users/qwe/Downloads/python/loading_data/day1/higt_low.py", line 22, in <module>
    high = int(row[1])
ValueError: invalid literal for int() with base 10: ''

该traceback指出,Python无法处理其中一天的最高气温,因为它无法将空字符串(' ' )转换为整数。只要看一下death_valley_2014.csv,就能发现其中的问题:

--snip--
#从文件中获取日期和最高气温和最低气温
filename = 'death_valley_2014.csv'

with open(filename) as f:
    reader = csv.reader(f)
    header_row = next(reader)

    dates,highs,lows = [],[],[]
    for row in reader:
❶       try:  #对于每一行,尝试从中提取日期、最高气温和最低气温
            current_date = datetime.strptime(row[0], "%Y-%m-%d") 
            high = int(row[1])
            low = int(row[3])
❷       except ValueError:   #只要缺失其中一项数据,Python就会引发ValueError 异常,而我们可打印一条错误消息, 指出缺失数据的日期
            print(current_date, 'missing data')
❸       else:
            dates.append(current_date)
            highs.append(high)
            lows.append(low)

#根据数据绘制图形
fig = plt.figure(dpi=128, figsize=(10, 6))
plt.plot(dates, highs, c='red', alpha=0.5) 
plt.plot(dates, lows, c='blue', alpha=0.5)
plt.fill_between(dates, highs, lows, facecolor='blue', alpha=0.1)
# 设置图形的格式
❹title = "Daily high and low temperatures - 2014\nDeath Valley, CA"
plt.title(title, fontsize=20)
--snip--

在❷处打印错误消息后,循环将接着处理下一行。如果获取特定日期的所有数据时没有发生错误,将运行else 代码块,并将数据附加到相应列表的末 尾(见❸)。鉴于我们绘图时使用的是有关另一个地方的信息,我们修改了标题,在图表中指出了这个地方(见❹)
缺失数据提示:

(datetime.datetime(2014, 2, 16, 0, 0), 'missing data')
过滤掉错误显示的图表

相关文章

网友评论

      本文标题:Python数据可视化day04|下载数据

      本文链接:https://www.haomeiwen.com/subject/omixlftx.html