Python编程从入门到实践ver3-Day2

16.1 CSV格式文件

16.1.1 解析CSV格式文件的file header

#sitka_highs.py
from pathlib import Path
import csv


path = Path('weather_data\sitka_weather_07-2021_simple.csv')

#利用splitlines()方法,获得一个包含各行数据的列表,赋值到lines中
lines = path.read_text().splitlines()
#创建reader对象,用于解析文件各行
reader = csv.reader(lines)
#next()函数用于读取下一行,在本代码中第一次出现,所以是读取第一行
#所以就读取到了file header
header_row = next(reader)
print(header_row)

Bug

上来就出bug了并且解决不了...

提示

FileNotFoundError: [Errno 2] No such file or directory: 'weather_data\\sitka_weather_07-2021_simple.csv'

我绝对已经放在同一目录下了,并且还尝试了绝对目录和Pandas方法引用csv文件,依然都是同样的报错

实在解决不了了,把完整报错放在这里,如果有看到的大神感谢解答!

(所以后面代码只是对书的写代码练习了,没有跑出结果尝试,估计会有很多bug...)

PS D:\.../weather_data/test.py
Traceback (most recent call last):
  File "c:\Users\...\weather_data\test.py", line 7, in <module>
    lines = path.read_text().splitlines()
            ^^^^^^^^^^^^^^^^
  File "C:\Users\...\Python\Python312\Lib\pathlib.py", line 1027, in read_text
    with self.open(mode='r', encoding=encoding, errors=errors) as f:
         ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users...\Python\Python312\Lib\pathlib.py", line 1013, in open
    return io.open(self, mode, buffering, encoding, errors, newline)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
FileNotFoundError: [Errno 2] No such file or directory: 'weather_data\\sitka_weather_07-2021_simple.csv'

16.1.2 打印file header和位置

#利用splitlines()方法,获得一个包含各行数据的列表,赋值到lines中
lines = path.read_text().splitlines()
#创建reader对象,用于解析文件各行
reader = csv.reader(lines)
#next()函数用于读取下一行,在本代码中第一次出现,所以是读取第一行
#所以就读取到了file header
header_row = next(reader)


#for循环遍历header_row列表,用enumerate()获得每个元素的索引及其值
for index,column_header in enumerate(header_row):
    print(index,column_header)

16.1.3 提取并读取数据

#sitka_highs.py
from pathlib import Path
import csv


path = Path('weather_data\sitka_weather_07-2021_simple.csv')

#利用splitlines()方法,获得一个包含各行数据的列表,赋值到lines中
lines = path.read_text().splitlines()
#创建reader对象,用于解析文件各行
reader = csv.reader(lines)
#next()函数用于读取下一行,在本代码中第一次出现,所以是读取第一行
#所以就读取到了file header
header_row = next(reader)

#提取最高气温和日期
highs = []
for row in reader:
    high = int(row[4])
    highs.append(high)

print(highs)

16.1.4 绘制温度图

#sitka_highs.py
from pathlib import Path
import csv

import matplotlib.pyplot as plt

path = Path('weather_data\sitka_weather_07-2021_simple.csv')

#利用splitlines()方法,获得一个包含各行数据的列表,赋值到lines中
lines = path.read_text().splitlines()
#创建reader对象,用于解析文件各行
reader = csv.reader(lines)
#next()函数用于读取下一行,在本代码中第一次出现,所以是读取第一行
#所以就读取到了file header
header_row = next(reader)

#提取最高气温和日期
highs = []
for row in reader:
    high = int(row[4])
    highs.append(high)

#根据最高温度绘图
plt.style.use('seaborn')
fig,ax=plt.subplots()
ax.plot(highs,color='red')

ax.set_title("Daily High Temperatures, July 2021",fontsize=24)
ax.set_xlabel('',fontsize=16)
ax.set_ylabel("Temperature (F)",fontsize=16)
ax.tick_params(labelsize=16)

plt.show()

 16.1.6 添加日期

#sitka_highs.py
from pathlib import Path
import csv

import matplotlib.pyplot as plt

from datetime import datetime

path = Path('weather_data\sitka_weather_07-2021_simple.csv')

#利用splitlines()方法,获得一个包含各行数据的列表,赋值到lines中
lines = path.read_text().splitlines()
#创建reader对象,用于解析文件各行
reader = csv.reader(lines)
#next()函数用于读取下一行,在本代码中第一次出现,所以是读取第一行
#所以就读取到了file header
header_row = next(reader)

#提取最高气温和日期
dates, highs =[], []
for row in reader:
    current_date = datetime.strptime(row[2],'%Y-%m-%d')
    high = int(row[4])
    dates.append(current_date)
    highs.append(high)

#根据最高温度绘图
plt.style.use('seaborn')
fig,ax=plt.subplots()
ax.plot(dates,highs,color='red')

ax.set_title("Daily High Temperatures, July 2021",fontsize=24)
ax.set_xlabel('',fontsize=16)

fig.autofmt_xdate

ax.set_ylabel("Temperature (F)",fontsize=16)
ax.tick_params(labelsize=16)

plt.show()

 16.1.8 再绘制一个数据系列-添加最低温

#sitka_highs_lows.py
from pathlib import Path
import csv

import matplotlib.pyplot as plt

from datetime import datetime

path = Path('weather_data\sitka_weather_07-2021_simple.csv')

#利用splitlines()方法,获得一个包含各行数据的列表,赋值到lines中
lines = path.read_text().splitlines()
#创建reader对象,用于解析文件各行
reader = csv.reader(lines)
#next()函数用于读取下一行,在本代码中第一次出现,所以是读取第一行
#所以就读取到了file header
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)


#根据最高温度绘图
plt.style.use('seaborn')
fig,ax=plt.subplots()
ax.plot(dates,highs,color='red')
ax.plot(dates,lows,color='blue')

ax.set_title("Daily High&Low Temperatures, July 2021",fontsize=24)
ax.set_xlabel('',fontsize=16)

fig.autofmt_xdate

ax.set_ylabel("Temperature (F)",fontsize=16)
ax.tick_params(labelsize=16)

plt.show()

16.1.9 给图中区域着色

#sitka_highs_lows.py
from pathlib import Path
import csv

import matplotlib.pyplot as plt

from datetime import datetime

path = Path('weather_data\sitka_weather_07-2021_simple.csv')

#利用splitlines()方法,获得一个包含各行数据的列表,赋值到lines中
lines = path.read_text().splitlines()
#创建reader对象,用于解析文件各行
reader = csv.reader(lines)
#next()函数用于读取下一行,在本代码中第一次出现,所以是读取第一行
#所以就读取到了file header
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)


#根据最高温度绘图
plt.style.use('seaborn')
fig,ax=plt.subplots()
ax.plot(dates,highs,color='red',alpha=0.5)
ax.plot(dates,lows,color='blue',alpha=0.5)
#alpah实参指定颜色透明度,0为透明,1为完全不透明(默认0
ax.fill_between(dates,highs,lows,facecolor='blue',alpha=0.1)


ax.set_title("Daily High Temperatures, July 2021",fontsize=24)
ax.set_xlabel('',fontsize=16)

fig.autofmt_xdate

ax.set_ylabel("Temperature (F)",fontsize=16)
ax.tick_params(labelsize=16)

plt.show()

16.2 GeoJSON格式文件

16.2.2  查看GeoJSON数据

#eq_expplore_data.py
from pathlib import Path
import json

#将数据作为字符串读取并转换为Python对象
path = Path('eq_data/eq_data_1_day_m1.geojson')
contents = path.read_text()
#json.load()将整个数据集转换为python对象
#转换为字典,赋值给all_equal_data
all_equal_data = json.loads(contents)


#将数据转换为更容易阅读的版本
path = Path('eq_data/readable_eq_data.geojson')
readable_contents = json.dumps(all_equal_data,indent=4)
path.write_text(readable_contents)

16.2.3 创建地震列表

#eq_expplore_data.py
from pathlib import Path
import json

#将数据作为字符串读取并转换为Python对象
path = Path('eq_data/eq_data_1_day_m1.geojson')
contents = path.read_text()
#json.load()将整个数据集转换为python对象
#转换为字典,赋值给all_equal_data
all_equal_data = json.loads(contents)

#查看数据集里的所有地震
#从字典all_eq_data中提取和key 'features'相关联的数据,将其赋值给变量all_eq_dicts
all_equal_dicts = all_equal_data['features']
print(len(all_equal_dicts))

16.2.4 提取震级

#eq_expplore_data.py
from pathlib import Path
import json

#将数据作为字符串读取并转换为Python对象
path = Path('eq_data/eq_data_1_day_m1.geojson')
contents = path.read_text()
#json.load()将整个数据集转换为python对象
#转换为字典,赋值给all_equal_data
all_equal_data = json.loads(contents)

#查看数据集里的所有地震
#从字典all_eq_data中提取和key 'features'相关联的数据,将其赋值给变量all_eq_dicts
all_equal_dicts = all_equal_data['features']
print(len(all_equal_dicts))


mags=[]
for eq_dict in all_equal_dicts:
    mag = eq_dict['properties']['mag']
    mags.append(mag)


print (mags[:10])

16.2.5 提取位置数据

#eq_expplore_data.py
from pathlib import Path
import json

#将数据作为字符串读取并转换为Python对象
path = Path('eq_data/eq_data_1_day_m1.geojson')
contents = path.read_text()
#json.load()将整个数据集转换为python对象
#转换为字典,赋值给all_equal_data
all_equal_data = json.loads(contents)

#查看数据集里的所有地震
#从字典all_eq_data中提取和key 'features'相关联的数据,将其赋值给变量all_eq_dicts
all_equal_dicts = all_equal_data['features']
print(len(all_equal_dicts))


mags,titles,lons,lats=[],[],[],[]
for eq_dict in all_equal_dicts:
    mag = eq_dict['properties']['mag']
    title = eq_dict['properties']['title']
    lon=eq_dict['geometry']['coordinates'][0]
    lat=eq_dict['geometry']['coordinates'][1]
    mags.append(mag)
    titles.append(title)
    lons.append(lon)
    lats.append(lat)

print (mags[:10])
print(titles[:2])
print(lons[:5])
print(lats[:5])

16.2.6 绘制地震散点图

#eq_world_map.py

import plotly.express as px

#eq_expplore_data.py
from pathlib import Path
import json

#将数据作为字符串读取并转换为Python对象
path = Path('eq_data/eq_data_1_day_m1.geojson')
contents = path.read_text()
#json.load()将整个数据集转换为python对象
#转换为字典,赋值给all_equal_data
all_equal_data = json.loads(contents)

#查看数据集里的所有地震
#从字典all_eq_data中提取和key 'features'相关联的数据,将其赋值给变量all_eq_dicts
all_equal_dicts = all_equal_data['features']
print(len(all_equal_dicts))


mags,titles,lons,lats=[],[],[],[]
for eq_dict in all_equal_dicts:
    mag = eq_dict['properties']['mag']
    title = eq_dict['properties']['title']
    lon=eq_dict['geometry']['coordinates'][0]
    lat=eq_dict['geometry']['coordinates'][1]
    mags.append(mag)
    titles.append(title)
    lons.append(lon)
    lats.append(lat)

print (mags[:10])
print(titles[:2])
print(lons[:5])
print(lats[:5])

fig=px.scatter(
    x=lons,
    y=lats,
    labels={'x':'经度','y':'纬度'},
    range_x=[-200,200],
    range_y=[-90,90],
    width=800,
    height=800,
    title='全球地震散点图',
)
fig.write_html('global_earthquakes.html')
fig.show()

16.2.8 定制标记的尺寸

#eq_world_map.py

import plotly.express as px

#eq_expplore_data.py
from pathlib import Path
import json

#将数据作为字符串读取并转换为Python对象
path = Path('eq_data/eq_data_1_day_m1.geojson')
contents = path.read_text()
#json.load()将整个数据集转换为python对象
#转换为字典,赋值给all_equal_data
all_equal_data = json.loads(contents)

#查看数据集里的所有地震
#从字典all_eq_data中提取和key 'features'相关联的数据,将其赋值给变量all_eq_dicts
all_equal_dicts = all_equal_data['features']
print(len(all_equal_dicts))


mags,titles,lons,lats=[],[],[],[]
for eq_dict in all_equal_dicts:
    mag = eq_dict['properties']['mag']
    title = eq_dict['properties']['title']
    lon=eq_dict['geometry']['coordinates'][0]
    lat=eq_dict['geometry']['coordinates'][1]
    mags.append(mag)
    titles.append(title)
    lons.append(lon)
    lats.append(lat)

print (mags[:10])
print(titles[:2])
print(lons[:5])
print(lats[:5])

fig=px.scatter(
    x=lons,
    y=lats,
    labels={'x':'经度','y':'纬度'},
    range_x=[-200,200],
    range_y=[-90,90],
    width=800,
    height=800,
    title='全球地震散点图',
    size='震级',
    size_max=20,
)
fig.write_html('global_earthquakes.html')
fig.show()

16.2.9 定制标记的颜色

#eq_world_map.py

import plotly.express as px

#eq_expplore_data.py
from pathlib import Path
import json

#将数据作为字符串读取并转换为Python对象
path = Path('eq_data/eq_data_30_day_m1.geojson')
try:
    contents = path.read_text()
except:
    contents = path.read_text(encoding='utf-8')

contents = path.read_text()
#json.load()将整个数据集转换为python对象
#转换为字典,赋值给all_equal_data
all_equal_data = json.loads(contents)

#查看数据集里的所有地震
#从字典all_eq_data中提取和key 'features'相关联的数据,将其赋值给变量all_eq_dicts
all_equal_dicts = all_equal_data['features']
print(len(all_equal_dicts))


mags,titles,lons,lats=[],[],[],[]
for eq_dict in all_equal_dicts:
    mag = eq_dict['properties']['mag']
    title = eq_dict['properties']['title']
    lon=eq_dict['geometry']['coordinates'][0]
    lat=eq_dict['geometry']['coordinates'][1]
    mags.append(mag)
    titles.append(title)
    lons.append(lon)
    lats.append(lat)

print (mags[:10])
print(titles[:2])
print(lons[:5])
print(lats[:5])

fig=px.scatter(
    x=lons,
    y=lats,
    labels={'x':'经度','y':'纬度'},
    range_x=[-200,200],
    range_y=[-90,90],
    width=800,
    height=800,
    title='全球地震散点图',
    size='震级',
    size_max=20,
    color='震级',
)
fig.write_html('global_earthquakes.html')
fig.show()

16.2.10 其他渐变

#其他渐变
import plotly.express as px
px.colors.named_colorscales()

16.2.11 增加悬停文本

#eq_world_map.py

import plotly.express as px

#eq_expplore_data.py
from pathlib import Path
import json

#将数据作为字符串读取并转换为Python对象
path = Path('eq_data/eq_data_30_day_m1.geojson')
try:
    contents = path.read_text()
except:
    contents = path.read_text(encoding='utf-8')

contents = path.read_text()
#json.load()将整个数据集转换为python对象
#转换为字典,赋值给all_equal_data
all_equal_data = json.loads(contents)

#查看数据集里的所有地震
#从字典all_eq_data中提取和key 'features'相关联的数据,将其赋值给变量all_eq_dicts
all_equal_dicts = all_equal_data['features']
print(len(all_equal_dicts))


mags,titles,lons,lats=[],[],[],[]
for eq_dict in all_equal_dicts:
    mag = eq_dict['properties']['mag']
    title = eq_dict['properties']['title']
    lon=eq_dict['geometry']['coordinates'][0]
    lat=eq_dict['geometry']['coordinates'][1]
    mags.append(mag)
    titles.append(title)
    lons.append(lon)
    lats.append(lat)

print (mags[:10])
print(titles[:2])
print(lons[:5])
print(lats[:5])

fig=px.scatter(
    x=lons,
    y=lats,
    labels={'x':'经度','y':'纬度'},
    range_x=[-200,200],
    range_y=[-90,90],
    width=800,
    height=800,
    title='全球地震散点图',
    size='震级',
    size_max=20,
    color='震级',
#增加悬停文本
    hover_name='位置',
)
fig.write_html('global_earthquakes.html')
fig.show()

 Summary:

        1. 最失败的一天,两个小时的时间一直在解决ERROR2的问题并且甚至一直没找到解决办法,希望有路过的大神能够帮忙解决这个问题

        2. 可视化的基础,涉及到了基础美化和heatmap的代码基础~后面做数据挖掘和分析还得继续做,也希望有路过的大神能够给一个数据挖掘和分析的学习路径!之前浅薄地学习了R,现在浅薄地学习了Python...感恩!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值