Python讀取CSV文件并進(jìn)行數(shù)據(jù)可視化繪圖
介紹:文件 sitka_weather_07-2018_simple.csv是阿拉斯加州錫特卡2018年1月1日的天氣數(shù)據(jù),其中包含當(dāng)天的最高溫度和最低溫度。數(shù)據(jù)文件存儲(chǔ)與data文件夾下,接下來用Python讀取該文件數(shù)據(jù),再基于數(shù)據(jù)進(jìn)行可視化繪圖。(詳細(xì)細(xì)節(jié)請看代碼注釋)
sitka_highs.py
import csv # 導(dǎo)入csv模塊
from datetime import datetime
import matplotlib.pyplot as plt
filename = 'data/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): # 對列表調(diào)用了 enumerate()來獲取每個(gè)元素的索引及其值,方便我們提取需要的數(shù)據(jù)列
# print(index, column_header)
# 從文件中獲取最高溫度
dates, highs = [], []
for row in reader:
current_date = datetime.strptime(row[2], '%Y-%m-%d')
high = int(row[5])
dates.append(current_date)
highs.append(high)
# 根據(jù)最高溫度繪制圖形
plt.style.use('seaborn')
fig, ax = plt.subplots()
ax.plot(dates, highs, c='red')
# 設(shè)置圖形的格式
ax.set_title("2018年7月每日最高溫度", fontproperties="SimHei", fontsize=24)
ax.set_xlabel('', fontproperties="SimHei", fontsize=16)
fig.autofmt_xdate()
ax.set_ylabel("溫度(F)", fontproperties="SimHei", fontsize=16)
ax.tick_params(axis='both', which='major', labelsize=16)
plt.show()運(yùn)行結(jié)果如下:

設(shè)置以上圖標(biāo)后,我們來添加更多的數(shù)據(jù),生成一副更復(fù)雜的錫特卡天氣圖。將sitka_weather_2018_simple.csv數(shù)據(jù)文件置于data文件夾下,該文件包含整年的錫特卡天氣數(shù)據(jù)。
對代碼進(jìn)行修改:
sitka_highs.py
import csv # 導(dǎo)入csv模塊
from datetime import datetime
import matplotlib.pyplot as plt
filename = 'data/sitka_weather_2018_simple.csv'
with open(filename) as f:
reader = csv.reader(f)
header_row = next(reader) # 返回文件的下一行,在這便是首行,即文件頭
# for index, column_header in enumerate(header_row): # 對列表調(diào)用了 enumerate()來獲取每個(gè)元素的索引及其值,方便我們提取需要的數(shù)據(jù)列
# print(index, column_header)
# 從文件中獲取最高溫度
dates, highs = [], []
for row in reader:
current_date = datetime.strptime(row[2], '%Y-%m-%d')
high = int(row[5])
dates.append(current_date)
highs.append(high)
# 根據(jù)最高溫度繪制圖形
plt.style.use('seaborn')
fig, ax = plt.subplots()
ax.plot(dates, highs, c='red')
# 設(shè)置圖形的格式
ax.set_title("2018年每日最高溫度", fontproperties="SimHei", fontsize=24)
ax.set_xlabel('', fontproperties="SimHei", fontsize=16)
fig.autofmt_xdate()
ax.set_ylabel("溫度(F)", fontproperties="SimHei", fontsize=16)
ax.tick_params(axis='both', which='major', labelsize=16)
plt.show()運(yùn)行結(jié)果如下:

代碼再改進(jìn):雖然上圖已經(jīng)顯示了豐富的數(shù)據(jù),但是還能再添加最低溫度數(shù)據(jù),使其更有用
對代碼進(jìn)行修改:
sitka_highs_lows.py
import csv # 導(dǎo)入csv模塊
from datetime import datetime
import matplotlib.pyplot as plt
filename = 'data/sitka_weather_2018_simple.csv'
with open(filename) as f:
reader = csv.reader(f)
header_row = next(reader) # 返回文件的下一行,在這便是首行,即文件頭
# for index, column_header in enumerate(header_row): # 對列表調(diào)用了 enumerate()來獲取每個(gè)元素的索引及其值,方便我們提取需要的數(shù)據(jù)列
# print(index, column_header)
# 從文件中獲取日期、最高溫度和最低溫度
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)
# 根據(jù)最高溫度和最低溫度繪制圖形
plt.style.use('seaborn')
fig, ax = plt.subplots()
ax.plot(dates, highs, c='red', alpha=0.5) # alpha指定顏色的透明度,0為完全透明
ax.plot(dates, lows, c='blue', alpha=0.5)
ax.fill_between(dates, highs, lows, facecolor='blue',alpha=0.1)
# 設(shè)置圖形的格式
ax.set_title("2018年每日最高溫度", fontproperties="SimHei", fontsize=24)
ax.set_xlabel('', fontproperties="SimHei", fontsize=16)
fig.autofmt_xdate()
ax.set_ylabel("溫度(F)", fontproperties="SimHei", fontsize=16)
ax.tick_params(axis='both', which='major', labelsize=16)
plt.show()運(yùn)行結(jié)果如下:

此外,讀取CSV文件過程中,數(shù)據(jù)可能缺失,程序運(yùn)行時(shí)就會(huì)報(bào)錯(cuò)甚至崩潰。所有需要在從CSV文件中讀取值時(shí)執(zhí)行錯(cuò)誤檢查代碼,對可能的異常進(jìn)行處理,更換數(shù)據(jù)文件為:death_valley_2018_simple.csv ,該文件有缺失值。

對代碼進(jìn)行修改:
death_valley_highs_lows.py
import csv # 導(dǎo)入csv模塊
from datetime import datetime
import matplotlib.pyplot as plt
filename = 'data/death_valley_2018_simple.csv'
with open(filename) as f:
reader = csv.reader(f)
header_row = next(reader) # 返回文件的下一行,在這便是首行,即文件頭
# for index, column_header in enumerate(header_row): # 對列表調(diào)用了 enumerate()來獲取每個(gè)元素的索引及其值,方便我們提取需要的數(shù)據(jù)列
# print(index, column_header)
# 從文件中獲取日期、最高溫度和最低溫度
dates, highs, lows = [], [], []
for row in reader:
current_date = datetime.strptime(row[2], '%Y-%m-%d')
try:
high = int(row[5])
low = int(row[6])
except ValueError:
print(f"Missing data for {current_date}")
else:
dates.append(current_date)
highs.append(high)
lows.append(low)
# 根據(jù)最高溫度和最低溫度繪制圖形
plt.style.use('seaborn')
fig, ax = plt.subplots()
ax.plot(dates, highs, c='red', alpha=0.5) # alpha指定顏色的透明度,0為完全透明
ax.plot(dates, lows, c='blue', alpha=0.5)
ax.fill_between(dates, highs, lows, facecolor='blue',alpha=0.1)
# 設(shè)置圖形的格式
ax.set_title("2018年每日最高溫度和最低氣溫\n美國加利福利亞死亡谷", fontproperties="SimHei", fontsize=24)
ax.set_xlabel('', fontproperties="SimHei", fontsize=16)
fig.autofmt_xdate()
ax.set_ylabel("溫度(F)", fontproperties="SimHei", fontsize=16)
ax.tick_params(axis='both', which='major', labelsize=16)
plt.show()如果現(xiàn)在運(yùn)行 death_valley_highs_lows.py,將會(huì)發(fā)現(xiàn)缺失數(shù)據(jù)的日期只有一個(gè):
Missing data for 2018-02-18 00:00:00
妥善地處理錯(cuò)誤后,代碼能夠生成圖形并忽略缺失數(shù)據(jù)的那天。運(yùn)行結(jié)果如下:

到此這篇關(guān)于Python讀取CSV文件并進(jìn)行數(shù)據(jù)可視化繪圖的文章就介紹到這了,更多相關(guān)Python讀取CSV內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
- Python操作csv文件之csv.writer()和csv.DictWriter()方法的基本使用
- Python Pandas讀寫txt和csv文件的方法詳解
- Python 修改CSV文件實(shí)例詳解
- python讀取和保存為excel、csv、txt文件及對DataFrame文件的基本操作指南
- 利用python合并csv文件的方式實(shí)例
- Python中CSV文件(逗號(hào)分割)實(shí)戰(zhàn)操作指南
- python用pd.read_csv()方法來讀取csv文件的實(shí)現(xiàn)
- Python如何讀取csv文件時(shí)添加表頭/列名
- Python 比較兩個(gè) CSV 文件的三種方法并打印出差異
相關(guān)文章
如何利用python多線程爬取天氣網(wǎng)站圖片并保存
最近做個(gè)天 氣方面的APP需要用到一些天氣數(shù)據(jù),所以下面這篇文章主要給大家介紹了關(guān)于如何利用python多線程爬取天氣網(wǎng)站圖片并保存的相關(guān)資料,文中通過示例代碼介紹的非常詳細(xì),需要的朋友可以參考下2021-11-11
使用python求解迷宮問題的三種實(shí)現(xiàn)方法
關(guān)于迷宮問題,常見會(huì)問能不能到達(dá)某點(diǎn),以及打印到達(dá)的最短路徑,下面這篇文章主要給大家介紹了關(guān)于如何使用python求解迷宮問題的三種實(shí)現(xiàn)方法,需要的朋友可以參考下2022-03-03
查看TensorFlow checkpoint文件中的變量名和對應(yīng)值方法
今天小編就為大家分享一篇查看TensorFlow checkpoint文件中的變量名和對應(yīng)值方法,具有很好的參考價(jià)值,希望對大家有所幫助。一起跟隨小編過來看看吧2018-06-06
python實(shí)現(xiàn)kmp算法的實(shí)例代碼
這篇文章主要介紹了python實(shí)現(xiàn)kmp算法的實(shí)例代碼,非常不錯(cuò),具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2019-04-04
Python爬蟲beautifulsoup4常用的解析方法總結(jié)
今天小編就為大家分享一篇關(guān)于Python爬蟲beautifulsoup4常用的解析方法總結(jié),小編覺得內(nèi)容挺不錯(cuò)的,現(xiàn)在分享給大家,具有很好的參考價(jià)值,需要的朋友一起跟隨小編來看看吧2019-02-02
如何在Python?中使用?Luhn?算法驗(yàn)證數(shù)字
Luhn 算法驗(yàn)證器有助于檢查合法數(shù)字并將其與不正確或拼寫錯(cuò)誤的輸入分開,這篇文章主要介紹了在Python中使用Luhn算法驗(yàn)證數(shù)字,需要的朋友可以參考下2023-06-06

