gis可以导入csv格式数据_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文件, 本文末尾有下载链接

分析sitkaweather07-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()

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

ff6c95e385fbb22a9b6172a6b95d3943.png

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

分析sitkaweather2014.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()

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

7733ff7d8788b35c5d73e189a7a3994b.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

high = int(row[1])

ValueError: invalid literal for int() with base 10: ''

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

分析deathvalley2014.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()

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

5da39769186b186f9486dc2aa55ad917.png

deathvalley2014.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-1600:00:00错误数据, 不影响可视化图表的生成.

参考

代码:highslows.py

highslows2.py

highs_lows3.py

文件:sitkaweather07-2014.csv

sitkaweather2014.csv

deathvalley2014.csv

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值