數(shù)據(jù)以兩種常見格式存儲:CSV
和JSON
CSV文件格式
comma-separated values
import csv
filename = 'sitka_weather_07-2018_simple.csv'
with open(filename) as f:
reader = csv.reader(f)
header_row = next(reader)
print(header_row)
# ['USW00025333', 'SITKA AIRPORT, AK US', '2018-01-01', '0.45', '', '48', '38']
for index, column_header in enumerate(header_row):
# 打印文件位置和文件頭
print(index, column_header)
0 USW00025333
1 SITKA AIRPORT, AK US
2 2018-01-01
3 0.45
4
5 48
6 38
csv.reader()
:將前面存儲的文件對象作為實參傳遞給它,創(chuàng)建一個與該文件相關(guān)聯(lián)的閱讀器對象
next()
返回文件中的下一行
第一次調(diào)用該函數(shù),返回第一行,依次增加
enumerate()
函數(shù)可以將一個可迭代對象轉(zhuǎn)換為一個枚舉對象,返回的枚舉對象包含每個元素的索引和對應(yīng)的元素值
enumerate(iterable, start=0)
-
iterable
:必需,表示要枚舉的可迭代對象 -
start
:可選,表示元素索引的起始值
[‘STATION’, ‘NAME’, ‘DATE’, ‘PRCP’, ‘TAVG’, ‘TMAX’, ‘TMIN’]
STATION 記錄數(shù)據(jù)的氣象站的編碼
NAME 氣象站的名稱
TMAX 最高溫度 TMIN 最低溫度
獲取某一列的值
filename = 'sitka_weather_07-2021_simple.csv'
with open(filename) as f:
reader = csv.reader(f)
header_row = next(reader) # 該文件第一行是"STATION","NAME","DATE","TAVG","TMAX","TMIN",沒有數(shù)字溫度,使用next跳過改行
# 從文件中獲取最高溫度
highs = []
for row in reader:
high = int(row[5]) # 文件里的數(shù)據(jù)都是以字符串格式儲存的
highs.append(high)
print(highs)
# [53, 52, 54, 55, 55, 54, 53, 53, 53, 51, 51, 54, 52, 51, 50, 54, 56, 57, 55, 56, 54, 55, 56, 54, 52, 49, 57, 52, 52, 60, 48]
繪制溫度圖表
import matplotlib.pyplot as plt
from matplotlib.font_manager import FontProperties
font = FontProperties(fname='msyh.ttc', size=14) # 假設(shè)選擇msyh字體,大小為14
# 根據(jù)最高溫度繪制圖形。
plt.style.use('seaborn')
fig, ax = plt.subplots()
ax.plot(highs, c='red')
# 設(shè)置圖形的格式。
ax.set_title("2018年7月每日最高溫度", fontsize=24,fontproperties=font)
ax.set_xlabel('', fontsize=16)
ax.set_ylabel("溫度 (F)", fontsize=16,fontproperties=font)
ax.tick_params(axis='both', which='major', labelsize=16)
plt.show()
labelsize
xy軸上的數(shù)字的大小
模塊datetime 將字符串轉(zhuǎn)為日期
from datetime import datetime
first_date = datetime.strptime('2018-07-01', '%Y-%m-%d')
print(first_date) # 2018-07-01 00:00:00
# first_date # datetime.datetime(2018, 7, 1, 0, 0)
實參 | 含義 |
---|---|
%A | 星期幾,如Monday |
%B | 月份名,如January |
%m | 用數(shù)表示的月份(01~12) |
%d | 用數(shù)表示的月份中的一天(01~31) |
%Y | 四位的年份,如2019 |
%y | 兩位的年份,如19 |
%H | 24小時制的小時數(shù)(00~23) |
%I | 12小時制的小時數(shù)(01~12) |
%p | am或pm |
%M | 分鐘數(shù)(00~59) |
%S | 秒數(shù)(00~61) |
在圖表中添加日期
import csv
from datetime import datetime
import matplotlib.pyplot as plt
from matplotlib.font_manager import FontProperties
font = FontProperties(fname='msyh.ttc', size=14)
filename = 'sitka_weather_07-2021_simple.csv'
with open(filename) as f:
reader = csv.reader(f)
header_row = next(reader)
# 從文件中獲取日期和最高溫度
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("2021年7月每日最高溫度", fontsize=24,fontproperties=font)
ax.set_xlabel('', fontsize=16)
fig.autofmt_xdate()
ax.set_ylabel("溫度 (F)", fontsize=16,fontproperties=font)
ax.tick_params(axis='both', which='major', labelsize=16)
# which可以接收三個值: 'major', 'minor', 'both'
plt.show()
fig.autofmt_xdate()
:繪制傾斜的日期標簽
ax.tick_params()
是用來設(shè)置坐標軸刻度線和刻度標簽的屬性的函數(shù)
axis='both’表示要設(shè)置x軸和y軸的刻度線和刻度標簽的屬性
which='major’表示要設(shè)置的是主刻度線和刻度標簽的屬性,即顯示刻度值的那些刻度線和刻度標簽
涵蓋更長的時間
filename = 'sitka_weather_2021_simple.csv'
with open(filename) as f:
reader = csv.reader(f)
header_row = next(reader)
# 從文件中獲取日期和最高溫度和最低溫度
dates, highs, lows = [], [], []
for row in reader:
current_date = datetime.strptime(row[2], '%Y-%m-%d')
high = int(row[4])
low = int(row[5])
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')
ax.plot(dates, lows, c='blue')
# 設(shè)置圖形的格式
ax.set_title("2021年每日最高溫度", fontsize=24,fontproperties=font)
ax.set_xlabel('', fontsize=16)
fig.autofmt_xdate()
ax.set_ylabel("溫度 (F)", fontsize=16,fontproperties=font)
ax.tick_params(axis='both', which='major', labelsize=16)
plt.show()
給圖表區(qū)域著色
方法fill_between()
# 根據(jù)最高溫度繪制圖形
plt.style.use('seaborn')
fig, ax = plt.subplots()
ax.plot(dates, highs, c='red', alpha=1)
ax.plot(dates, lows, c='blue', alpha=0.5)
ax.fill_between(dates, highs, lows, facecolor='blue', alpha=0.1)
錯誤檢查
數(shù)據(jù)缺失
try-except-else 代碼塊
continue跳過數(shù)據(jù)
remove() 或del 刪除數(shù)據(jù)
filename = 'death_valley_2021_simple.csv'
with open(filename) as f:
reader = csv.reader(f)
header_row = next(reader)
# 從文件中獲取日期和最高溫度
dates, highs, lows = [], [], []
for row in reader:
current_date = datetime.strptime(row[2], '%Y-%m-%d')
try:
high = int(row[4])
low = int(row[5])
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(figsize=(15, 9))
ax.plot(dates, highs, c='red', alpha=1)
ax.plot(dates, lows, c='blue', alpha=0.5)
ax.fill_between(dates, highs, lows, facecolor='blue', alpha=0.1)
# 設(shè)置圖形的格式
title = "2018年每日最高溫度和最低溫度\n美國加利福尼亞州死亡谷"
ax.set_title(title, fontsize=20,fontproperties=font)
ax.set_xlabel('', fontsize=16)
fig.autofmt_xdate()
ax.set_ylabel("溫度 (F)", fontsize=16,fontproperties=font)
ax.tick_params(axis='both', which='major', labelsize=16)
plt.show()
文章來源:http://www.zghlxwxcb.cn/news/detail-684860.html
調(diào)整圖表大小
figsize
單位為英寸文章來源地址http://www.zghlxwxcb.cn/news/detail-684860.html
fig, ax = plt.subplots(figsize=(8, 5))
到了這里,關(guān)于python-數(shù)據(jù)可視化-下載數(shù)據(jù)-CSV文件格式的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!