14. Python3 使用csv模块处理CSV(逗号分割的值)格式存储的天气数据

CSV文件格式

CSV文件格式是逗号分隔值(Comma-Separated Values,CSV,有时也称为字符分隔值,因为分隔字符也可以不是逗号),其文件以纯文本形式存储表格数据(数字和文本).

datetime模块

因为csv格式文件中含有日期格式, 我们使用datetime模块来解析.

datetime模块中strptime函数可根据接受的实参规则来解析日期

from datetime import datetime

first_date = datetime.strptime('2020-10-22 18:32:30', '%Y-%m-%d %H:%M:%S')
print(first_date)

测试结果:

2020-10-22 18:32:30

模块datetime中设置日期和时间格式的实参

实参含义
%A星期的名称, 如Monday
%B月份名, 如January
%m用数字表示的月份(01~12)
%d用数字表示月份中的一天(01~31)
%Y四位年份, 如2020
%y两位年份, 如20
%H24小时制的小时数(00~23)
%I12小时制的小时数(01~12)
%pam或pm
%M分钟数(00~59)
%S秒数(00~60)

使用csv模块处理文件

代码中使用到csv文件, 本文末尾有下载链接

分析sitka_weather_07-2014.csv文件

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)
	# next(reader)函数是返回reader阅读器的下一行,目前只调用了一次,所以是头行
	header_row = next(reader)
	# 打印头行,header_row它是一个列表
	# print(header_row)
	# enumerate() 获取每个元素的索引及其值
	for index, column_header in enumerate(header_row):
		print(index, column_header)

	# 第二列每天的最高温度
	dates, highs = [], []
	for row in reader:
		current_date = datetime.strptime(row[0], '%Y-%m-%d')
		print(current_date)
		dates.append(current_date)
		high = int(row[1])
		highs.append(high)

	print(dates)
	print(highs)

	# 根据数据绘制图形
	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()

提取文件的数据生成可视化图表:

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-f1oXQVhN-1637590864049)(/upload/2020/10/image-6d8db87a134d4af689b835f8c3d06672.png)]

上面是一个月的天气数据分析, 下面试着分析更复杂的天气图

分析sitka_weather_2014.csv

highs_lows2.py

import csv
from datetime import datetime

from matplotlib import pyplot as plt

# 从文件中获取每天的最高温度
filename = 'sitka_weather_2014.csv'
with open(filename) as f:
	reader = csv.reader(f)
	# next(reader)函数是返回reader阅读器的下一行,目前只调用了一次,所以是头行
	header_row = next(reader)
	# 打印头行,header_row它是一个列表
	# print(header_row)
	# enumerate() 获取每个元素的索引及其值
	for index, column_header in enumerate(header_row):
		print(index, column_header)

	# 第二列每天的最高温度
	dates, highs, lows = [], [], []
	for row in reader:
		current_date = datetime.strptime(row[0], '%Y-%m-%d')
		print(current_date)
		dates.append(current_date)

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

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

	print(dates)
	print(highs)

	# 根据数据绘制图形
	fig = plt.figure(dpi=128, figsize=(10, 6))
	plt.plot(dates, highs, c='red')
	plt.plot(dates, lows, c='blue')

	# facecolor指定填充区域的颜色
	plt.fill_between(dates, highs, lows, facecolor='blue', alpha=0.1)
	# 设置图形的格式
	plt.title("Daily high and low temperatures - 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()

提取文件的数据生成可视化图表:

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-AFSONekS-1637590864051)(/upload/2020/10/image-79913eaf9da643efbc0093b7136ffe20.png)]

在上面代码中, 有一处代码high = int(row[1])
当row[1]所在位置是没有数据时或者数据类型不对, 当使用int()转换就会报ValueError, 如下面这种报错.

Traceback (most recent call last):
  File "/Users/wushanghui/Documents/code/codechina/python3-learn/csv/highs_lows3.py", line 25, in <module>
    high = int(row[1])
ValueError: invalid literal for int() with base 10: ''

下面看怎么避免这种问题.

分析death_valley_2014.csv

highs_lows3.py

import csv
from datetime import datetime

from matplotlib import pyplot as plt

# 从文件中获取每天的最高温度
filename = 'death_valley_2014.csv'
with open(filename) as f:
	reader = csv.reader(f)
	# next(reader)函数是返回reader阅读器的下一行,目前只调用了一次,所以是头行
	header_row = next(reader)
	# 打印头行,header_row它是一个列表
	# print(header_row)
	# enumerate() 获取每个元素的索引及其值
	for index, column_header in enumerate(header_row):
		print(index, column_header)

	# 第二列每天的最高温度
	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:
			print(current_date, '错误数据')
		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')
	plt.plot(dates, lows, c='blue')

	# facecolor指定填充区域的颜色
	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)
	plt.xlabel("", fontsize=16)
	# 绘制斜的日期标签
	fig.autofmt_xdate()
	plt.ylabel("Temperature (F)", fontsize=16)
	plt.tick_params(axis='both', which='major', labelsize=16)

	plt.show()

提取文件的数据生成可视化图表:
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-a3GCNhgQ-1637590864053)(/upload/2020/10/image-da41db533c474bf4b2b6b9f790785d3e.png)]

death_valley_2014.csv 这个文件中有一行数据是2014-2-16,,,,,,,,,,,,,,,,,,,0.00,,,-1
如果不进行错误检查会报错, 代码中我们使用try-except-else来处理了这种问题:

try:
    current_date = datetime.strptime(row[0], '%Y-%m-%d')
    high = int(row[1])
    low = int(row[3])
except ValueError:
    print(current_date, '错误数据')
else:
    dates.append(current_date)
    highs.append(high)
    lows.append(low)

只会在控制台打印2014-02-16 00:00:00 错误数据, 不影响可视化图表的生成.

参考

代码:
highs_lows.py
highs_lows2.py
highs_lows3.py

文件:
sitka_weather_07-2014.csv
sitka_weather_2014.csv
death_valley_2014.csv


Python3 目录

  1. Python3 教程
  2. Python3 变量和简单数据类型
  3. Python3 列表
  4. Python3 操作列表
  5. Python3 if 语句
  6. Python3 if 字典
  7. Python3 用户输入和while循环
  8. Python3 函数
  9. Python3 类
  10. Python3 文件和异常
  11. Python3 测试代码
  12. Python3 使用matplotlib绘制图表
  13. Python3 使用Pygal生成矢量图形文件
  14. Python3 使用csv模块处理CSV(逗号分割的值)格式存储的天气数据
  15. Python3 处理JSON格式数据(制作交易收盘价走势图)
  16. Python3 使用API
  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值