日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > python >内容正文

python

数据分析CSV模块的基本使用(以分析复杂的天气情况为例),附完整的Python代码及csv文件详解---数据可视化

發布時間:2025/3/15 python 46 豆豆
生活随笔 收集整理的這篇文章主要介紹了 数据分析CSV模块的基本使用(以分析复杂的天气情况为例),附完整的Python代码及csv文件详解---数据可视化 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

目錄

    • 一、前提準備
    • 二、代碼解釋
      • 2.1分析CSV文件頭
      • 2.2提取并讀取數據
      • 2.3繪制氣溫圖表
      • 2.4在圖表中添加日期(datetime模塊)
        • 2.4.1書上源代碼
        • 2.4.2完善代碼
      • 2.5覆蓋更廣的時間
        • 2.5.1書上源代碼
        • 2.5.2完善代碼
      • 2.6再繪制一個數據系列--添加最低氣溫數據
        • 2.6.1添加最低氣溫數據
        • 2.6.2給圖表區域著色
      • 2.7錯誤檢查---異常處理

一、前提準備

建立一個文件夾,如圖所示,里面包含三個csv文件,我在百度網盤里面分享出來了,可以點擊下載

百度網盤:數據文件
鏈接:點擊此處
提取碼:cin1

二、代碼解釋

2.1分析CSV文件頭

header_row.py

# coding = utf-8import csv"""分析CSV文件頭"""filename = 'sitka_weather_07-2014.csv'# 打開這個文件,將文件對象存儲在f中 with open(filename) as f:# 創建一個與該文件相關聯的閱讀器reader = csv.reader(f)# 返回文件的下一行,前面的代碼中,我們只調用了next()一次,因此得到的是文件第一行header_row = next(reader)# 調用enumerate獲取每個元素的索引及其值for index, colum_header in enumerate(header_row):print(index, colum_header)

運行結果


注意:
AKDT=阿拉斯加時間(Alaska Daylight Time)

2.2提取并讀取數據

max_temperature.py

# coding = utf-8import csv"""提取并讀取數據:讀取每天的最高氣溫"""filename = 'sitka_weather_07-2014.csv'# 打開這個文件,將文件對象存儲在f中 with open(filename) as f:# 創建一個與該文件相關聯的閱讀器reader = csv.reader(f)# 返回文件的下一行,前面的代碼中,我們只調用了next()一次,因此得到的是文件第一行header_row = next(reader)# 創建一個為max_temperature的空列表max_temperature = []# 遍歷文件中余下的各行for row in reader:#每次執行該循環時,我們都將索引1(第二列)的數據附加到max_temperature的末尾max = int(row[1])max_temperature.append(max)print(max_temperature)

運行結果

2.3繪制氣溫圖表

temperature_chart.py

# coding = utf-8import csv from matplotlib import pyplot as plt"""提取并讀取數據:讀取每天的最高氣溫"""filename = 'sitka_weather_07-2014.csv'# 打開這個文件,將文件對象存儲在f中 with open(filename) as f:# 創建一個與該文件相關聯的閱讀器reader = csv.reader(f)# 返回文件的下一行,前面的代碼中,我們只調用了next()一次,因此得到的是文件第一行header_row = next(reader)# 創建一個為max_temperature的空列表max_temperature = []# 遍歷文件中余下的各行for row in reader:# 每次執行該循環時,我們都將索引1(第二列)的數據附加到max_temperature的末尾max = int(row[1])max_temperature.append(max)"""根據數據繪制圖形"""# dpi:每英寸的點數 figsize:寬高fig = plt.figure(dpi=100, figsize=(10, 6))# 將最高氣溫傳給plotplt.plot(max_temperature, c='blue')# 設置圖形的格式plt.title("Daily max temperature,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()

運行結果

2.4在圖表中添加日期(datetime模塊)

模塊datetime中設置日期和時間格式的參數(常用):點擊此處

2.4.1書上源代碼

chart_addtime.py

# coding = utf-8import csv from matplotlib import pyplot as plt from datetime import datetime"""提取并讀取數據:讀取每天的最高氣溫"""filename = 'sitka_weather_07-2014.csv'# 打開這個文件,將文件對象存儲在f中 with open(filename) as f:# 創建一個與該文件相關聯的閱讀器reader = csv.reader(f)# 返回文件的下一行,前面的代碼中,我們只調用了next()一次,因此得到的是文件第一行header_row = next(reader)# 創建兩個為dates和max_temperature的空列表,用來存儲從文件中提取的日期和最高氣溫dates, max_temperature = [], []# 遍歷文件中余下的各行for row in reader:current_date = datetime.strptime(row[0], "%Y-%m-%d")dates.append(current_date)# 每次執行該循環時,我們都將索引1(第二列)的數據附加到max_temperature的末尾max = int(row[1])max_temperature.append(max)"""根據數據繪制圖形"""# dpi:每英寸的點數 figsize:寬高fig = plt.figure(dpi=100, figsize=(10, 6))# 將日期和最高氣溫傳給plotplt.plot(dates, max_temperature, c='blue')# 設置圖形的格式plt.title("Daily max temperature,july 2014", fontsize=24)plt.xlabel('', fontsize=16)#使用autofmt_xdate來繪制傾斜的日期標簽,以免彼此重疊fig.autofmt_xdate()plt.ylabel('Temperature(F)', fontsize=16)plt.tick_params(axis='both', which='major', labelsize=16)plt.show()

運行結果

注意上面是書上的代碼運行之后的原圖

2.4.2完善代碼

我花了快一天的時間在網上查資料,咋改這東西才能跟書上的圖片一模一樣,運行書上的代碼,我真的醉了我去。以下是更改過后的代碼:

# coding = utf-8import csv from matplotlib import pyplot as plt from datetime import datetime from matplotlib import dates as mdates"""提取并讀取數據:獲取日期和最高氣溫"""filename = 'sitka_weather_07-2014.csv'# 打開這個文件,將文件對象存儲在f中 with open(filename) as f:# 創建一個與該文件相關聯的閱讀器reader = csv.reader(f)# 返回文件的下一行,前面的代碼中,我們只調用了next()一次,因此得到的是文件第一行header_row = next(reader)# 創建兩個為dates和max_temperature的空列表,用來存儲從文件中提取的日期和最高氣溫dates, max_temperature = [], []# 遍歷文件中余下的各行for row in reader:current_date = datetime.strptime(row[0], "%Y-%m-%d")dates.append(current_date)# 每次執行該循環時,我們都將索引1(第二列)的數據附加到max_temperature的末尾max = int(row[1])max_temperature.append(max)"""根據數據繪制圖形"""# dpi:每英寸的點數 figsize:寬高fig = plt.figure(dpi=100, figsize=(10, 6))# 將日期和最高氣溫傳給plotplt.plot(dates, max_temperature, c='red')# 設置圖形的格式plt.title("Daily max temperature,July 2014", fontsize=24)# 設置橫坐標日期的上下限plt.xlim([datetime(2014, 7, 1), datetime(2014, 7, 31)]) # 日期上下限plt.gca().xaxis.set_major_formatter(mdates.DateFormatter('%b %d %Y')) # 日期格式,%B為月份名,%b為月份名縮寫plt.gca().xaxis.set_major_locator(mdates.DayLocator(interval=3)) # 日期間隔plt.xlabel('', fontsize=16)# 使用autofmt_xdate來繪制傾斜的日期標簽,以免彼此重疊fig.autofmt_xdate()# 溫度上下限和間隔plt.yticks(range(54, 74, 2))plt.ylabel('Temperature(F)', fontsize=16)# pyplot模塊中的tick_params()方法可以修改坐標刻度,刻度標簽和網格線的外觀plt.tick_params(axis='both', which='major', direction='in', labelsize=16)plt.show()

運行結果

2.5覆蓋更廣的時間

2.5.1書上源代碼

這里只需要將表名filename改一下就行了,當然也可以更改一下標題,我這里還改了顏色為red
complete_chart.py

# coding = utf-8import csv from matplotlib import pyplot as plt from datetime import datetime"""提取并讀取數據:獲取日期和最高氣溫"""filename = 'sitka_weather_2014.csv'# 打開這個文件,將文件對象存儲在f中 with open(filename) as f:# 創建一個與該文件相關聯的閱讀器reader = csv.reader(f)# 返回文件的下一行,前面的代碼中,我們只調用了next()一次,因此得到的是文件第一行header_row = next(reader)# 創建兩個為dates和max_temperature的空列表,用來存儲從文件中提取的日期和最高氣溫dates, max_temperature = [], []# 遍歷文件中余下的各行for row in reader:current_date = datetime.strptime(row[0], "%Y-%m-%d")dates.append(current_date)# 每次執行該循環時,我們都將索引1(第二列)的數據附加到max_temperature的末尾max = int(row[1])max_temperature.append(max)"""根據數據繪制圖形"""# dpi:每英寸的點數 figsize:寬高fig = plt.figure(dpi=100, figsize=(10, 6))# 將日期和最高氣溫傳給plotplt.plot(dates, max_temperature, c='red')# 設置圖形的格式plt.title("Daily max temperature,--2014", fontsize=24)plt.xlabel('', fontsize=16)#使用autofmt_xdate來繪制傾斜的日期標簽,以免彼此重疊fig.autofmt_xdate()plt.ylabel('Temperature(F)', fontsize=16)plt.tick_params(axis='both', which='major', labelsize=16)plt.show()

運行結果

2.5.2完善代碼

# coding = utf-8import csv from matplotlib import pyplot as plt from datetime import datetime from matplotlib import dates as mdates"""提取并讀取數據:獲取日期和最高氣溫"""filename = 'sitka_weather_2014.csv'# 打開這個文件,將文件對象存儲在f中 with open(filename) as f:# 創建一個與該文件相關聯的閱讀器reader = csv.reader(f)# 返回文件的下一行,前面的代碼中,我們只調用了next()一次,因此得到的是文件第一行header_row = next(reader)# 創建兩個為dates和max_temperature的空列表,用來存儲從文件中提取的日期和最高氣溫dates, max_temperature = [], []# 遍歷文件中余下的各行for row in reader:current_date = datetime.strptime(row[0], "%Y-%m-%d")dates.append(current_date)# 每次執行該循環時,我們都將索引1(第二列)的數據附加到max_temperature的末尾max = int(row[1])max_temperature.append(max)"""根據數據繪制圖形"""# dpi:每英寸的點數 figsize:寬高fig = plt.figure(dpi=100, figsize=(10, 6))# 將日期和最高氣溫傳給plotplt.plot(dates, max_temperature, c='red')# 設置圖形的格式plt.title("Daily max temperature,2014", fontsize=24)# 設置橫坐標日期的上下限plt.xlim([datetime(2014, 1, 1), datetime(2014, 12, 22)]) # 日期上下限plt.gca().xaxis.set_major_formatter(mdates.DateFormatter('%b %Y')) # 日期格式,%B為月份名,%b為月份名縮寫plt.xlabel('', fontsize=16)# 使用autofmt_xdate來繪制傾斜的日期標簽,以免彼此重疊fig.autofmt_xdate()# 溫度上下限和間隔plt.yticks(range(20, 80, 5))plt.ylabel('Temperature(F)', fontsize=16)# pyplot模塊中的tick_params()方法可以修改坐標刻度,刻度標簽和網格線的外觀plt.tick_params(axis='both', which='major', direction='in', labelsize=16)plt.show()

運行結果

2.6再繪制一個數據系列–添加最低氣溫數據

2.6.1添加最低氣溫數據

high_low_chart.py

# coding = utf-8import csv from matplotlib import pyplot as plt from datetime import datetime from matplotlib import dates as mdates"""提取并讀取數據:獲取日期和最高氣溫和最低氣溫"""filename = 'sitka_weather_2014.csv'# 打開這個文件,將文件對象存儲在f中 with open(filename) as f:# 創建一個與該文件相關聯的閱讀器reader = csv.reader(f)# 返回文件的下一行,前面的代碼中,我們只調用了next()一次,因此得到的是文件第一行header_row = next(reader)# 創建兩個為dates和max_temperature的空列表,用來存儲從文件中提取的日期和最高氣溫dates, max_temperature, min_temperature = [], [], []# 遍歷文件中余下的各行for row in reader:current_date = datetime.strptime(row[0], "%Y-%m-%d")dates.append(current_date)# 每次執行該循環時,我們都將索引1(第二列)的數據附加到max_temperature的末尾max = int(row[1])max_temperature.append(max)min = int(row[3])min_temperature.append(min)"""根據數據繪制圖形"""# dpi:每英寸的點數 figsize:寬高fig = plt.figure(dpi=100, figsize=(10, 6))# 將日期和最高氣溫傳給plotplt.plot(dates, max_temperature, c='red')plt.plot(dates, min_temperature, c='green')# 設置圖形的格式plt.title("Daily max temperature and min temperature,2014", fontsize=24)# 設置橫坐標日期的上下限plt.xlim([datetime(2014, 1, 1), datetime(2014, 12, 22)]) # 日期上下限plt.gca().xaxis.set_major_formatter(mdates.DateFormatter('%b %Y')) # 日期格式,%B為月份名,%b為月份名縮寫plt.xlabel('', fontsize=16)# 使用autofmt_xdate來繪制傾斜的日期標簽,以免彼此重疊fig.autofmt_xdate()# 溫度上下限和間隔plt.yticks(range(20, 80, 5))plt.ylabel('Temperature(F)', fontsize=16)# pyplot模塊中的tick_params()方法可以修改坐標刻度,刻度標簽和網格線的外觀plt.tick_params(axis='both', which='major', direction='in', labelsize=16)plt.show()

運行結果

2.6.2給圖表區域著色

high_low_chart.py

# coding = utf-8import csv from matplotlib import pyplot as plt from datetime import datetime from matplotlib import dates as mdates"""提取并讀取數據:獲取日期和最高氣溫和最低氣溫"""filename = 'sitka_weather_2014.csv'# 打開這個文件,將文件對象存儲在f中 with open(filename) as f:# 創建一個與該文件相關聯的閱讀器reader = csv.reader(f)# 返回文件的下一行,前面的代碼中,我們只調用了next()一次,因此得到的是文件第一行header_row = next(reader)# 創建兩個為dates和max_temperature的空列表,用來存儲從文件中提取的日期和最高氣溫dates, max_temperature, min_temperature = [], [], []# 遍歷文件中余下的各行for row in reader:current_date = datetime.strptime(row[0], "%Y-%m-%d")dates.append(current_date)# 每次執行該循環時,我們都將索引1(第二列)的數據附加到max_temperature的末尾max = int(row[1])max_temperature.append(max)min = int(row[3])min_temperature.append(min)"""根據數據繪制圖形"""# dpi:每英寸的點數 figsize:寬高fig = plt.figure(dpi=100, figsize=(10, 6))# 將日期和最高氣溫傳給plotplt.plot(dates, max_temperature, c='red', alpha=0.5)plt.plot(dates, min_temperature, c='green', alpha=0.5)#中間傳紅色哈哈哈哈plt.fill_between(dates, max_temperature, min_temperature, facecolor='pink', alpha=0.8)# 設置圖形的格式plt.title("Daily max temperature and min temperature,2014", fontsize=24)# 設置橫坐標日期的上下限plt.xlim([datetime(2014, 1, 1), datetime(2014, 12, 22)]) # 日期上下限plt.gca().xaxis.set_major_formatter(mdates.DateFormatter('%b %Y')) # 日期格式,%B為月份名,%b為月份名縮寫plt.xlabel('', fontsize=16)# 使用autofmt_xdate來繪制傾斜的日期標簽,以免彼此重疊fig.autofmt_xdate()# 溫度上下限和間隔plt.yticks(range(20, 80, 5))plt.ylabel('Temperature(F)', fontsize=16)# pyplot模塊中的tick_params()方法可以修改坐標刻度,刻度標簽和網格線的外觀plt.tick_params(axis='both', which='major', direction='in', labelsize=16)plt.show()

運行結果

2.7錯誤檢查—異常處理

將high_low_chart.py的第十行filename改為death_valley_2014.csv,如
運行的時候就會報錯:

Traceback (most recent call last):File "F:/Z/Python/project/project2/csva/high_low_chart.py", line 28, in <module>max = int(row[1]) ValueError: invalid literal for int() with base 10: ''

如圖:

報錯原因:ValueError:基為10的int()的文本無效:“” ,說明death_valley_2014.csv文件中存在空字符串
death_valley_2014.csv中發現2014-2-16這一天

因此,我們就需要進行異常處理
異常處理

# coding = utf-8import csv from matplotlib import pyplot as plt from datetime import datetime from matplotlib import dates as mdates"""提取并讀取數據:獲取日期和最高氣溫和最低氣溫,異常處理"""filename = 'death_valley_2014.csv'# 打開這個文件,將文件對象存儲在f中 with open(filename) as f:# 創建一個與該文件相關聯的閱讀器reader = csv.reader(f)# 返回文件的下一行,前面的代碼中,我們只調用了next()一次,因此得到的是文件第一行header_row = next(reader)# 創建兩個為dates和max_temperature的空列表,用來存儲從文件中提取的日期和最高氣溫dates, max_temperature, min_temperature = [], [], []# 遍歷文件中余下的各行for row in reader:try:current_date = datetime.strptime(row[0], "%Y-%m-%d")max = int(row[1])min = int(row[3])except ValueError:print(current_date, 'missing data')else:dates.append(current_date)max_temperature.append(max)min_temperature.append(min)"""根據數據繪制圖形"""# dpi:每英寸的點數 figsize:寬高fig = plt.figure(dpi=100, figsize=(10, 6))# 將日期和最高氣溫傳給plotplt.plot(dates, max_temperature, c='red', alpha=0.5)plt.plot(dates, min_temperature, c='green', alpha=0.5)#中間傳紅色哈哈哈哈plt.fill_between(dates, max_temperature, min_temperature, facecolor='pink', alpha=0.8)# 設置圖形的格式plt.title("Daily max temperature and min temperature,2014", fontsize=24)# 設置橫坐標日期的上下限plt.xlim([datetime(2014, 1, 1), datetime(2014, 12, 22)]) # 日期上下限plt.gca().xaxis.set_major_formatter(mdates.DateFormatter('%b %Y')) # 日期格式,%B為月份名,%b為月份名縮寫plt.xlabel('', fontsize=16)# 使用autofmt_xdate來繪制傾斜的日期標簽,以免彼此重疊fig.autofmt_xdate()# 溫度上下限和間隔plt.yticks(range(20, 80, 5))plt.ylabel('Temperature(F)', fontsize=16)# pyplot模塊中的tick_params()方法可以修改坐標刻度,刻度標簽和網格線的外觀plt.tick_params(axis='both', which='major', direction='in', labelsize=16)plt.show()

運行結果


學習《python編程從入門到實戰》16章第一節,通過敲這些代碼,發現一句真理:實踐是檢驗真理的唯一標準!
書上的源碼有些不足,我以為是我哪里代碼打錯了,檢查了不下三遍,也可真夠有耐煩心的,完善代碼給整了一天,不過這也鍛煉了自己的能力哈哈哈哈!

以上就是全部內容啦,如果有不懂的小伙伴歡迎提出來傲!

總結

以上是生活随笔為你收集整理的数据分析CSV模块的基本使用(以分析复杂的天气情况为例),附完整的Python代码及csv文件详解---数据可视化的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。