1. 程式人生 > >《Python程式設計從入門到實踐》記錄之Python處理CSV檔案資料

《Python程式設計從入門到實踐》記錄之Python處理CSV檔案資料

目錄

1、分析CSV檔案(reader()函式、next()函式)

2、列印檔案頭及其位置

3、提取並讀取、顯示資料

4、在圖表中新增日期(datetime模組)


csv模組包含在Python標準庫中,可用於分析CSV檔案中的資料行。

1、分析CSV檔案(reader()函式、next()函式)

#!/usr/bin/env python
# -*- coding:utf-8 -*-
import csv  # 匯入CSV模組
from datetime import datetime

from matplotlib import pyplot as plt

# Get dates, high, and low temperatures from file.
filename = 'sitka_weather_07-2014.csv'
with open(filename) as f:
    reader = csv.reader(f)
    header_row = next(reader)
    print(header_row)

程式碼解析:

  • csv.reader()函式,建立一個與該檔案關聯的閱讀器物件。
  • CSV模組包含函式next(),返回檔案中的下一行,上述程式碼只調用了一次next(),得到檔案的第一行。
  • 將reader返回的資料儲存在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']

2、列印檔案頭及其位置

為了讓檔案頭資料更容易理解,將列表中的每個標頭檔案及其位置打印出來:

#!/usr/bin/env python
# -*- coding:utf-8 -*-
import csv
from datetime import datetime

from matplotlib import pyplot as plt

# Get dates, high, and low temperatures from file.
filename = 'sitka_weather_07-2014.csv'
with open(filename) as f:
    reader = csv.reader(f)
    header_row = next(reader)

    for index, colum_header in enumerate(header_row):
        print(index, colum_header)

程式碼解析:

對列表header_row呼叫了enumerate來獲取每個元素的索引及其值

執行結果:

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

3、提取並讀取、顯示資料

知道資料的位置後,我們來讀取每天的最高氣溫:

#!/usr/bin/env python
# -*- coding:utf-8 -*-
import csv
from datetime import datetime

from matplotlib import pyplot as plt

# Get dates, high, and low temperatures from file.
filename = 'sitka_weather_07-2014.csv'
with open(filename) as f:
    reader = csv.reader(f)
    header_row = next(reader)

    # 讀取資料
    highs = []
    for row in reader:
        high = int(row[1])  # 轉換為數值
        highs.append(high)

    print(highs)

    # 繪製氣溫圖表
    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()

執行結果:

[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]


4、在圖表中新增日期(datetime模組)

在獲取該資料時,獲得的是一個字串,所以我們需要將字串‘2014-7-1’轉換為一個表示相應日期的物件。這就會用到模組datetime中的方法strptime。

strptime需要兩個引數:(1)需要轉換為日期的字串;(2)設定日期的格式。

strptime()可以接受各種實參來設定日期格式,下表給出其中一些實參:

實參 含義
%A 興趣的名稱,如Monday
%B 月分名,如January
%m 用數字表示的月份名(01~12)
%d 用數字表示月份中的一天(01~31)
%Y 四位的年份,如2015
%y 兩位的年份,如15
%H 24小時制的小數(00~23)
%I 12小時制的小數(01~12)
%p am或pm
%M 分鐘數(00~59)
%S 秒數(00~59)

下述程式碼為圖表新增日期:

#!/usr/bin/env python
# -*- coding:utf-8 -*-
import csv
from datetime import datetime

from matplotlib import pyplot as plt

# Get dates, high, and low temperatures from file.
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_data = datetime.strptime(row[0], "%Y-%m-%d")
        dates.append(current_data)
        # 讀取最高溫資料
        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()

執行結果: 


下邊繪製一個整年的天氣資料圖:

#!/usr/bin/env python
# -*- coding:utf-8 -*-
import csv
from datetime import datetime

from matplotlib import pyplot as plt

# Get dates, high, and low temperatures from file.
filename = 'sitka_weather_2014.csv'
with open(filename) as f:
    reader = csv.reader(f)
    header_row = next(reader)

    # 讀取資料,獲取日期和最高氣溫

    dates, highs = [], []  # 兩個空列表,用於儲存日期和最高溫氣溫
    for row in reader:
        # 讀取日期資料
        current_data = datetime.strptime(row[0], "%Y-%m-%d")
        dates.append(current_data)
        # 讀取最高溫資料
        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()

執行結果:


下邊繪製一個最高氣溫和最低氣溫資料,並給區域著色: 

#!/usr/bin/env python
# -*- coding:utf-8 -*-
import csv
from datetime import datetime

from matplotlib import pyplot as plt

# Get dates, high, and low temperatures from file.
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:
        try:
            current_date = datetime.strptime(row[0], "%Y-%m-%d")
            high = int(row[1])
            low = int(row[3])
        except ValueError:
            print(current_date, 'missing data')
        else:
            dates.append(current_date)
            highs.append(high)
            lows.append(low)

# Plot data.
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)
# 區域著色,facecolor為填充顏色,alpha透明度
plt.fill_between(dates, highs, lows, facecolor='blue', alpha=0.1)

# Format plot.
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()

執行結果: