CSV格式文件處理實例——某地氣溫變化折線圖


1、CSV文件是什么,以及與.XLS文件的區別?

csv是文本文件,用記事本就能打開,XLS是二進制的文件只有用EXCEL才能打
csv文件是以逗號為分隔符號,將各字段列分離出的一種ASCII文件。
csv(*.csv) 文件格式只能保存活動工作表中的單元格所顯示的文本和數值。工作表中所有的數據行和字符都將保存。
數據列以逗號分隔,每一行數據都以回車符結束。如果單元格中包含逗號,則該單元格中的內容以雙引號引起。

2、CSV文件常用的處理方法

1)通過調用csv.reader(),可以創建1個閱讀器對象

2)enumerate(),可以獲取每個元素的索引及其值

3)可以通過for循環遍歷閱讀器的各行

filename = '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):
        print (index, column_header)

    dates, lows, highs = [], [], []
    for row in reader:

3、strptime解讀日期

2018-02-18可以通過如下函數解讀

datetime.strptime('2018-02-18', '%Y-%m-%d')

4、折線圖繪制

1)首先繪制畫布

2)其次繪制折線以及描繪中間區域

3)再次設置坐標軸等格式

4)最后展示

notes:需要注意的是兩個函數

1)plt.fill_between()描繪兩個函數之間的中間區域

2)fig.autofmt_xdate()設置X軸坐標的樣式

 

    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)
    plt.fill_between(dates, highs, lows, facecolor='blue', alpha=0.1)

    plt.title('Daily high temperatures, July 2014', fontsize=24)
    plt.xlabel('', fontsize=16)
    plt.ylabel('Temperature (F)', fontsize=16)
    fig.autofmt_xdate()
    plt.tick_params(axis='both', which='major', labelsize=16)

    plt.show()

 5、最后附上整段代碼

 1 from matplotlib import pyplot as plt
 2 from datetime import datetime
 3 import csv
 4 
 5 
 6 filename = 'death_valley_2018_simple.csv'
 7 with open(filename) as f:
 8     reader = csv.reader(f)
 9     header_row = next(reader)
10 
11     for index, column_header in enumerate(header_row):
12         print (index, column_header)
13 
14     dates, lows, highs = [], [], []
15     for row in reader:
16         try:
17             current_date = datetime.strptime(row[2], '%Y-%m-%d')
18             high = int(row[4])
19             low = int(row[5])
20         except ValueError:
21             print(row[2])
22             print(current_date, 'missing date')
23         else:
24             dates.append(current_date)
25             highs.append(high)
26             lows.append(low)
27 
28     fig = plt.figure(dpi=128, figsize=(10, 6))
29     plt.plot(dates, highs, c='red', alpha=0.5)
30     plt.plot(dates, lows, c='blue', alpha=0.5)
31     plt.fill_between(dates, highs, lows, facecolor='blue', alpha=0.1)
32 
33     plt.title('Daily high temperatures, July 2014', fontsize=24)
34     plt.xlabel('', fontsize=16)
35     plt.ylabel('Temperature (F)', fontsize=16)
36     fig.autofmt_xdate()
37     plt.tick_params(axis='both', which='major', labelsize=16)
38 
39     plt.show()

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM