学习csv
1.csv文件讀取,csv文件是常用的數(shù)據(jù)存儲(chǔ)格式之一,我們使用Python模塊來(lái)處理csv文件,這是一個(gè)天氣信息表
import csv from matplotlib import pyplot as pltfilename = 'sitka_weather_07-2014.csv' with open(filename) as f:#從文件獲取數(shù)據(jù)reader = csv.reader(f)#獲取數(shù)據(jù)的第一行也就是數(shù)據(jù)字段header_row = next(reader)#print(header_row)#遍歷讀取到的第一行數(shù)據(jù)使用enumerate函數(shù)來(lái)獲取每個(gè)元素的索引和值# for index ,column_header in enumerate(header_row):# print(index,column_header) highs=[]#從文件獲取到最高氣溫for row in reader:highs.append(int(row[1]))print(highs)fig = plt.figure(dpi=128, figsize=(10, 6))plt.plot(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) title = "Daily high and low temperatures 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()除了這樣顯示,我們還可以讀取時(shí)間數(shù)據(jù)顯示在x軸上,添加datetime模塊
from datetime import datetime
讀取時(shí)間數(shù)據(jù)
filename = 'sitka_weather_07-2014.csv' with open(filename) as f:#從文件獲取數(shù)據(jù)reader = csv.reader(f)#獲取數(shù)據(jù)的第一行也就是數(shù)據(jù)字段header_row = next(reader)#print(header_row)#遍歷讀取到的第一行數(shù)據(jù)使用enumerate函數(shù)來(lái)獲取每個(gè)元素的索引和值# for index ,column_header in enumerate(header_row):# print(index,column_header) highs,dates=[],[]#從文件獲取到最高氣溫for row in reader:#從文件獲取日期current_date=datetime.strptime(row[0],"%Y-%m-%d")dates.append(current_date)highs.append(int(row[1]))print(highs,dates)fig = plt.figure(dpi=128, figsize=(5, 4))#添加日期plt.plot(dates,highs, c='red', alpha=0.5)圖中是一個(gè)月的天氣溫度情況
當(dāng)然還可以讀取整年的天氣情況,只要有足夠的數(shù)據(jù)
2.繪制一個(gè)數(shù)據(jù)系列,對(duì)比全年每個(gè)月的最高氣溫和最低氣溫
import csv from datetime import datetimefrom matplotlib import pyplot as pltfilename = 'death_valley_2014.csv' with open(filename) as f:reader = csv.reader(f)header_row = next(reader)dates, highs, lows = [], [], []for row in reader:#判斷是否有時(shí)間信息try:current_date = datetime.strptime(row[0], "%Y-%m-%d")high = int(row[1])#讀取最低溫?cái)?shù)據(jù)low = int(row[3])except ValueError:print(current_date, 'missing data')else:dates.append(current_date)highs.append(high)lows.append(low)#繪制圖表. fig = plt.figure(dpi=128, figsize=(10, 9)) plt.plot(dates, highs, c='red', alpha=0.5) plt.plot(dates, lows, c='blue', alpha=0.5) #facecolor指定了填充區(qū)域的顏色 plt.fill_between(dates, highs, lows, facecolor='blue', alpha=0.1)title = "Daily high and low temperatures CA" plt.title(title, fontsize=10) plt.xlabel('', fontsize=6) fig.autofmt_xdate() plt.ylabel("Temperature (F)", fontsize=6) plt.tick_params(axis='both', which='major', labelsize=6)plt.show()?
轉(zhuǎn)載于:https://www.cnblogs.com/jzxs/p/10196450.html
《新程序員》:云原生和全面數(shù)字化實(shí)踐50位技術(shù)專(zhuān)家共同創(chuàng)作,文字、視頻、音頻交互閱讀總結(jié)
- 上一篇: 源自KPI交谈的思考
- 下一篇: [转帖]2019 简易Web开发指南